django vanilla View 使用 CreateView 创建带有 imagefield 的实例

标签 django image forms

我正在使用 django vanilla View ( https://github.com/tomchristie/django-vanilla-views ) 要编辑模型对象(模型 CreateView),该模型有一个图像字段。

但在创建时它似乎没有保存图像,可能是因为我的使用不标准。

有几件事:

  • 对于模型 ImageField,我使用 upload_to 函数将图像保存到特定目录
  • 创建过程中使用了一些用户不需要填写的信息,因此我使用调度从 url 获取相关对象
  • 在保存之前,在 form_valid 函数中,我使用 form.save(commit=False) ,而不是在保存之前执行一些操作,然后保存对象

代码:

用于 upload_to 的函数

def get_image_path_albumphoto(instance, filename):
    return os.path.join('albums', slugify(str(instance.album)), filename)

模型(至少重要字段):

class AlbumPhoto(models.Model):
    .... some fields ...
    album = models.ForeignKey(Album, blank=False, null=False)
    image = models.ImageField(upload_to=get_image_path_albumphoto, blank=True, null=True)

创建 View :

class AlbumPhotoCreate(CreateView):
    model = AlbumPhoto
    fields=('all the other fields except the album','image')

def dispatch(self, *args, **kwargs):
    self.album = get_object_or_none(Album, id=kwargs['album_id'])
    return super(AlbumPhotoCreate, self).dispatch(*args, **kwargs)    

def get_context_data(self, **kwargs):
    kwargs['album'] = self.album
    return kwargs

def get_form(self, data=None, files=None, **kwargs):
    initial={'some_field':'gets_initialized here'}
    kwargs['initial']=initial
    return  super(AlbumPhotoCreate, self).get_form(data,files, **kwargs)

def get_success_url(self):
    if self.album:
        return 'an url using the album id with %d' % self.album.id
    return reverse_lazy('albumphoto_list')

def form_valid(self, form):
    obj = form.save(commit=False)
    obj.album=self.album
    obj.save()
    success_url= 'some url with the object id as %d' % obj.id
    return HttpResponseRedirect(success_url)  

但图像永远不会使用此代码保存......它在使用 django admin 添加对象时起作用,,,所以它是使用此 CreateView 的东西

更新

我尝试反转我的代码,首先在字段中包含专辑,删除了调度和 form_valid 函数...没有成功...最后删除了初始化...(get_form)也没有成功...这是实际上是 CreateView 的默认用法...所以它可能是 upload_to 函数中的某些内容...(?)

最佳答案

这个问题的答案比这个问题的形成更通用:

普通更新 View 是 GenericModelView 的扩展版本,因此这个问题更为通用,而不是由 django 普通 View 引起的。

要使用表单 View 上传文件,模板中的表单标签应具有:

enctype="multipart/form-data"

例如:

<form method="POST" action="." enctype="multipart/form-data">

关于django vanilla View 使用 CreateView 创建带有 imagefield 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24306556/

相关文章:

javascript - 使用 MVC 5 将图像发送到客户端并在新窗口或选项卡中打开

android - 从图库访问图片时无法设置图片来源-Android

mysql - 按一行中的相似项目对查询进行分组

python - 为了在Django 2.0.2中实现CreateView(CBV),是否需要在我们的项目中实现ModelForm?

使用 numpy 操作数组后 Python OpenCV 绘图错误

php - Symfony2,如何使表单标签类/属性与​​其输入不同?

php - 如何解决 HTTP/1.1 302 Found error when trying to get a contents of a form in php?

django - 摆脱 Django View 中的全局变量?

Django:员工装饰师

python - 为多对多关系形成、创建和更新 View