iFunction
iFunction

Reputation: 1268

Django, form not rendering in the template

Form not rendering in template.

There is NO model for this view, and i know that, this is a quick tool to hash a serial number. As a result, I am using form.Forms, not ModelForms. So instead of going through the rigmerole of creating a form from scratch, and as I'm adding this to my current site, using a form made sense, but I can't get it to render, it's real simple with two fields and a submit button. For some reason the form fields are not displaying, but the submit button is.

Form

class VoiceSearchForm(forms.Form):
    hw_number = forms.CharField(max_length=6)
    ca_serial = forms.CharField(max_length=16)

view

def voice_search_view(request):
    form = VoiceSearchForm(request.POST)
    if request.method == 'POST':
        form = VoiceSearchForm()
        if form.is_valid():
            hw_number = form.cleaned_data['hw_number']
            ca_serial = form.cleaned_data['ca_serial']

        # Do stuff with the data collected. 

    return render(request, 'voice_search.html', {})

template

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Voice Search</title>
  </head>
  <body>
    <h1>Hashing tool</h1>

    <form action="." class="voice_search"method="POST">
      {{ form.as_p }}
      {% csrf_token %}
      <input type="submit" class="btn" value="Submit">
    </form>
  </body>
</html>

I have followed the docs to get this far, but I must have copied something wrong and can't find anything on google for this, so I suspect on this incredibly rare occasion, this is the very first time this has happened.

Upvotes: 0

Views: 960

Answers (1)

Frank
Frank

Reputation: 2029

You need to pass the form as context to use it in your template. In your view change this:

    return render(request, 'voice_search.html', {})

to this:

    return render(request, 'voice_search.html', {'form': form})

You might also think about using a class-based generic view called form view.

In your case it would look like (untested):

from django.views.generic.edit import FormView

class VoiceSearchView(FormView):
    template_name = 'voice_search.html'
    form_class = VoiceSearchForm

    def form_valid(self, form):
        hw_number = form.cleaned_data['hw_number']
        ca_serial = form.cleaned_data['ca_serial']
        return super().form_valid(form)

Upvotes: 1

Related Questions