Django ModelForms

In this tutorial, we’ll be discussing and implementing ModelForms in our Django Web Application. Do brush up Django Models and Django Forms before proceeding ahead.

在本教程中,我们将在Django Web应用程序中讨论和实现ModelForms。 在继续进行之前,请先整理一下Django模型和Django表单。

Django ModelForms (Django ModelForms)

Instead of creating individual fields redundantly for Django Forms we can map them to a particular Model. This is called ModelForms.

我们可以将它们映射到特定的模型,而不是为Django表单冗余地创建单个字段。 这称为ModelForms。

ModelForm is a class that can be imported using:

ModelForm是可以使用以下命令导入的类:

from django.forms import ModelForm

Following are the benefits of using ModelForms:

以下是使用ModelForms的好处:

  • A ModelForm is useful when we want to create forms from Database fields.

    当我们要从数据库字段创建表单时,ModelForm非常有用。
  • We can add our own validation checkers on the Database Model fields.

    我们可以在数据库模型字段中添加我们自己的验证检查器。
  • We can include and exclude fields from the Model as per our choice.

    我们可以根据自己的选择在模型中包括和排除字段。
  • Easy to quickly save Form data to the database.

    易于快速将表单数据保存到数据库。
ModelForm vs Form 模型形式与形式

ModelForm gets their field definitions from a specified model class. It also has helper methods to save the forms to the database. These features are not present in ModelForm从指定的模型类获取其字段定义。 它还具有帮助程序方法,可将表单保存到数据库。 这些功能不在 Forms. Forms中

save()
save method is called on the Django ModelForm instance in order to save the data to the database (SQLite3).

保存()
为了将数据保存到数据库(SQLite3),在Django ModelForm实例上调用save方法。

Calling save would run the validation check. A ValueError will be raised if the data in the form doesn’t validate.

调用save将运行验证检查。 如果表单中的数据未通过验证,则会引发ValueError

save() method also accepts an optional argument commit. Setting commit to false would not save the data to the database.

save()方法还接受可选的参数commit。 将commit设置为false不会将数据保存到数据库。

创建ModelForm类 (Creating ModelForm Class)

To create a ModelForm class, we need to add a class Meta inside it. Inside the Meta class, we instantiate the Django Model class.

要创建ModelForm类,我们需要在其中添加一个类Meta。 在Meta类内部,我们实例化了Django Model类。

We must include/exclude the fields we want to use in our Model. To include fields we set them in a Python Array.

我们必须包括/排除我们要在模型中使用的字段。 为了包括fields我们将它们设置在Python数组中。

If you want to include all fields set fields = '__all__'.

如果要包括所有字段,请设置fields = '__all__'

To exclude fields set them inside the respective array.

exclude字段,请在各自的数组内设置它们。

An example of our Model class and ModelForm class is given below:

下面给出了我们的Model类和ModelForm类的示例:

from django.db import models
from django.forms import ModelForm

class SampleModel(models.Model):

    title = models.CharField(max_length=100)
    description = models.CharField(max_length=255)

    def __str__(self):
        return self.title

class SampleModelForm(ModelForm):
    class Meta:
        model = SampleModel
        fields = ['title']

In the above code, our SampleModelForm omits the field description.
Displaying the ModelForm in our Django Web application is quite similar to the way we did in the Django Forms tutorial.

在上面的代码中,我们的SampleModelForm省略了字段描述。
在我们的Django Web应用程序中显示ModelForm与我们在Django Forms教程中显示的方法非常相似。

To save the ModelForm to the database we do:

要将ModelForm保存到数据库,我们执行以下操作:

data = SampleModel(title='Me')
form = SampleModelForm(request.POST, instance=data)
form.save()

save(commit=False) is generally used when we want to keep an altered version of the data with us without saving. Typically for testing purposes.

当我们希望随身保存更改后的数据版本而不保存时,通常使用save(commit=False) 。 通常用于测试目的。

For that we can do:

为此,我们可以这样做:

form = SampleModelForm(request.POST)
model = form.save(commit=False)
model.title = 'Anupam testing'
model.save()

from django.forms import modelformset_factory

from django.forms import modelformset_factory

In the following section, we’ll build a simple Django ModelForms web application.

在以下部分中,我们将构建一个简单的Django ModelForms Web应用程序。

项目结构 (Project Structure)

Note: display0.html contains a backup of display.html.

注意 :display0.html包含display.html的备份。

To set up the above project, run the following set of commands one after the other in your terminal.

要设置上述项目,请在终端中一个接一个地运行以下命令集。

