我的图片上传存在问题。目前,所选图像文件未复制到目标目录,并且此文件的路径未添加到数据库中。
我在下面给出了我的代码:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(upload_to="avatar/")
form.py
class ProfileEditionForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user')
view.py:
def index(request):
if request.user.is_authenticated():
user = User.objects.get(pk=request.user.id)
if request.method == "POST":
form = ProfileEditionForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
#return HttpResponseRedirect(reverse('profile_edit'))
else:
form = ProfileEditionForm(instance=user)
return direct_to_template(request, 'profile_edit.html', { 'form' : form })
else:
return HttpResponseRedirect(reverse('main_page'))
提前感谢您的帮助。
答案 0 :(得分:2)
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
你的表单应该有enctype =“multipart / form-data”或request.FILES不会有任何数据流关联
答案 1 :(得分:1)
您的ModelForm绑定到UserProfile模型,但您使用instance = user实例化它。
PS:request.user是User.objects.get(pk = request.user.id)