我正在尝试在注册用户后创建用户个人资料。在此配置文件中,我需要上传图像。但是在验证图像时我一直收到KeyError。
经过几个小时的谷歌搜索和尝试不同的解决方案,我现在卡住了。有人可以告诉我我做错了什么吗?提前谢谢。
models.py
class Profile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE)
slug = models.SlugField(default='',
editable=False)
picture = models.ImageField('Profile picture',
upload_to='profile_pics/%Y-%m-%d/',
null=True,
blank=True)
bio = models.CharField("Short Bio", max_length=200, blank=True, null=True)
email_verified = models.BooleanField("Email verified", default=False)
views.py
from .models import Profile
from .forms import ProfileForm
class CreateProfile(FormView):
model = Profile
template_name = 'profiles/profile_form.html'
form_class = ProfileForm
fields = ['picture', 'bio']
def get_success_url(self):
return reverse('profiles:detail', kwargs={'slug': self.slug})
def form_valid(self, form):
profile = form.save(commit=False)
image = form.cleaned_data['image']
obj.user = self.request.user
profile.save()
return HttpResponseRedirect(self.get_success_url())
forms.py
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['picture', 'bio',]
回溯:
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in post
183. return self.form_valid(form)
File "/home/xxxxxxxxxx/xxxxxxxx/xxxxxxx/template/profiles/views.py" in form_valid
28. image = form.cleaned_data['image']
Exception Type: KeyError at /profiles/create/
Exception Value: 'image'
答案 0 :(得分:1)
错误在于:
def form_valid(self, form):
profile = form.save(commit=False)
image = form.cleaned_data['image']
obj.user = self.request.user
profile.save()
你试图获得图像'来自form.cleaned_data
,而您的头像字段被称为picture
。
所以,替换
image = form.cleaned_data['image']
与
image = form.cleaned_data['picture']