1. 程式人生 > >Form和ModelForm

Form和ModelForm

ret 創建 mode dir name title cnblogs set color

Django表單系統中,所有的表單類都作為django.forms.Form的子類創建,包括ModelForm

關於django的表單系統,主要分兩種

基於django.forms.Form:所有表單類的父類

基於django.forms.ModelForm:可以和模型類綁定的Form

form實例

# app01/views.py
from django.shortcuts import render, HttpResponse
                                                  
# Create your views here.
# from django import forms
from django import forms class LoginForm(forms.Form): user=forms.CharField(min_length=5, max_length=12, error_messages={required:"該內容不能為空"}, widget=forms.TextInput(attrs={"
class":"s",placeholder:user}) ) pwd=forms.CharField() def login(request): if request.method=="POST": form_obj=LoginForm(request.POST)
if form_obj.is_valid(): print(form_obj.cleaned_data) else: print(form_obj.errors) return HttpResponse("OK") form_obj=LoginForm() return render(request, "login.html",{form_obj: form_obj}) # template/login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> {% csrf_token %} {{ form_obj.as_p }} <button>提交</button> </form> </body> </html> ###或 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> {% csrf_token %} {{ form_obj.user }} {{ form_obj.pwd }} <button>提交</button> </form> </body> </html>
##註意事項
1) {% csrf_token %}
2)  html中button標簽在form表單中具有提交功能,在form表單外不具有提交功能
{{ form_obj.as_p }}
{{ form_obj.as_ul }}
{{ form_obj.as_table }}

ModelForm實例

from django.shortcuts import render, redirect, HttpResponse
from . import models
# Create your views here.
from django.forms import ModelForm
from django.forms import widgets as wid
from django.forms import fields as fld
                                        
                                        
class UserModelForm(ModelForm):
    class Meta:                 
        model = models.UserInfo
        fields = "__all__"              
        fields = [username,nickname]
        exclude = [username]                       
        error_messages={                             
            username: {required: 用戶名不能為空},
        }                                            
        widgets= {                                   
            username: wid.Textarea(attrs={class:"c1"})
        }                                            
        labels={                                     
            username: 用戶名,                    
        }                                            
        help_texts= {                                
            username: 別瞎寫,.......             
        }                                            
        field_classes= {                            
            nickname: fld.EmailField              
        }                                           
                                 
                                 
class RoleModelForm(ModelForm):
    class Meta:                 
        model = models.Role      
        fields = "__all__"       
                                       
                                       
class PermissionModelForm(ModelForm):
    class Meta:                 
        model = models.Permission
        fields = "__all__"       
                                 
                                 
class MenuModelForm(ModelForm):
    class Meta:                 
        model = models.Menu      
        fields = "__all__"       
                                            
                                            
def users(request):                        
    user_list= models.UserInfo.objects.all()
    return render(request,"rbac/users.html",{user_list:user_list})
                               
                               
def user_add(request):
    if request.method == "GET":
        model_form=UserModelForm()
        return render(request, "rbac/user_add.html", {model_form:model_form})                    
    else:                                     
        model_form=UserModelForm(request.POST)
        if model_form.is_valid():
            model_form.save()
            return redirect("/rbac/users/")
        return render(request, "rbac/user_add.html", {model_form: model_form})                                          
                                                      
                                                      
def user_del(request,pk):                            
    obj_queryset=models.UserInfo.objects.filter(pk=pk)
    if obj_queryset:                                  
        obj_queryset.delete()                         
    return redirect("/rbac/users/")                    
                                                       
                                                       
def user_edit(request,pk):
    obj = models.UserInfo.objects.filter(pk=pk).first()
    if not obj:                        
        return redirect("/rbac/users/")
    if request.method=="GET":
        model_form=UserModelForm(instance=obj)
        return                        render(request,rbac/user_edit.html,{model_form:model_form})
    else:                                                 
        model_form=UserModelForm(request.POST,instance=obj)
        if model_form.is_valid():                        
            model_form.save()                             
            return redirect("/rbac/users/")                
        return render(request, rbac/user_edit.html, {model_form: model_form})
 
 

 

Form和ModelForm