Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67497

Select from choices in ModelForm is not displayed in template Django

$
0
0

I want to create a ModelForm for creating an instance of the class Doctor in the template. However, options for the CharField with choices (Gender) are not displayed. I tried to specify widgets and choices in the ModelForm, however it still does not work.

What can i do to display list with options for the field with choices?

Screenshot of the template I have the following class:

class Doctor(models.Model):
    GENDER_CHOICES = [('F', 'Female'), ('M', 'Male')]
    doctor_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=70, blank=False, null=False)
    last_name = models.CharField(max_length=70, blank=False, null=False)
    gender = models.CharField(choices= GENDER_CHOICES, max_length=15, blank=False, null=False)
    specialization = models.CharField(max_length=50, blank=False, null=False)

And ModelForm created from this class

class DoctorForm(ModelForm):
    #gender = forms.ChoiceField(choices=Doctor.GENDER_CHOICES) not working
    class Meta:
        model = Doctor
        fields = ['doctor_id', 'first_name', 'last_name', 'gender', 'specialization', 'email',
                  'phone', 'education', 'experience', 'birth_date', 'address']

        #widgets = {
        #    'gender': forms.Select(choices=Doctor.GENDER_CHOICES)
        #} also not working

Method in views for creating an instance of the form:

def add_doctor(request):
    if request.method == "POST":
        form = DoctorForm(request.POST or None)
        if form.is_valid():
            form.save()
            # Do something.
            return redirect('doctors')
        messages.error(request, "Invalid form")
        return redirect('manage_doctor')
    else:
        form = DoctorForm()
        context = {
            'form': form
        }
        return render(request, 'manage_doctor.html', context)

Viewing all articles
Browse latest Browse all 67497

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>