James L.
James L.

Reputation: 1153

Issues handling 2 forms in same django template

I'm trying to have 2 different forms in same template. Dropdown in one of the forms is not showing any data. I've looked at other posts here but all seem to be quite overwhelming and confusing.

forms.py

class BookOnlineForm(forms.ModelForm):
    patient_name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
    phone = forms.CharField(max_length=200, required= True,widget=forms.TextInput())
    preference = forms.ChoiceField(required=True, choices = PREFER_CHOICES, widget = forms.Select)

    class Meta:
        model = Booking
        fields = ("patient_name","phone")

class UserContentForm(forms.ModelForm):
    time = forms.ChoiceField(required=True, choices = TIME_CHOICES, widget = forms.Select)
    comment = forms.CharField(max_length=2000, required= False,widget=forms.TextInput())

    class Meta:
        model = UserContent
        fields = ("time","comment")

views.py

def showDocProfile(request, id):
    try:
        doctor = Doctor.objects.get(id=id)
    except Doctor.DoesNotExist:
        raise Http404

    clinic = Clinic.objects.get(id=doctor.clinic.id)

  # User content comments and like begin here

    params = {}
    params.update(csrf(request))

    if request.user.is_authenticated():
        user = request.user

# User Content Form

    if request.method == "POST":
        form = UserContentForm(request.POST)

        if form.is_valid():
            time = form.cleaned_data['time']
            comment = form.cleaned_data['comment']

            if request.POST.get('Like') == 'Like':
                con = UserContent(time=time, comment = comment, liked = True, disliked = False, doctor_id = doctor.id, user_id = request.user.id)
                con.save()

            elif request.POST.get('Like') == 'Dislike':
                con = UserContent(time=time, comment = comment, liked = False, disliked = True,  doctor_id = doctor.id, user_id = request.user.id)

                con.save()

            url = '/dp/%s' % str(doctor.id)
            return HttpResponseRedirect(url)

    else:
        form = UserContentForm()

# BookingOnline Form

    if request.method == "POST":
        form = BookOnlineForm(request.POST)

        if form.is_valid():
            patient_name = form.cleaned_data['patient_name']
            preference = form.cleaned_data['preference']
            phone = form.cleaned_data['phone']

            lead = Booking(doctor_id=doctor.id, preference = preference, patient_name=patient_name, phone=phone)
            lead.save()

            url = '/dp/%s' % str(doctor.id)
            return HttpResponseRedirect(url)

        else:
            form = BookOnlineForm()


    d.update({'doctor': doctor, 'clinic': clinic,'form': form, })
    return render(request, 'm1/dp.html', d)

dp.html

The usercontent form is working fine. It's just the Booking form is not showing any preferences in the dropdown menu

  <form action="" method="post" id="user_uploader" > {% csrf_token %}

    <input type="hidden" name="doctor" value="{{ doctor.id }}" />
    <input type="text" class="form-control" placeholder="Your Name" id="patient_name" name = "patient_name">
    <input type="text" class="form-control" placeholder="Your Number" id="phone" name = "phone">

    <select class="form-control" id="preference" name="preference">
    <option><b>Time</b></option>
    {% for value, text in form.preference.field.choices %}
    <option value="{{ value }}">{{ text }}</option>
    {% endfor %}
    </select>

    {% for field in form.visible_fields %}
    {{ field.errors }}
    {% endfor %}

    <button class="btn btn-primary" type="submit" name="submit" id="ss-submit">Submit Booking Request</button>

    </form>

Upvotes: 0

Views: 35

Answers (1)

Alasdair
Alasdair

Reputation: 309089

You should use a different name for the UserContentForm and the BookForm, instead of calling them both form.

# User Content Form
if request.method == "POST":
    user_content_form = UserContentForm(request.POST)
    ...
else:
    user_content_form = UserContentForm()

# BookingOnline Form
if request.method == "POST":
    book_online_form = BookOnlineForm(request.POST)
    ...
# watch this indentation. In your question above it is incorrect.
else: 
    book_online_form = BookOnlineForm()

d.update({'doctor': doctor, 'clinic': clinic,'book_online_form': book_online_form, 'user_content_form': user_content_form})

You will have to replace form with the correct variable in the rest of the view and your template.

Ideally, you should use a prefix when including multiple forms in the same template. However, doing that will require additional changes in your template, as you have hardcoded the form fields (e.g <input ...>), instead of letting Django render them (e.g. {{ form.patient_name }}).

Upvotes: 1

Related Questions