社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  问与答

关于Form的用法

huangturen2007 • 10 年前 • 3531 次点击  

看了一些案例,实在是不明白Form或modelForm的作用。数据库是由models创建的,很多方法也可以在models里面实现,Form到底有什么特别之处,有没有比较典型的例子,就是那种非Form不可的例子,或者大神们也可以随便举个例子。有点痛苦啊。

还有就是在models下的class中定义的一些方法或函数,到底谁调用它们了,也看不到,难道这些函数都是基类方法的重写???

有没有哪个大神写一篇扫盲贴啊!!!!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/752
 
3531 次点击  
文章 [ 1 ]  |  最新文章 10 年前
Py站长
Reply   •   1 楼
Py站长    10 年前

http://stackoverflow.com/questions/2303268/djangos-forms-form-vs-forms-modelform

form没有和model绑定,你可以自己设置任何字段进行处理,ModelForm则是和model绑定的,例如你的表单是生成 一篇文章,那么这个form和文章 model绑定就可以了。 一般来说,使用比较多的是 ModelForm

Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.

Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.

forms.Form:

Documentation: Form objects Example of a normal form created with forms.Form:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

forms.ModelForm:

Documentation: Creating forms from models Straight from the docs:

If your form is going to be used to directly add or edit a Django model, you can use a ModelForm to avoid duplicating your model description.

Example of a model form created with forms.Modelform:

from django.forms import ModelForm

# Create the form class.
class ArticleForm(ModelForm):
    class Meta:
        model = Article

This form automatically has all the same field types as the Article model it was created from.