Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Django form field be rendered without a Django form?

Tags:

django

I have a simple HTML form for which I was not using a Django form, but now I want to add a select.

The select would be most easily created as a Django ChoiceField (as opposed to creating the select manually by looping, etc), however, it seems that it won't render properly without being bound/created within a Django form. (By not rendering properly, the browser shows <django.forms.widgets.Select object at 0x10e9a9d10>)

Is there any way to do this?

like image 701
John Lehmann Avatar asked May 05 '16 12:05

John Lehmann


1 Answers

You should use Django Form. But if you really don't want to use the form. You can generate HTML from ChoiceField in your view and pass the html to your template.

from django.forms import fields
my_choice = fields.ChoiceField(choices=((1, '1'), (2,'2')))
field_name = 'my_choice'
field_value = 1
my_choice_html = my_choice.widget.render(field_name, field_value)
return render(request, 'template.html', {'my_choice': my_choice_html})
like image 162
Muhammad Tahir Avatar answered Oct 19 '22 19:10

Muhammad Tahir