zoukankan      html  css  js  c++  java
  • Django-ModelForm


    作者:武沛齐 
    出处:Django之ModelForm组件

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

    ModelForm
        a.  class Meta:
                model,                           # 对应Model的
                fields=None,                     # 字段
                exclude=None,                    # 排除字段
                labels=None,                     # 提示信息
                help_texts=None,                 # 帮助提示信息
                widgets=None,                    # 自定义插件
                error_messages=None,             # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
                field_classes=None               # 自定义字段类 (也可以自定义字段)
                localized_fields=('birth_date',) # 本地化,如:根据不同时区显示数据
                如:
                    数据库中
                        2016-12-27 04:10:57
                    setting中的配置
                        TIME_ZONE = 'Asia/Shanghai'
                        USE_TZ = True
                    则显示:
                        2016-12-27 12:10:57
        b. 验证执行过程
            is_valid -> full_clean -> 钩子 -> 整体错误
     
        c. 字典字段验证
            def clean_字段名(self):
                # 可以抛出异常
                # from django.core.exceptions import ValidationError
                return "新值"
        d. 用于验证
            model_form_obj = XXOOModelForm()
            model_form_obj.is_valid()
            model_form_obj.errors.as_json()
            model_form_obj.clean()
            model_form_obj.cleaned_data
        e. 用于创建
            model_form_obj = XXOOModelForm(request.POST)
            #### 页面显示,并提交 #####
            # 默认保存多对多
                obj = form.save(commit=True)
            # 不做任何操作,内部定义 save_m2m(用于保存多对多)
                obj = form.save(commit=False)
                obj.save()      # 保存单表信息
                obj.save_m2m()  # 保存关联多对多信息
     
        f. 用于更新和初始化
            obj = model.tb.objects.get(id=1)
            model_form_obj = XXOOModelForm(request.POST,instance=obj)
            ...
     
            PS: 单纯初始化
                model_form_obj = XXOOModelForm(initial={...})

    一个实例:

    1. models.py

     1 from django.db import models
     2 
     3 # Create your models here.
     4 
     5 
     6 class UserInfo(models.Model):
     7     name = models.CharField(max_length=32)
     8     email = models.EmailField()
     9     nickName = models.CharField(max_length=32)
    10     group = models.ForeignKey('UserGroup', null=True, blank=True)
    11     role = models.ManyToManyField('Role', null=True, blank=True)
    12 
    13     def __str__(self):
    14         return self.name
    15 
    16 
    17 class UserGroup(models.Model):
    18     name = models.CharField(max_length=32)
    19     info = models.TextField()
    20 
    21     def __str__(self):
    22         return self.name
    23 
    24 
    25 class Role(models.Model):
    26     name = models.CharField(max_length=32)
    27     info = models.TextField()
    28 
    29     def __str__(self):
    30         return self.name
    View Code

    2. views.py

     1 from django.shortcuts import render,HttpResponse
     2 from django.forms import ModelForm
     3 from django.forms import fields as dfields
     4 from django.forms import widgets as dwidgets
     5 from app01 import models
     6 
     7 
     8 class TestModelForm(ModelForm):
     9     class Meta:
    10         model = models.UserInfo
    11         fields = '__all__'
    12         error_messages = {
    13             'name': {
    14                 'required': '用户名不能为空',
    15             },
    16             'email': {
    17                 'required': '邮箱不能为空',
    18                 'invalid': '邮箱格式不正确',
    19             },
    20             'nickName': {
    21                 'required': '昵称不能为空',
    22             }
    23         }
    24         labels = {
    25             'name': '用户名',
    26             'email': '邮箱',
    27             'nickName': '昵称',
    28             'group': '部门',
    29             'role': '角色',
    30         }
    31         widgets = {
    32             'name': dwidgets.Input(attrs={'class': 'form-control'}),
    33             'email': dwidgets.Input(attrs={'class': 'form-control'}),
    34             'nickName': dwidgets.Input(attrs={'class': 'form-control'}),
    35             'group': dwidgets.Select(attrs={'class': 'form-control'}),
    36             'role': dwidgets.SelectMultiple(attrs={'class': 'form-control'}),
    37         }
    38 
    39 # Create your views here.
    40 
    41 
    42 def test(request):
    43     content = {'form': None}
    44     if request.method == 'GET':
    45         form = TestModelForm()
    46         content['form'] = form
    47         return render(request, 'test.html', content)
    48     else:
    49         form = TestModelForm(request.POST)
    50         content['form'] = form
    51         if form.is_valid():
    52             print(form.cleaned_data)
    53             form.save()
    54             return HttpResponse('add success!')
    55         else:
    56             return render(request, 'test.html', content)
    57 
    58 
    59 def edit(request, nid):
    60     obj = models.UserInfo.objects.filter(id=nid).first()
    61     content = {'form': None}
    62     if request.method == 'GET':
    63         form = TestModelForm(instance=obj)
    64         content['form'] = form
    65         return render(request, 'edit.html', content)
    66     else:
    67         form = TestModelForm(instance=obj, data=request.POST, files=request.FILES)
    68         if form.is_valid():
    69             form.save()
    70             return HttpResponse('edit success!')
    71         content['form'] = form
    72         return render(request, 'test.html', content)
    View Code

    3. templates

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
     6     <title>Title</title>
     7 </head>
     8 <body>
     9 <form method="post" novalidate>
    10     {% csrf_token %}
    11     <div class="form-group" style=" 300px; margin: 50px auto;">
    12         {{ form.as_p }}
    13         <input type="submit" value="提交">
    14     </div>
    15 </form>
    16 
    17 <script src="/static/jquery-3.2.1.js"></script>
    18 </body>
    19 </html>
    test.html
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
     6     <title>Title</title>
     7 </head>
     8 <body>
     9 <form method="post" novalidate>
    10     {% csrf_token %}
    11     <div class="form-group" style=" 300px; margin: 50px auto;">
    12         {{ form.as_p }}
    13         <input type="submit" value="提交">
    14     </div>
    15 </form>
    16 
    17 <script src="/static/jquery-3.2.1.js"></script>
    18 </body>
    19 </html>
    edit.html
  • 相关阅读:
    php下的jsonp使用实例
    jquery ajax jsonp跨域调用实例代码
    js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)
    jsonp实现跨域访问
    jsonp调用实例
    Jsonp和java操作例子
    JSONP实例
    跨平台移动开发工具:PhoneGap与Titanium全方位比拼
    混合开发模式下主流移动开发平台分析
    企业移动信息化应用开发模式选型指南
  • 原文地址:https://www.cnblogs.com/OldJack/p/7491385.html
Copyright © 2011-2022 走看看