Additions and deletions based on Form component and based on ModelForm

Introduction to ModelForm

ModelForm
    a.  class Meta:
            model,                           # Corresponding Model Of
            fields=None,                     # field
            exclude=None,                    # Exclusion field
            labels=None,                     # Prompt message
            help_texts=None,                 # Help Tips
            widgets=None,                    # Custom Plugins
            error_messages=None,             # Custom error information (overall error information) from django.core.exceptions import NON_FIELD_ERRORS)
            field_classes=None               # Custom field classes (or fields can also be customized)
            localized_fields=('birth_date',) # Localization, such as displaying data according to different time zones
            For example:
                //Database
                    2016-12-27 04:10:57
                setting Configuration in
                    TIME_ZONE = 'Asia/Shanghai'
                    USE_TZ = True
                //Then show:
                    2016-12-27 12:10:57
    b. Verify execution process
        is_valid -> full_clean -> hook -> Overall error
 
    c. Dictionary Field Validation
        def clean_Field name(self):
            # Exceptions can be thrown
            # from django.core.exceptions import ValidationError
            return "New Value"
    d. For validation
        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. For creating
        model_form_obj = XXOOModelForm(request.POST)
        #### Page display and submit #####
        # Save many-to-many by default
            obj = form.save(commit=True)
        # No action, internal definition save_m2m(For saving many-to-many)
            obj = form.save(commit=False)
            obj.save()      # Save form information
            obj.save_m2m()  # Save associated many-to-many information
 
    f. For update and initialization
        obj = model.tb.objects.get(id=1)
        model_form_obj = XXOOModelForm(request.POST,instance=obj)
        ...
 
        PS: Simple Initialization
            model_form_obj = XXOOModelForm(initial={...})

Scenarios:
ModelForm - Small and Medium Applications.Because ModelForm is dependent on models
Form - Large Application *

Matters needing attention:

Matters needing attention:
            - 1. class 
                  class Foo(ModelForm):
                    class Meta:
                        # model = models.Role
                        # fields = "__all__"
                        # fields = ['caption',]
                        # exclude = ['catpion']
                        model = models.UserType
                        fields = "__all__"

                        error_messages = {
                            'title':{'required':'Name cannot be empty','invalid':'Format error'}
                        }
                        widgets = {
                            'title':wd.TextInput(attrs={'class':'c1'})
                        }
                
            - 2. Add to
                 GET:
                    form = Foo()
                 POST:
                    form = Foo(data=request.POST)
                    form.is_valid()
                    form.cleaned_data
                    form.erros
                    form.save()
            - 3. modify
                 GET:
                    form = Foo(instance=obj)
                 
                 POST:
                    form = Foo(instance=obj,dat=request.POST)
                    ...
                    form.save()
                    

II. Table Structure

from django.db import models

# Create your models here.
class UserInfo (models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)
    ut = models.ForeignKey("UserType")

class UserType (models.Model):
    title = models.CharField(max_length=32)
    roles = models.ManyToManyField(to="Roles")
    def __str__(self):
        return self.title

class Roles(models.Model):
    caption = models.CharField(max_length=32)
    def __str__(self):
        return self.caption

3. Addition and Editing Based on Form Components

Add: This is just an addition to a single table

from django.forms import Form, fields,widgets,ModelForm
from django.shortcuts import render,redirect,HttpResponse
from app01 import models
# Create your views here.
class RoleForm(Form):
    '''utilize Form'''
    caption = fields.CharField(required=True,error_messages={"required":True})

def role(request):
    role_obj = models.Roles.objects.all()
    print(role_obj)
    return render(request, "role.html",{"role_obj":role_obj})

# Be based on Form Realized
def role_add(request):
    '''Add Roles'''
    if request.method=="GET":
        form = RoleForm()
        return render(request,"role_add.html",{"form":form})
    else:
        form = RoleForm(data=request.POST)
        if form.is_valid():
            print("zzzzz")
            caption = form.cleaned_data.get("caption")
            models.Roles.objects.create(caption=caption)
            # models.Roles.objects.create(**form.cleaned_data)
            return redirect("/role/")
        else:
            return render(request,"role_add.html",{"form":form})

Edit: Edit a single table

