schmico
schmico

Reputation: 11

Django Form not rendering in template

I must just be overlooking something here, but after stripping everything back - I can't seem to get Django to render either a Form or ModelForm to my template. Code below:

#forms.py
class ContactForm(forms.Form):
   subject = forms.CharField(max_length=100)
   message = forms.CharField()
   sender = forms.EmailField()
   cc_myself = forms.BooleanField(required=False)

#views.py
def index(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid(): # All validation rules pass
            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm() # An unbound form
    return render_to_response('home/new_website.html',{
        'form': form,
        })

#new_website_html
<html>
<body>
    <form method = "post" action = "">
        {{ form.as_p }}
    </form>
</body>
</html>

Upvotes: 1

Views: 1607

Answers (2)

mozes
mozes

Reputation: 11

I had the same issue and after many tries this is my solution:

Change the view from this

#views.py
else:
    form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
    'form': form,
    })

To that:

#views.py
else:
    form = ContactForm() # An unbound form
    return render_to_response('home/new_website.html',{
        'form': form,
        })

Or a simple newline is enough:

#views.py
else:
    form = ContactForm() # An unbound form

return render_to_response('home/new_website.html',{
    'form': form,
    })

Strange thing is, after these changes the original code worked.

Upvotes: 1

linpingta
linpingta

Reputation: 2630

Any error page or just blank page? Actually I just try your code and get form rendering correct(I don't know how to insert local result image here) Please make sure DEBUG=TRUE in settings.py while it's not the problem. @Burhan I think indent problem only happens because he edits it in stackoverflow. Btw, your form doesn't have a submit button, maybe add it in html like

Upvotes: 0

Related Questions