[英]Check box in django redux form. I am using django-redux
我在Django redux注冊表格中添加了兩個復選框。 現在,我可以選中這兩個選項,但是我希望用戶一次選擇任何一個。 如何實現呢? 下面是我的代碼
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserSelection(models.Model):
employer = models.BooleanField()
candidate = models.BooleanField()
user = models.OneToOneField(User)
表格
from django import forms
from registration.forms import RegistrationFormUniqueEmail
class MyRegForm(RegistrationFormUniqueEmail):
employer = forms.BooleanField()
candidate = forms.BooleanField()
regbackend.py
from registration.backends.default.views import RegistrationView
from .forms import MyRegForm
from .models import UserSelection
class MyRegistrationView(RegistrationView):
form_class = MyRegForm
def register(self, form_class):
new_user = super(MyRegistrationView, self).register(form_class)
p = form_class.cleaned_data['employer']
q = form_class.cleaned_data['candidate']
new_profile = UserSelection.objects.create(user=new_user, employer=p, candidate=q)
new_profile.save()
return new_user
您確定要兩個布爾字段嗎? 如果您有一個帶有選擇項的char字段,則該表格僅允許您選擇一個選擇項。
USER_TYPE_CHOICES = [
('employer', 'Employer'),
('candidate', 'Candidate'),
]
class UserSelection(models.Model):
user = models.OneToOneField(User)
user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES)
如果您確實需要兩個布爾字段,則可以為模型編寫一個干凈的方法。
from django.core.exceptions import ValidationError
class UserSelection(models.Model):
employer = models.BooleanField(blank=True)
candidate = models.BooleanField(blank=True)
user = models.OneToOneField(User)
def clean(self):
if self.employer and self.candidate:
raise ValidationError("You cannot select employer and candidate")
if not (self.employer or self.candidate):
raise ValidationError("You must select employer or candidate")
請注意,您需要在布爾字段上輸入blank=True
,以允許用戶取消選中它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.