Home > Software engineering >  ChoiceFields to give two different forms or different fields in html template and django
ChoiceFields to give two different forms or different fields in html template and django

Time:10-17

I am trying to make a registration form for a dentist and a student, where I have a choice field for a dentist and a student. What I want to happen is, when dentist is picked, I should be able to see the specialties field in the html as well as Django to pick that form, and for student, to pick student_email and institution. I am confused to how to write its code in the template and I looked almost everywhere and couldn't find anything that could help with what I want. I also included an image with what the registration image looks like. I know I can use select and option in html template but still a bit confused about them as well. If you could show me a better way to apply my idea, please let me know.

form.py

from django import forms
from django_countries.fields import CountryField


class RegistrationForm(forms.Form):

   Specialties = [
       ('pediatric','Pediatric'),
       ('oral surgeon','Oral Surgeon'),
       ('periodontist','Periodontist (Restorative; Esthetic)'),
       ('orthodontist','Orthodonsit'),
       ('endodontist','Endodontist'),
       ('prosthodontist','Prosthodontist'),
       ('oral pathologist','Oral Pathologist'),
       ('oral radiologist','Oral Radiologist'),
       ('public health dentist','Public Health Dentist'),
       ('research and academics','Research and Academics'),
   ]

   username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True, unique=True)
   email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True)
   student_email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True)
   password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True)
   password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True)
   first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   date_of_birth = forms.DateField(label = "Date of Birth", widget=forms.SelectDateWidget([x for x in range(1920,2021)]), required=True)
   country = CountryField().formfield(required=True)
   gender = forms.ChoiceField(widget=forms.RadioSelect, choices=[('male','Male'),('female','Female')], required=True)
   specialty = forms.CharField(widget=forms.Select(choices= Specialties), required=True)
   institution = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   dentist_or_student = forms.ChoiceField(widget=forms.RadioSelect, choices=[('dentist','Dentsit'),('student','Student')], required=True)

   def clean_student_email(self):

       data = self.cleaned_data['student_email']
       if "@edu" not in data: #Check if the student's email is educational or not
           raise forms.ValidationError("Email must be @edu")
       return data

views.py

def user_register(request):
    template_name = 'accounts/signup.html'

    if request.method == 'POST':
        
        form = RegistrationForm(request.POST)
        
        # Check for validity
        if form.is_valid():
            if form.cleaned_data['dentist_or_student'] == 'dentist':

                if User.objects.filter(username=form.cleaned_data['username']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Username already exists'
                    })
                elif User.objects.filter(email=form.cleaned_data['email']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Email already exists'
                    })
                elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                    return render(request,template_name, {
                        'form': form,
                        'error_message': 'Passwords do not match'
                    })
                else:
                    # Create the user
                    user = User.objects.create_user(
                        form.cleaned_data['username'],
                        form.cleaned_data['email'],
                        form.cleaned_data['password']
                    )
                    user.first_name = form.cleaned_data['first_name']
                    user.last_name = form.cleaned_data['first_name']
                    user.dentist_or_student = form.cleaned_data['dentist']
                    user.date_of_birth = form.cleaned_data['date_of_birth']
                    user.country = form.cleaned_data['country']
                    user.gender = form.cleaned_data['gender']
                    user.save()

                    # Login the user
                    login(request, user)

                    # redirect to Homepage
                    return HttpResponseRedirect('home')

            elif form.cleaned_data['dentist_or_student'] == 'student':
                if User.objects.filter(username=form.cleaned_data['username']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Username already exists'
                    })
                elif User.objects.filter(email=form.cleaned_data['student_email']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Email already exists'
                    })
                elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                    return render(request,template_name, {
                        'form': form,
                        'error_message': 'Passwords do not match'
                    })
                else:
                    # Create the user
                    user = User.objects.create_user(
                        form.cleaned_data['username'],
                        form.cleaned_data['student_email'],
                        form.cleaned_data['password']
                    )
                    user.first_name = form.cleaned_data['first_name']
                    user.last_name = form.cleaned_data['first_name']
                    user.dentist_or_student = form.cleaned_data['student']
                    user.date_of_birth = form.cleaned_data['date_of_birth']
                    user.country = form.cleaned_data['country']
                    user.gender = form.cleaned_data['gender']
                    user.save()

                    # Login the user
                    login(request, user)

                    # redirect to Homepage
                    return HttpResponseRedirect('home')

            else:
                messages.error(request, 'Please pick if either you are a Dentist or a Student before continuing the form')
                return redirect('register')

    # No post data available, just show the webpage
    else:
        form = RegistrationForm()

    return render(request, template_name, {'form': form})

enter image description here

CodePudding user response:

You are using a CharField (see docs) for a field that has options. Try using a ChoiceField (see docs) instead. Something like:

specialty = forms.ChoiceField(choices= Specialties, required=True)

CodePudding user response:

You should add both into your html, and make them hidden. Then add an alert into your Select, and OnChange you can make hidden=false of the selected form.

YOURSELECT.addEventListener("change", document.getElementById(YOURSELECT.value).removeAttribute("hidden"););

  • Related