【问题标题】:Uploading image files上传图片文件
【发布时间】:2010-11-07 21:43:36
【问题描述】:

您能帮我在 django 表单的视图上上传图片吗?

模型.py

​​>
class User_Profile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile')
    photo  = models.ImageField(upload_to = 'profiles/', null=True, blank=True)

Forms.py

​​>
class ProfileForm(forms.ModelForm):
        class Meta:
            model = User_Profile
            exclude = ('user')

Views.py

​​>
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, instance=request.user.profile)

        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/panel/correct/')

    else:
        profile_form = ProfileForm(instance=request.user.profile)

我的 html 表单已经包含 enctype="multipart/form-data"

【问题讨论】:

  • 嗨,亚历克斯,您可能需要告诉我们目前什么不适合您。

标签: django file-upload image-upload


【解决方案1】:

你好像不是binding the file data to the form

profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) 

【讨论】:

  • 谢谢,这就是问题所在……这是我第一次在 Django 中使用 Forms……(从 0.96 开始没有使用 django,没有 newforms)
【解决方案2】:

为什么不使用django-avatar 项目(根据示例,我假设您正在考虑将用户头像添加到您的项目中)?

他们有一个非常简洁的解决方案,带有一个额外的标签,可以在第一次显示之前调整图像的大小。您存储原始图像并定义您希望在网站上接受的图像尺寸,其余的会自动为您完成。

【讨论】:

    【解决方案3】:

    这只是关注docs的问题。

    您没有在帖子中使用正确的表单初始化。特别是您缺少 request.FILES 参数:

     form = ProfileForm(request.POST, request.FILES)
    

    上面上传的文件可以从FILES数组中检索到:

     photo_file = request.FILES['photo']
    

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2011-07-21
      • 2014-11-16
      • 2013-09-22
      • 2019-06-22
      相关资源
      最近更新 更多