我尝试了通用视图的简约 django 实现来上传个人资料图片。
views.py
class UpdateProfile(UpdateView):
form_class = UpdateUserProfileForm
model = UserProfile
success_url = reverse_lazy('show_profile')
模型.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']
用户个人资料_表单.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/)不包括通用视图,所以我想知道这是否可能。
Update:感谢 Alasdair 的回答,我更新了我的模板,因此它现在可以作为带有通用视图的图片上传的简约原型正常工作。
要显示图片,请参阅文档说明(https://docs.djangoproject.com/en/1.10/howto/static-files/)再次非常有帮助。
此外,还需要媒体设置才能将文件上传到媒体文件夹。
设置.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)
template
{% if userprofile.picture.url|length > 0 %}
<img src="{{ userprofile.picture.url }}" width="200px">
{% else %}
<img src="{% static "/img/default_profile.jpg" %}" width="200px" />
{% endif %}