Django 4.0 - 使用 MultipleChoiceField 保存多个选项
Django 4.0 - Saving Multiple Options using MultipleChoiceField
我正在尝试将多项选择字段保存在我的数据库中的数组中
我不知道该怎么做,我有一个使用标准 ChoiceField 的可行解决方案,但目前它只保存了一个选项
我希望数据库中的值显示为例如“Beavers, Cubs”或“Scouts, Cubs”
如何更改我当前的代码来执行此操作?
(这只是我的第二个问题,所以任何建设性的批评将不胜感激)
models.py
class User(AbstractBaseUser, PermissionsMixin):
# A full User model with admin-compliant permissions that uses a full-length email field as the username
# Email and password are required but all other fields are optional
email = models.EmailField(_('email address'), max_length=254, unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
section = models.CharField(max_length=30)
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_executive = models.BooleanField(_('executive status'), default=False,
help_text=_('Designates that this user is part of the executive committee.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlencode(self.email)
def get_full_name(self):
# Returns the first_name plus the last_name, with a space in between
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
# Returns the short name (first name) for the user
return self.first_name
views.py
def register(request):
articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = request.POST.get('username')
user.section = request.POST.get('section')
user.second_section = request.POST.get('second_section')
user.save()
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
context = {
'title': 'Register',
'articles': articles,
'form': form,
}
return render(request, 'accounts/register.html', context)
forms.py
SECTION = [
('Beavers', 'Beavers'),
('Cubs', 'Cubs'),
('Scouts', 'Scouts'),
]
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
help_text='Please select the section that your child currently attends.')
"""
section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
help_text='Please select the section(s) that your child currently attends.')
"""
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']
在 views.py 中更改以下行
user.section = request.POST.get('section')
至
user.section = ‘,’.join(request.POST.getlist('section'))
或者将“部分”更改为 JSONField 并列出它。
在将您的选择字段添加到您的 forms.py 之前,将您的选择字段放在后端始终是一个好习惯:
SECTION = (('BC', 'Beaver Cubs',),('SC', 'Scout Cubs',))
class User(AbstractBaseUser, PermissionsMixin):
# A full User model with admin-compliant permissions that uses a full-length email field as the username
# Email and password are required but all other fields are optional
email = models.EmailField(_('email address'), max_length=254, unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
# Here we make the selection of our section in choice filed
section = models.CharField(choices=SECTION, max_length=10)
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_executive = models.BooleanField(_('executive status'), default=False,
help_text=_('Designates that this user is part of the executive committee.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlencode(self.email)
def get_full_name(self):
# Returns the first_name plus the last_name, with a space in between
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
# Returns the short name (first name) for the user
return self.first_name
然后我们将字段添加到我们的表单中,如下所示:
lass UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1',
'password2', 'section']
widgets = {
'section': forms.Select(attrs={'class': 'custom-select md-form'}),
}
# This is as clean and good practice
我正在尝试将多项选择字段保存在我的数据库中的数组中
我不知道该怎么做,我有一个使用标准 ChoiceField 的可行解决方案,但目前它只保存了一个选项
我希望数据库中的值显示为例如“Beavers, Cubs”或“Scouts, Cubs”
如何更改我当前的代码来执行此操作?
(这只是我的第二个问题,所以任何建设性的批评将不胜感激)
models.py
class User(AbstractBaseUser, PermissionsMixin):
# A full User model with admin-compliant permissions that uses a full-length email field as the username
# Email and password are required but all other fields are optional
email = models.EmailField(_('email address'), max_length=254, unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
section = models.CharField(max_length=30)
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_executive = models.BooleanField(_('executive status'), default=False,
help_text=_('Designates that this user is part of the executive committee.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlencode(self.email)
def get_full_name(self):
# Returns the first_name plus the last_name, with a space in between
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
# Returns the short name (first name) for the user
return self.first_name
views.py
def register(request):
articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = request.POST.get('username')
user.section = request.POST.get('section')
user.second_section = request.POST.get('second_section')
user.save()
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
context = {
'title': 'Register',
'articles': articles,
'form': form,
}
return render(request, 'accounts/register.html', context)
forms.py
SECTION = [
('Beavers', 'Beavers'),
('Cubs', 'Cubs'),
('Scouts', 'Scouts'),
]
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
help_text='Please select the section that your child currently attends.')
"""
section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
help_text='Please select the section(s) that your child currently attends.')
"""
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']
在 views.py 中更改以下行
user.section = request.POST.get('section')
至
user.section = ‘,’.join(request.POST.getlist('section'))
或者将“部分”更改为 JSONField 并列出它。
在将您的选择字段添加到您的 forms.py 之前,将您的选择字段放在后端始终是一个好习惯:
SECTION = (('BC', 'Beaver Cubs',),('SC', 'Scout Cubs',))
class User(AbstractBaseUser, PermissionsMixin):
# A full User model with admin-compliant permissions that uses a full-length email field as the username
# Email and password are required but all other fields are optional
email = models.EmailField(_('email address'), max_length=254, unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
# Here we make the selection of our section in choice filed
section = models.CharField(choices=SECTION, max_length=10)
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_executive = models.BooleanField(_('executive status'), default=False,
help_text=_('Designates that this user is part of the executive committee.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlencode(self.email)
def get_full_name(self):
# Returns the first_name plus the last_name, with a space in between
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
# Returns the short name (first name) for the user
return self.first_name
然后我们将字段添加到我们的表单中,如下所示:
lass UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1',
'password2', 'section']
widgets = {
'section': forms.Select(attrs={'class': 'custom-select md-form'}),
}
# This is as clean and good practice