(1048,"列' user_id'不能为空")提交表单时 - Django

时间:2017-12-21 20:41:34

标签: django forms

当我尝试上传图片时,我收到错误(1048,"列' user_id'不能为空")但是,没有user_id列。我尝试设置user = models.OneToOneField(null = False),但它不起作用。

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    description = models.CharField(max_length=140, default='')
    city = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    image = models.ImageField(upload_to='profile_image', default='profile_image/Default.jpg')

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

forms.py

class UpdateBioForm(forms.ModelForm):
    image = forms.ImageField()

    class Meta:
        model = UserProfile
        fields = (
            'image',
            'city',
            'website',
            'description',
        )
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4, 'cols': 15}),
        }

    def save(self, commit=True):
        savedBio = super(UpdateBioForm, self).save(commit=False)
        savedBio.image = self.cleaned_data['image']
        savedBio.city = self.cleaned_data['city']
        savedBio.website = self.cleaned_data['website']
        savedBio.description = self.cleaned_data['description']


        if commit:
            savedBio.save()

        return savedBio

views.py

def update_bio(request):
    if request.method == 'POST':
        form = UpdateBioForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = UpdateBioForm(instance=request.user)
    args = {'form': form}
    return render(request, 'accounts/update_bio.html', context=args)

1 个答案:

答案 0 :(得分:0)

您应该更改非POST案例以传递UserProfile而不是User对象,可能如下:

else:
    profile = UserProfile.objects.get(user=request.user)
    form = UpdateBioForm(instance=profile)

另外,我认为你不需要重新编写所有save逻辑,这些都是使用ModelForm的本质。