#Be based on Form Realized Editing
def role_edit(request,nid):
    obj = models.Roles.objects.filter(id=nid).first()
    print(obj.caption)
    if not obj :
        return HttpResponse("Page does not exist")
    if request.method=="GET":
        form = RoleForm(initial={"caption":obj.caption})   #Editing requires a instance,Give Way instance=An object you want to edit
    else:
        form = RoleForm(data = request.POST)
        if form.is_valid():
            models.Roles.objects.filter(id=nid).update(**form.cleaned_data)
            return redirect("/role/")
    return render(request,"role_edit.html",{"form":form})

One-to-many additions or many-to-many additions based on the Form component are detailed in the blogHttp://www.cnblogs.com/haiyan123/p/7816877.html

4. Addition and Editing Based on ModelForm

Add: Add a single table

# Be based on ModelForm Add of
class RoleModelForm(ModelForm):
    class Meta:   #This class must be written, and the name must be this
        model = models.Roles   #this model It's also fixed, take care not to add s,
        fields = "__all__"   #Represents all fields, but you can also specify a single field


def role_add(request):
    if request.method == "GET":
        form = RoleModelForm()
        return render(request,"role_add.html",{"form":form})
    else:
        form = RoleModelForm(data=request.POST)
        if form.is_valid():
            form.save()   #You can use it directly here save Method creates the data
            return redirect("/role/")
        else:
            return render(request,"role_add.html",{"form":form})

Add: Many-to-many additions, as do a bunch of many-to-many additions

# Many-to-many additions
def usertype(request):
    user_type_list = models.UserType.objects.all()
    return render(request,"usertype.html",{'user_type_list':user_type_list})

class UserTypeModelForm(ModelForm):
    title = fields.CharField(max_length=6,required=True,widget=widgets.Textarea)   #This field is temporarily added.
    # In other words modelForm Also available Form The way.
    # You can also add fields in this way, if you overwrite them, you can add them if you don't; as it is now, you can overwrite them below, and of course, you can use them below if you don't have one above.

    class Meta:
        model = models.UserType
        fields = "__all__"

        error_messages = {
            "title":{"required":"User name cannot be empty","invalid":"Mailbox format is inconsistent"}
        }
        widgets = {
            "title":widgets.TextInput(attrs={"class":"c1"})
        }

def usertype_add(request):
    '''Many-to-many additions'''
    if request.method=="GET":
        modelform = UserTypeModelForm()
        return render(request,"usertype_add.html",{"modelform":modelform})
    else:
        modelform = UserTypeModelForm(data=request.POST)
        if modelform.is_valid():
            modelform.save()   #Also available save To do so, even the fields of the relationship table are added
            return redirect("/usertype/")
        else:
            return render(request, "usertype_add.html", {"modelform": modelform})

Edit: Edit a single table

# Be based on modelForm Realized Editing
def role_edit(request,nid):
    obj = models.Roles.objects.filter(id=nid).first()
    if not obj :
        return HttpResponse("Page does not exist")
    if request.method=="GET":
        form = RoleModelForm(instance=obj)   #Editing requires a instance,Give Way instance=An object you want to edit
    else:
        form = RoleModelForm(data = request.POST,instance=obj)
        if form.is_valid:
            form.save()
            return redirect("/role/")
    return render(request,"role_edit.html",{"form":form})

Edit: many-to-many editing

# Many-to-many editing
def usertype(request):
    user_type_list = models.UserType.objects.all()
    return render(request,"usertype.html",{'user_type_list':user_type_list})

class UserTypeModelForm(ModelForm):
    title = fields.CharField(max_length=6,required=True,widget=widgets.Textarea)   #This field is temporarily added.
    # In other words modelForm Also available Form The way.
    # You can also add fields in this way, if you overwrite them, you can add them if you don't; as it is now, you can overwrite them below, and of course, you can use them below if you don't have one above.

    class Meta:
        model = models.UserType
        fields = "__all__"

        error_messages = {
            "title":{"required":"User name cannot be empty","invalid":"Mailbox format is inconsistent"}
        }
        widgets = {
            "title":widgets.TextInput(attrs={"class":"c1"})
        }


def usertype_edit(request,nid):
    #Find roles for the current type of user
    obj = models.UserType.objects.filter(id =nid).first()
    if not obj:
        return HttpResponse("Page does not exist")
    if request.method =="GET":
        form = UserTypeModelForm(instance=obj)
        return render(request,"usertype_edit.html",{"form":form})
    else:
        form = UserTypeModelForm(instance=obj,data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("/usertype/")
    return render(request,"usertype_edit.html",{"form":form})

Tags: Python Django Database

Posted on Wed, 08 Jul 2020 11:41:12 -0400 by wdallman