如何制作必填项:模型Django中的布尔字段 [英] How to make Required: boolean field in model Django
问题描述
我有一个模型,该模型的字段称为is_student
和is_teacher
Student
和Teacher
形式
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)
我要确保此字段为:
- 始终由用户检查
True
*必填
- Always Checked by the user
True
*Required
当前:TeacherApplications
模型中的is_teacher
Currently: is_teacher
in TeacherApplications
Model
-
未选中时-将0保存到表单并继续. (不好)
When unchecked - it saved 0 to the form and continues. (Not good)
选中时,出现此错误:
ValueError /register/teacher中的int()具有基数的无效文字 10:"
ValueError at /register/teacher invalid literal for int() with base 10: ''
当前:StudentProfile
模型中的is_student
Currently: is_student
in StudentProfile
Model
- 选中时出现此错误
- When checked gives this error
/register/[[on]值必须为True或ValidationError 错.]
ValidationError at /register/ ["'on' value must be either True or False."]
- 未选中时,它将0保存到表单中并继续. (再次,不好)
- When unchecked it saved 0 to the form and continues. (Again, not good)
更新后的代码
以上错误均已消失:每次在检查is_teacher/is_student 后尝试尝试提交表单时都出现新错误
Above errors are gone: New error each time I try to submit form after checking is_teacher/is_student
在/register/NOT NULL约束处的IntegrityError失败: account_studentprofile.is_student
IntegrityError at /register/ NOT NULL constraint failed: accounts_studentprofile.is_student
模型
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)
视图
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 })
表格
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')
推荐答案
您可以将此字段添加到StudentResistrationForm
和TeacherRegistrationForm
,并在clean_fieldname
方法中为其添加自定义验证以使其为必需:
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
在视图中,也可以从窗体中创建student
和teacher
对象,而不是从request.POST
获取原始数据:
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()
这篇关于如何制作必填项:模型Django中的布尔字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!