Weholt
Weholt

Reputation: 1979

Adding some info to a form in django, not using the template?

I need to add some plain info/html at the top of my form-class, but I cannot add that text in the template. I got a piece of code looking like:

from django import forms

class ContactForm1(forms.Form):
    subject = forms.CharField(max_length=100)
    sender = forms.EmailField()

But when I send this form to the template I'd like to render some plain html at the top of the form, before the form fields. The reason I cannot add the info in the template is that the form is fetched dynamically related to the request, then passed to the template and the cleanest way I could find was to add the extra info to the form itself. Something like this:

class ContactForm1(forms.Form):
    info = InfoField("""<h1>This is the header</h1>
                        and then some more html""")
    subject = forms.CharField(max_length=100)
    sender = forms.EmailField()

And the html in info-field would be rendered before the other fields. I just could not wrap my head around how to subclass django.forms.Field and render my own html.

Any thoughts?

Upvotes: 0

Views: 153

Answers (1)

Myth
Myth

Reputation: 1602

As Torsten said, using template is best option.

If you do not want to use it, you may want to take a look at creating custom widgets

http://docs.djangoproject.com/en/dev/ref/forms/fields/#creating-custom-fields

There are many custom widgets written already, so you can easily find the source code and study how to do it.

Upvotes: 1

Related Questions