2016-10-05 48 views
1

我嘗試了一個簡單的django實現通用視圖來上傳個人資料圖片。Django文件上傳UpdateView

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> 

一切工作正常。現在錯誤消息。網站字段將被正確更新,並且搜索按鈕允許選擇要上傳的文件。但是該文件永遠不會出現在系統中,並且數據庫字段保持爲空。

不幸的是,文件上傳(https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/)的django文檔不包含通用視圖,所以我想知道它是否可能。

更新:感謝麥金太爾的答案,我更新了我的模板,所以它現在正常工作作爲一個簡約的原型與通用視圖圖片上傳。

要顯示圖片,說明文檔(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 %} 

回答

2

的問題是在您的模板。您尚未設置enctype,因此request.FILES將始終爲空。它應該是:

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

太棒了。謝謝。現在一切正常。 – user1491229