When to use django forms vs manual forms?

落花浮王杯 提交于 2020-01-04 02:28:06

问题


I am beginning learning django and have just come across django forms (I've always used manual forms in the past in django templates).

Should I always use django forms no matter what or are there scenarios where I should write the forms in the templates manually?


回答1:


You can use your own forms, but it is better to use django forms because it provides more customization and flexibility.

It is easy to change the type of "widget" rendered with very little code change when you use django forms.

For example:

class MyForm(forms.Form):
    my_field = forms.ChoiceField(choices=CHOICES) #choices can be a tuple

Would render as a checkbox field. If you want to render the same as a Radio button, all you would have to do is:

class MyForm(forms.Form):
    my_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)

You would have to manually change the entire code if you have your own form.

You can also do some custom field level validation on the server side in one pass (Example, check if username is unique) - You can achieve the same in a custom form, but you will have to handle every scenario yourself.

Also, django has ModelForms which would be a replica of the Model object - that tremendously reduces the amount of work that needs to be done for validation, and form processing.



来源:https://stackoverflow.com/questions/16868300/when-to-use-django-forms-vs-manual-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!