我有一个个人资料页面,我希望允许用户上传个人资料图片。我可以编辑所有文本,但无法上传图像。如果我通过管理员添加图像,但不通过网站上的用户个人资料页面,它可以工作。请注意,通过管理员创建时 - 它正确上传到我在媒体文件夹中指定的目录(profile_image)。我在模板页面上创建了一些错误处理,但生成的错误是:“'image'属性没有与之关联的文件。”以下是我的代码:
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(default='',max_length=100 )
last_name = models.CharField(default='',max_length=100)
email = models.CharField(max_length=100, default='')
date_birth = models.DateField(default=datetime.datetime.now())
bio = models.TextField(default='')
image = models.ImageField(upload_to='profile_image', blank=True)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
views.py
@login_required
def edit_profile(request):
profile = get_object_or_404(models.UserProfile)
if request.method == 'POST':
form = forms.EditProfileForm(data=request.POST, instance=profile)
if form.is_valid():
form.save()
return redirect('/accounts/profile')
else:
form = forms.EditProfileForm(instance=profile)
args = {'form':form}
return render(request, 'accounts/edit_profile.html', args)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from . import models
class UserProfileForm(forms.ModelForm):
class Meta:
model = models.UserProfile
fields = [
'first_name',
'last_name',
'email',
'date_birth',
'bio',
'image',
]
class EditProfileForm(UserProfileForm):
model = models.UserProfile
fields = [
'first_name',
'last_name',
'email',
'date_birth',
'bio',
'image',
]
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'accounts/media')
edit_profile.html
{% extends "layout.html" %}
{% block title %}User Profile | {{ user }}{{ super }}{% endblock %}
{% block body %}
<h1>My Profile</h1>
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p}}
<button type="submit">Save</button>
</form>
{% endblock %}
答案 0 :(得分:5)
该文件来自 request.FILES
,而不是 request.POST
。在视图中执行以下操作:
form = forms.EditProfileForm(data=request.POST, files=request.FILES, instance=profile)
请参阅documentation on file uploads:
处理此表单的视图将接收
request.FILES
中的文件数据,该字典包含每个FileField
的键(或表单中ImageField
或其他FileField subclass
)。