from django.shortcuts import render from django import forms from django.forms import fields from app01 import models class UserInfoModelForm(forms.ModelForm): class Meta: model = models.UserInfo #去哪个类获取字段 也可以进行增删改查 fields = "__all__" #所有的 # fields = ['username', 'email'] #取其中的 # exclude = ['username'] #排除当中的username # Create your views here. class UserInfoForm(forms.Form): username = fields.CharField(max_length=32) email = fields.EmailField() user_type = fields.ChoiceField( choices=models.UserType.objects.values_list('id','caption') ) def __init__(self, *args, **kwargs): super(UserInfoForm,self).__init__(*args,**kwargs) self.fields['user_type'].choices =models.UserType.objects.values_list('id','caption') def index(request): if request.method == "GET": # obj = UserInfoForm() obj = UserInfoModelForm() return render(request,'index.html', {'obj': obj}) elif request.method == "POST": obj = UserInfoModelForm(request.POST) print(obj.is_valid()) print(obj.cleaned_data) print(obj.errors) # models.UserInfo.objects.create(**obj.cleaned_data) return render(request, 'index.html')