使用UpdateView上传Django文件

使用UpdateView上传Django文件

本文介绍了使用UpdateView上传Django文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried a minimalistic django implementation of generic views to upload profile pictures.

views.py

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

models.py

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

userprofile_form.html

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

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

Everything works fine. Now error message. The website field will be updated properly, and a search button allows to choose a file for upload. However the file never appears in the system and the database field remains empty.

很遗憾,django文档上载了文档()

Unfortunately the django documentation on file upload (https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/) does not include generic views, so I wonder if it is possible at all.

更新:多亏了Alasdair的回答,我更新了模板,使其可以使用

Update: Thanks to Alasdair's answer I updated my template so it works fine now as a minimalistic prototype for picture upload with generic views.

要显示图片,请参见文档说明()再次很有帮助。

To display the picture, instructions of the documentation (https://docs.djangoproject.com/en/1.10/howto/static-files/) are quite helpful again.

另外,必须进行媒体设置才能将文件上传到媒体文件夹。

Also the media settings are necessary to upload the files to the media folder.

settings.py

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 %}


推荐答案

问题在您的模板中。您尚未设置 enctype ,因此 request.FILES 始终为空。应该是:

The problem is in your template. You haven't set enctype, so request.FILES will always be empty. It should be:

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

这篇关于使用UpdateView上传Django文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 14:44