何时使用django表单与手动表单? [英] When to use django forms vs manual forms?

查看:136
本文介绍了何时使用django表单与手动表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习django,刚刚遇到django表单(我以前一直在django模板中使用过手动表单)。



我应该始终使用django表单,无论什么或有什么场合,我应该手动在模板中编写表单?

解决方案

您可以使用自己的表单,但最好使用django表单,因为它提供了更多的自定义和灵活性。



当您使用django表单时,很容易更改使用非常少的代码更改呈现的窗口小部件类型。



例如:

  class MyForm(forms.Form) 
my_field = forms.ChoiceField(choices = CHOICES)#choices可以是元组

呈现为复选框字段。
如果要像单选按钮一样渲染,您只需要执行以下操作:

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

如果您有自己的表单,则必须手动更改整个代码。



您还可以在一次通过服务器端进行一些自定义字段级验证(示例,检查用户名是否唯一) - 您可以在自定义表单中实现相同,但你必须自己处理每一个场景。



另外,django有一个 ModelForms ,它将是Model对象的复制品 - 极大地减少了工作量需要进行验证和表单处理。


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?

解决方案

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.

这篇关于何时使用django表单与手动表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