使用Django 2.0提交注册后的完整性错误

时间:2018-04-08 20:37:08

标签: python django

注册后我继续收到完整性错误(FOREIGN KEY约束失败)。

from django.db import models
from .user import User
from django.core.validators import RegexValidator
from django.db.models.signals import post_save
from django.dispatch import receiver


class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    avatar = models.ImageField(upload_to='media/pictures/', blank=True)
    regex = RegexValidator(r'^\d{2}/\d{4}',
                           message='Required. 7 characters or fewer. This value must contain only numeric and slash.')
    matric_no = models.CharField(validators=[regex], blank=False, max_length=7, unique=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)  # validators should be a list
    address = models.CharField(max_length=150, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False, default='M',)

forms.py

class StudentProfileForm(forms.ModelForm):
    avatar = forms.ImageField()

    class Meta:
        model = Student
        fields = ('avatar', 'phone_number', 'address', 'gender', 'matric_no')

views.py

class StudentRegistrationView(CreateView):
    model = Student
    form_class = StudentProfileForm
    template_name = 'registration.html'

    def student_registration(request):
        if request.method == "POST":
            form = StudentProfileForm(request.POST, request.FILES)
            if form.is_valid():
                register = form.save(False)
                register.save()
                return redirect('home')

        else:
            form = StudentProfileForm()
        return render(request, 'accounts/registration.html', {'form': form})

我认为问题可能是matric_no字段,或者您认为是什么?

2 个答案:

答案 0 :(得分:0)

userOneToOneField,不可为空,而且它不在表单中,因此您需要分配它。方便的是,您已经在执行解决方案的第1步和第3步(使用commit False保存表单,然后保存实例),因此您只需添加缺少的步骤:

if form.is_valid():
    register = form.save(commit=False)
    register.user = request.user
    register.save()

答案 1 :(得分:0)

我在模型中使用信号来解决问题并以这种方式编写我的视图

view.py

def signup(request):
    if request.method == 'POST':
        form = StudentSignUpForm(request.POST)
        if form.is_valid():
            user_obj = form.save(commit=False)
            user_obj.set_password(form.cleaned_data.get('password1'))
            user_obj.save()
            user_login = auth.authenticate(username=user_obj.username, password=form.cleaned_data.get('password1'))
            login(request, user_login)
            return redirect('student_register')
    else:
        form = StudentSignUpForm()
    return render(request, 'registration/signup_form.html', {'form': form})

model.py

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