/ accounts / regist_save /发生的IntegrityError

时间:2017-12-09 14:34:36

标签: javascript python html django

/ accounts / regist_save /的IntegrityError NOT NULL约束失败:accounts_newuser.user_id 错误发生。我在

中写道

views.py

def regist(request):
    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)
    context = {
        'regist_form': regist_form,
        'profile_form': profile_form, 
    }
    return render(request, 'registration/regist.html', context)

@require_POST
def regist_save(request):

    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)

    if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
                regist = regist_form.save(commit=False)
                regist.is_staff = True
                regist.save()

                profile = profile_form.save(commit=False)
                sex = request.POST.get("sex", "")
                print(1111)
                print(sex)
                profile.save()
    else:
        print(regist_form.errors)
        print(profile_form.errors)
    return redirect('detail')

regist.html

 <div class="form-group-lg">

    <label for="id_username">Username</label>

    {{ regist_form.username }}

  </div>

  <div class="form-group-lg">

    <label for="id_email">Email</label>

    {{ regist_form.email }}
  </div>

  <div class="form-group-lg">

    <label for="id_password">Password</label>

    {{ regist_form.password1 }}

  </div>



  <div class="form-group-lg">
    <label for="id_password">Password2</label>

    {{ regist_form.password2 }}
    <p class="help-block">{{ regist_form.password2.help_text }}</p>

  </div>



  {% load static %}
  <div class="form-group-lg">
    <label for="birthday">Date</label>

    <select id="year" class="form-control year" name="year">
      <option value="">--</option>
    </select>
    Year
    <select id="month" class="form-control month" name="month">
      <option value="">--</option>
    </select>
    Month
    <select id="day" class="form-control day" name="day">
      <option value="">--</option>
    </select>
    Day
    <br>
    <br>
  </div>

  <div class="form-group-lg">
    <label for="sex">SEX</label>
    <select id="sex" class="form-control sex" name="sex">
      <option value="">--</option>
      <option value="male">male</option>
      <option value="female">female</option>
    </select>
  </div>


  <script src="{% static 'accounts/register.js' %}"></script>


      <button type="submit" class="btn-lg regist">REGIST</button>

      <input name="next" type="hidden" />

  {% csrf_token %}

</form>

regist.js

$(() => {
    for (let i = 1900; i < 2020; i++) {
        $("#year").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 12; i++) {
        $("#month").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 31; i++) {
        $("#day").append(`<option value="${i}">${i}</option>`);
    }
})

models.py

from django.db import models
from django.contrib.auth.models import User

    class NewUser(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
        sex = models.CharField(max_length=100,null=True, blank=True, default=None)

在forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser

class RegisterForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email','password1','password1',)
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

class ProfileForm(forms.ModelForm):
    class Meta:
        model = NewUser
        fields = (
            "birthday", "sex"
        )

我真的无法理解为什么会发生这种错误,因为我没有在NewUser模型中编写user_id。我认为完整性错误意味着在Model.OneToOneField中找不到列可以与用户和NewUser的模型连接。我认为这个错误意味着我应该在新用户模型中准备user_id,但如果我的想法是正确的,我无法理解为什么。我该如何解决这个问题?我该怎么写呢?

1 个答案:

答案 0 :(得分:0)

这是因为在NewUser模型中,用户字段是必填字段。在ProfileForm中,不包括用户字段。因此,当ProfileForm尝试在没有用户附加的情况下保存NewUser时,会导致上述错误。

我们要做的是在实际保存之前将用户附加到实例:

profile = profile_form.save(commit=False)
profile.user = registered_user # you can get the user from the registerform above
profile.save()