Python菜鸟之路:Django ModelForm的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python菜鸟之路:Django ModelForm的使用相关的知识,希望对你有一定的参考价值。

一、简单使用案例

#views.py
from django.shortcuts import render,HttpResponse
from app01 import models

from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
class UserInfoModelForm(forms.ModelForm):

    is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())

    class Meta:
        model = models.UserInfo
        fields = ‘__all__‘
        # fields =  [‘username‘,‘email‘]
        # exclude = [‘username‘]
        labels = {
            ‘username‘: ‘用户名‘,
            ‘email‘: ‘邮箱‘,
        }
        help_texts = {
            ‘username‘: ‘...‘
        }
        widgets = {
            ‘username‘: Fwidgets.Textarea(attrs={‘class‘: ‘c1‘})
        }
        error_messages = {
            ‘__all__‘:{

            },
            ‘email‘: {
                ‘required‘: ‘邮箱不能为空‘,
                ‘invalid‘: ‘邮箱格式错误..‘,
            }
        }
        field_classes = {
            # ‘email‘: Ffields.URLField
        }

        # localized_fields=(‘ctime‘,)

    def clean_username(self):
        old = self.cleaned_data[‘username‘]
        return old
def index(request):
    if request.method == "GET":
        obj = UserInfoModelForm()
        return render(request,‘index.html‘,{‘obj‘: obj})
    elif request.method == "POST":
        obj = UserInfoModelForm(request.POST)
        if obj.is_valid():
            # obj.save()
            instance = obj.save(False)
            instance.save()
            obj.save_m2m()


        # print(obj.is_valid())
        # print(obj.cleaned_data)
        # print(obj.errors.as_json())
        return render(request,‘index.html‘,{‘obj‘: obj})

  

#models.py
from django.db import models

# Create your models here.


class UserType(models.Model):
    caption = models.CharField(max_length=32)


class UserGroup(models.Model):
    name = models.CharField(max_length=32)


class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField()
    user_type = models.ForeignKey(to=‘UserType‘,to_field=‘id‘)
    u2g = models.ManyToManyField(UserGroup)

  

  

以上是关于Python菜鸟之路:Django ModelForm的使用的主要内容,如果未能解决你的问题,请参考以下文章

Python菜鸟之路:Django 路由补充FBV和CBV

Python菜鸟之路:Django 表单验证

Python菜鸟之路:Django 序列化数据

Python菜鸟之路:Django Admin后台管理功能使用

Python菜鸟之路:Django 路由模板ORM

我的python菜鸟之路5