开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