获取下拉列表ID并使用python django保存到view.py文件中

时间:2018-07-18 06:45:38

标签: python django

这是我的 models.py 文件

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    join_date = models.DateField(default=datetime.today())
    end_date = models.DateField(default=datetime.today() + timedelta(days=7))
    package_status = models.BooleanField(default=True,blank=True)
    phone_number = models.CharField(max_length=30, blank=True)
    idboard= models.CharField(max_length=30, blank=True)

 @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

instance.profile.save()

这是我的 forms.py 文件

class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    phone_number = forms.CharField(help_text='Required. Format: 03001234567')
    idboard = forms.ModelChoiceField(queryset=Board_TB.objects.filter(pk__in=b[1,2]),required=False)

    class Meta:
        model = User
        fields = ('username', 'email','password1', 'password2','phone_number','idboard')

这是我的 views.py 文件

def signup(request):

    if request.method == 'POST':  
        form = SignUpForm(request.POST) 
        if form.is_valid():

            user = form.save()
            user.refresh_from_db()  

            user.profile.phone_number = form.cleaned_data.get('phone_number')
            user.profile.idboard = form.cleaned_data.get('idboard')
            user.save()

            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)

            return redirect('index')    
    else:
        form = SignUpForm()

    return render(request, 'accounts/signup.html',{'form' : form,})

但是我遇到了这个错误:

  

/ accounts / signup /中的IntegrityError       (“ 23000”,“ [23000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]无法将值NULL插入表的“ idboard”列中   'edxlinkdb.dbo.accounts_profile';列不允许为空。更新   失败。 (515)(SQLExecDirectW); [23000] [Microsoft] [SQL Server本机   客户端11.0] [SQL Server]该语句已终止。 (3621)“)

0 个答案:

没有答案