0

I am trying to save Multiple Choices inside my database

I have a rough idea of how to do this but I am looking for a complete solution

I am also wanting users to select multiple options on the Register page as these values will then be saved into the ManyToManyField

I want my users to be able to access blogs for multiple sections (at the moment I can only get this to work for one section only)

How can I change my current code to do this?

(This is only my 3rd question so any constructive criticism will be appreciated)

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)
    # section = models.ManyToManyField('UserSection', related_name='sections')
    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

    #def email_user(self, subject, message, from_email=None):
        # Sends an email to this User
        #send_mail(subject, message, from_email, [self.email])

"""
class UserSection(models.Model):
    section_name = models.CharField(max_length=30)

    def __str__(self):
        return self.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']

Below is a section of my base.html file that uses Jinja2 to render the buttons to access each sections blog page

<ul class="navbar-nav ms-auto">
    {% if user.section == 'Beavers' %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'beavers_blog_home' %}"><span class="fas fa-blog"></span> Beavers Blog</a>
    </li>
    {% endif %}
    {% if user.section == 'Cubs' %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'cubs_blog_home' %}"><span class="fas fa-blog"></span> Cubs Blog</a>
    </li>
    {% endif %}
    {% if user.section == 'Scouts' %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'scouts_blog_home' %}"><span class="fas fa-blog"></span> Scouts Blog</a>
    </li>
    {% endif %}
    {% if user.is_authenticated %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'profile' %}"><span class="fas fa-users"></span> Profile</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{% url 'logout' %}"><span class="fas fa-sign-out-alt"></span> Logout</a>
    </li>
    {% else %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'login' %}"><span class="fas fa-sign-in-alt"></span> Login</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{% url 'register' %}"><span class="fas fa-user-plus"></span> Register</a>
    </li>
    {% endif %}
</ul>
  • What exactly is the problem that you're having? – Lzak Feb 14 '22 at 17:57
  • @Lzak there is no problem with the code, It's that I am just trying to let users select multiple sections and display it inside the database Essentially I want the user to be able to access the Cubs Blog and any other blog out of the options but I am struggling to find a good solution for this – Kiran Sarda Feb 14 '22 at 18:09
  • I do have a similar question [here](https://stackoverflow.com/questions/71035644/django-4-0-saving-multiple-options-using-multiplechoicefield) where I try to find a solution using MultipleChoiceFields – Kiran Sarda Feb 14 '22 at 18:11
  • https://stackoverflow.com/questions/47867760/django-quiz-app-model-for-multiple-choice-questions this is thing u might looking for – Faisal Nazik Feb 14 '22 at 18:14
  • @FaisalNazik that uses ForeignKeys, I am looking at ManyToManyFields I'll give it a try though – Kiran Sarda Feb 14 '22 at 18:26

0 Answers0