首页 > 代码库 > Python菜鸟之路:Django ModelForm的使用
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的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。