Django模型和表格之间有什么区别? [英] whats the difference between Django models and forms?

查看:60
本文介绍了Django模型和表格之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,无法理解模型和形式.谁能建议我与他们有关的差异和教程.

I am new to Django and can't understand the models and forms. Can any one suggest me the differences and tutorials related to them.

推荐答案

基本上,模型封装有关某物的信息(即,它对它们进行建模),并存储在数据库中.例如,我们可以为一个人建模:

Basically, a model encapsulates information about something (i.e., it models it), and is stored in the database. For example, we could model a person:

from django import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    height = models.FloatField()
    weight = models.FloatField()

无论何时创建并保存模型实例,Django都会将其存储在数据库中,以供以后检索和使用.

Whenever a model instance is created and saved, Django stores it in the database for you to retrieve and use at a later date.

另一方面,表单对应于HTML表单,即,一组字段,呈现给最终用户以填充一些数据.表单可以完全独立于模型,例如搜索表单:

On the other hand, forms correspond to HTML forms, i.e., a set of fields which are presented to the end user to fill some data in. A form can be completely independent of a model, for example a search form:

from django import forms

class SearchForm(forms.Form):
    search_terms = forms.CharField(max_length=100)
    max_results = forms.IntegerField()

提交后,Django负责验证用户输入的值并将其转换为Python类型(例如整数).然后,您要做的就是编写使用这些值执行某些操作的代码.

When submitted, Django takes care of validating the values the user entered and converting them to Python types (such as integers). All you then have to do is write the code which does something with these values.

当然,如果您已经创建了模型,则通常会希望允许用户通过表单来创建这些模型.Django不必重复所有字段名称并自己创建表单,而是为此提供了一个快捷方式,即 ModelForm :

Of course, if you have created a model, you will often want to allow a user to create these models through a form. Instead of having to duplicate all the field names and create the form yourself, Django provides a shortcut for this, the ModelForm:

from django.forms import ModelForm

class PersonForm(forms.ModelForm)
    class Meta:
        model = Person

关于进一步的阅读,我将从 Django文档开始,其中包括有关创建和使用模型的教程,并对表单进行了相当深入的研究.还有很多Django书籍和在线教程可以帮助您.

As for further reading, I would start with the Django documentation, which includes a tutorial on creating and using models, and a fairly in-depth look at forms. There are also plenty of Django books and online tutorials to help you along.

这篇关于Django模型和表格之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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