保存ModelForm时,列中的null值违反非空约束

时间:2015-02-19 18:32:51

标签: python django modelform

我有一个扩展django User模型的模型:

class UserProfile(models.Model): 
    user = models.OneToOneField(User, verbose_name="user details")
    rewardpoints = models.IntegerField("rewardpoints") 

    def __str__(self):  
          return "%s's profile" % self.user.username  

my forms.py

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ['rewardpoints']

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']

我的view.py

class UserProfileFormView(View):
    def post(self, request, *args, **kwargs):
        userform = UserForm(request.POST, prefix='users')
        userprofileform = UserProfileForm(request.POST, prefix='userprofiles')
        if userform.is_valid() and userprofileform.is_valid():
            new_user = userform.save() #### Error over here.
            new_userprofile = userprofileform.save(commit=False)
            new_userprofile.user = new_user
            new_userprofile.save()
            return HttpResponseRedirect(reverse('users:welcome'))
        else:
            userform = UserForm(prefix='users')
            userprofileform = UserProfileForm(prefix='userprofiles')
            return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
    def get(self, request, *args, **kwargs):
        userform = UserForm(prefix='users')
        userprofileform = UserProfileForm(prefix='userprofiles')    
        return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})

我的signup.html

<p> Hello Signup!! </p>
<form action="{% url 'users:signup' %}" method="post">
{% csrf_token %}
{{ user_form.username.label_tag }}
{{ user_form.username }}
{{ user_form.password.label_tag }}
{{ user_form.password }}
{{ userprofile_form }}
<input type="submit" value="Submit" />
</form>
</html>

但在发布帖子请求时,会出现此错误:null value in column "rewardpoints" violates not-null constraint

请告诉我一个方法。

1 个答案:

答案 0 :(得分:0)

错误是因为您的字段rewardpoints需要一些值,它不能为空,所以,或者通过表单将值传递给rewardpoint,或者您可以为其设置默认值(推荐)。然后,当您创建userprofile时,表单将设置0作为初始值。

class UserProfile(models.Model): 
    user = models.OneToOneField(User, verbose_name="user details")
    rewardpoints = models.IntegerField(default=0)