0
我有一個問題,我寫了和平的Djnago代碼,爲用戶上傳配置文件圖片,從管理區域模型工作正常,但從網站本身圖像不能上傳,似乎代碼是不均勻的被稱爲。這裏是我的代碼,你可以檢查並告訴我什麼可能是錯的?Django ImageField上傳的問題
models.py:
from django.conf import settings
from django.db import models
from django.core.files import File
def upload_location(instance, filename):
location = str(instance.user.id)
return "%s/%s" %(location, filename)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
def __unicode__(self):
return unicode(self.user.id)
forms.py:
from django import forms
from .models import ProfilePicture
class ProfileEditPicture(forms.ModelForm):
class Meta:
model = ProfilePicture
fields = [
"profile_picture"
]
views.py:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture
@login_required()
def profile_picture(request, id):
user = get_object_or_404(User, id=id)
title = "Profile Edit"
profile, created = Profile.objects.get_or_create(user=user)
form = ProfileEditPicture(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
context = {
"form":form,
"title":title,
"profile":profile
}
return render(request, "profile/form.html", context)
urls.py:
urlpatterns = [
...
url(r'^profile_picture/(?P<id>[\[email protected]+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模板中的HTML代碼是默認的django表單。
感謝提前:)
已包含'ENCTYPE = 「的multipart/form-data的」'? – Wtower
我應該在哪裏包括?在forms.py中?我必須導入一些東西才能使用它? – Tadas