How to make Required: boolean field in model Django

試著忘記壹切 提交于 2019-12-08 03:04:27

问题


I have a model with a field called in is_student and is_teacher Student and Teacher forms

is_teacher = models.BooleanField('teacher status', default=False)
is_student = models.BooleanField('student status', default=False)

I want to make sure this field is:

  • Always Checked by the user True *Required

Currently: is_teacher in TeacherApplications Model

  • When unchecked - it saved 0 to the form and continues. (Not good)

  • When checked gives me this error:

ValueError at /register/teacher invalid literal for int() with base 10: ''

Currently: is_student in StudentProfile Model

  • When checked gives this error

ValidationError at /register/ ["'on' value must be either True or False."]

  • When unchecked it saved 0 to the form and continues. (Again, not good)

UPDATED CODE


Above errors are gone: New error each time I try to submit form after checking is_teacher/is_student

IntegrityError at /register/ NOT NULL constraint failed: accounts_studentprofile.is_student


model

class StudentProfile(models.Model):
    user = models.OneToOneField('Accounts', related_name='student_profile')
    # additional fields for students
    AMEB_Ratings = models.PositiveIntegerField(default=0)
    is_student = models.BooleanField('student status', default=False)



class TeacherApplications(models.Model):
    user = models.OneToOneField('Accounts', related_name='teacher_profile')
    # additional fields for teachers
    instrument = models.TextField(max_length=500, blank=True)
    skill = models.CharField(max_length=30, blank=True)
    experience_in_years = models.PositiveIntegerField(blank=True)
    is_teacher = models.BooleanField('teacher status', default=False)

view

def registerStudent(request):
    # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
    if request.method == "POST":
        user_form = UserForm(request.POST)
        form = StudentResistrationForm(request.POST)

        if form.is_valid() and user_form.is_valid():
            User = get_user_model()
            username = user_form.cleaned_data['username']
            email = user_form.cleaned_data['email']
            password = user_form.cleaned_data['password']
            new_user = User.objects.create_user(username=username, email=email, password=password)

            student = form.save(commit=False)
            student.user = new_user
            student.save()

            # Student_profile = StudentProfile()
            # Student_profile.user = new_user
            # Student_profile.AMEB_Ratings = request.POST['AMEB_Ratings']
            # Student_profile.is_student = request.POST.get('is_student', False)

            new_user.save()
            # Student_profile.save()
            # form.save()

            return redirect('/')
    else:
        #  Create the django default user form and send it as a dictionary in args to the reg_form.html page.
        user_form = UserForm()
        form = StudentResistrationForm()        

        # args = {'form_student': form, 'user_form': user_form }
    return render(request, 'accounts/reg_form_students.html', {'form_student': form, 'user_form': user_form })

def teacherApplication(request):
    # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
    if request.method == "POST":
        user_form = UserForm(request.POST)
        form = TeacherRegistrationForm(request.POST)

        if form.is_valid() and user_form.is_valid():
            User = get_user_model()
            username = user_form.cleaned_data['username']
            email = user_form.cleaned_data['email']
            password = user_form.cleaned_data['password']
            new_user = User.objects.create_user(username=username, email=email, password=password)

            teacher = form.save(commit=False)
            teacher.user = new_user
            teacher.save()

            # Teacher_profile = TeacherApplications()
            # Teacher_profile.user = new_user
            # Teacher_profile.instrument = request.POST['instrument']
            # Teacher_profile.skill = request.POST['skill']
            # Teacher_profile.experience_in_years = request.POST['experience_in_years']
            # Teacher_profile.is_teacher = request.POST.get('is_teacher', False)

            new_user.save()
            # Teacher_profile.save()
            # form.save()

            return redirect('/')
    else:
        #  Create the django default user form and send it as a dictionary in args to the reg_form.html page.
        user_form = UserForm()
        form = TeacherRegistrationForm()  
    return render(request, 'accounts/reg_form_teachers.html', {'form_student': form, 'user_form': user_form })

forms

class StudentResistrationForm(forms.ModelForm):
    class Meta:
        model = StudentProfile
        fields = (  
            'AMEB_Ratings',
            'is_student',

        )

    def save(self, commit=True):
        user = super(StudentResistrationForm, self).save(commit=False)
        # user.first_name = self.cleaned_data['first_name']
        # user.last_name = self.cleaned_data['last_name']
        user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings']

        if commit:
            user.save()

        return user


class TeacherRegistrationForm(forms.ModelForm):
    class Meta:
        model = TeacherApplications
        fields = (
            'instrument',
            'skill',
            'experience_in_years',
            'is_teacher',
        )

class UserForm(forms.ModelForm):
    class Meta:
        model = get_user_model()
        fields = ('username', 'email', 'password')

回答1:


You can add this fields to StudentResistrationForm and TeacherRegistrationForm and add custom validation for it in clean_fieldname method to make it required:

StudentResistrationForm(ModelForm):
    class Meta:
        model = StudentRegistration
        fields = (
            'instrument',
            'skill',
            'experience_in_years',
            'is_student',
        )

    def clean_is_student(self):
        is_student = self.cleaned_data.get('is_student')
        if not is_student:
            raise forms.ValidationError('This field is required')
        return is_student  

Also in view instead of getting raw data from request.POST you can use forms to create student and teacher objects:

new_user = User.objects.create_user(username=username, email=email, password=password)
teacher = form.save(commit=False)
teacher.user = new_user
teacher.save()


来源:https://stackoverflow.com/questions/49622241/how-to-make-required-boolean-field-in-model-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!