【问题标题】:Django file upload with UpdateView使用 UpdateView 上传 Django 文件
【发布时间】:2017-02-14 02:51:59
【问题描述】:

我尝试了一个通用视图的简约 django 实现来上传个人资料图片。

views.py

class UpdateProfile(UpdateView):
    form_class = UpdateUserProfileForm
    model = UserProfile
    success_url = reverse_lazy('show_profile')

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='user/img/%Y-%m-%d/', blank=True)

forms.py

class UpdateUserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['website','picture']

userprofile_form.html

<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="{% trans "Save" %}"/>
</form>

一切正常。现在错误消息。网站字段将正确更新,搜索按钮允许选择要上传的文件。但是该文件永远不会出现在系统中,并且数据库字段保持为空。

不幸的是,关于文件上传的 django 文档 (https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/) 不包含通用视图,所以我想知道这是否可能。

更新:感谢 Alasdair 的回答,我更新了我的模板,因此它现在可以作为带有通用视图的图片上传的简约原型。

要显示图片,文档说明(https://docs.djangoproject.com/en/1.10/howto/static-files/)再次很有帮助。

还需要媒体设置才能将文件上传到媒体文件夹。

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = 'absolute-path-to/media'

urls.py

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模板

{% if userprofile.picture.url|length > 0 %}
    <img src="{{ userprofile.picture.url }}" width="200px">
{% else %}
    <img src="{% static "/img/default_profile.jpg" %}" width="200px" />
{% endif %}

【问题讨论】:

    标签: django file-upload django-generic-views


    【解决方案1】:

    问题出在您的模板中。您还没有设置enctype,所以request.FILES 将始终为空。应该是:

    <form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2016-03-15
      • 2011-06-12
      • 2011-03-18
      • 2010-09-23
      • 1970-01-01
      相关资源
      最近更新 更多