mkdir DjangoModelForm
cd DjangoModelForm
virtualenv -p /usr/local/bin/python3 env
source env/bin/activate
pip3 install django
django-admin startproject ModelFormProject
cd ModelFormProject
python3 manage.py runserver
django-admin startapp detailsapp
cd detailsapp
mkdir templates
cd templates
touch userdetails.html
touch display.html
cd ..
touch urls.py
touch forms.py

Our Django app’s name is detailsapp. Add it in the settings.py INSTALLED_APPS list.
userdetails.html is the first page of our application.

我们的Django应用的名称为detailsapp 。 将其添加到settings.py INSTALLED_APPS列表中。
userdetails.html是我们应用程序的第一页。

(Code)

The code for the urls.py file inside the detailsapp folder is:

detailsapp文件夹中urls.py文件的代码为:

from django.urls import path
from django.contrib import admin

from detailsapp import views as detailsapp_views

urlpatterns = [
 path('userdetails/', detailsapp_views.userDetails),
 path('display/', detailsapp_views.userDetails),

path('', admin.site.urls),
]

The code for the urls.py file inside the ModelFormProject folder is:

ModelFormProject文件夹中urls.py文件的代码是:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('detailsapp.urls'))
]

models.py

models.py

from django.db import models
class UserDetails(models.Model):

    title = models.CharField(max_length=100)
    gender = models.CharField(max_length=255)
    notes = models.CharField(max_length=255)

    def __str__(self):
        return self.title

forms.py

forms.py

from django.forms import ModelForm
from detailsapp.models import UserDetails

class UserModelForm(ModelForm):
    class Meta:
        model = UserDetails
        fields = ['title', 'notes']

views.py

views.py

from django.shortcuts import render
from django.db import models
from detailsapp.models import UserDetails
from django.template import loader
from django.http import HttpResponse
from django.forms import modelformset_factory

# Create your views here.

from .forms import UserModelForm

def userDetails(request):

    if request.method == 'POST':
        form = UserModelForm(request.POST)
        if form.is_valid():

            u = form.save()
            users = UserDetails.objects.all()

            return render(request, 'display.html', {'users': users})

            

    else:
        form_class = UserModelForm

    return render(request, 'userdetails.html', {
        'form': form_class,
    })

When the form is empty the else statement is executed and is used to create the form in the userdetails.html file:

表单为空时,将执行else语句,并用于在userdetails.html文件中创建表单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Forms Tutorial</title>
</head>
<body>
<h2>Django Forms Tutorial</h2>

<form action="/display/" method="post">
    {% csrf_token %}
    <table>
    {{form.as_table}}

 </table>
<input type="submit" value="Submit" />
</form>
</body>
</html>

users = UserDetails.objects.all() is used to retrieve all the entries from the database and pass it to the display.html file:

users = UserDetails.objects.all()用于从数据库检索所有条目,并将其传递给display.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ModelForm Tutorial</title>
</head>
<body>
<h2>All User Details</h2>
<table>
    {% for item in users %}
    <tr>
        <td><b>Title:</b>{{ item.title }}</td>
        <td><b>Gender:</b> {{ item.gender|default:"NA" }}</td>
        <td><b>Notes:</b> {{ item.notes }}</td>
    </tr>
    <tr>
    <td colspan="2" class="divider"><hr/></td>
</tr>
    {% endfor %}
</table>
</body>
</html>

Since the gender field is excluded, we’ve set a default value on it using Django Templates.

由于不包括性​​别字段,因此我们使用Django模板为其设置了默认值。

To run the application on your localhost we must form save the Models in the database

为了在本地主机上运行应用程序,我们必须将模型保存在数据库中

python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py runserver

The output of the application in action is given below:

实际应用程序的输出如下:

In order to clear the database, run the following command:

为了清除数据库,请运行以下命令:

python3 manage.py flush

This brings an end to this tutorial. We’ll be covering more custom helper functions and adding our own validation checks in the next tutorial.
In the source code below we’ve added the piece of code to use save(commit=False). Uncomment it and comment out the code that uses save(). We’ve added the template for it in display0.html. Copy it to display.html.

本教程到此结束。 在下一教程中,我们将介绍更多的自定义帮助器功能,并添加我们自己的验证检查。
在下面的源代码中,我们添加了一段代码来使用save(commit = False)。 取消注释,并注释掉使用save()的代码。 我们已经在display0.html中为其添加了模板。 将其复制到display.html。

翻译自: https://www.journaldev.com/22467/django-modelforms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值