Django 表单无效

Django Form getting invalid

我是 Django 的新手。进入新版本后,我在表格方面遇到了一些麻烦。关注,

1、型号

class UserProfileDetails(models.Model):

user = models.OneToOneField(User)
profilePicture = models.ImageField('Profile Picture',upload_to='static/ProfilePic/', null=True,blank=True)

def __str__(self):
    return self.user.username

2、形式

class imageUploadForm(forms.ModelForm):
class Meta:
    model=  UserProfileDetails
    fields = ['user','profilePicture']

3、最后是视图函数

def upload_pic(request):
current_user = request.user
if request.method == 'POST':
    form = imageUploadForm(request.POST, request.FILES)
    if form.is_valid():
        pic = form.cleaned_data['profilePicture']
        m = UserProfileDetails(user= current_user.id,profilePicture=pic)
        m.save()
    else:
        raise NotImplemented("What if the user doesn't have an associated profile?")

return HttpResponseRedirect(reverse('polls:profile'))

此代码适用于 Django 1.8。但是移植到Django 1.10.4之后,表单就失效了。我相信,问题出在 OneToOneField 上。

IMP: 另外,我正在使用pinax账户应用程序进行账户管理。

为什么这个表格越来越无效?

当您提交表单时,似乎没有为两个字段(用户和个人资料图片)提供正确的输入。我的猜测是您没有通过用户发送表单,这意味着它是无效的。所以你只是上传图片。

您不需要在表单字段属性中包含 'user',因为您已经在视图中使用 'request.user' 访问了该属性。所以从表单中删除 'user' 字段。

此外,为确保它是正确的,请将 'user=current_user.id' 更改为 'user=current_user',这样您就可以将实例与实例进行匹配,而不是将实例与 id 进行匹配。