Django 4.0 - Сохранение нескольких вариантов с помощью поля MultipleChoiceField
Я пытаюсь сохранить поля множественного выбора в массиве внутри моей базы данных
Я понятия не имею, как это сделать, у меня есть рабочее решение с использованием стандартного ChoiceField, но оно сохраняет только один вариант на данный момент
Я хочу, чтобы мои значения в базе данных отображались, например, как "Beavers, Cubs" или "Scouts, Cubs"
Как я могу изменить мой текущий код, чтобы сделать это?
(Это только мой 2-й вопрос, поэтому любая конструктивная критика будет оценена по достоинству)
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():
#if request.POST.get('section'):
#form.section = request.POST.getlist('section')
#to_str = form.section
#string = str(to_str)[1:-1]
#form.save(string)
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')
to
user.section = ‘,’.join(request.POST.getlist('section'))
Или измените '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