django separated front and rear ends _02 (form of verification)

django order to facilitate verification request parameter, using the module form, in the form, we can use it to check the basic rules, may be custom validation rules

Import module requires the use of

from django import forms

from django.forms import ValidationError

from `` django.forms`` Import model_to_dict, the ValidationError
 from django.utils.httpwrappers Import jsonResponse
 from django.shortcuts Import the render
 from django.views Import View
 from Django Import Forms
 from . Import Models
 # CVB manner, with the table in Example 

# form Django carrying the data check module 
class CaseForm (forms.Form):
     '' ' verification request parameter ' '' 
    title = forms.CharField (= 50 MAX_LENGTH, min_length = 2 ) 
    descForms.CharField = (70 = max_length, required = False) # required default desc = False may be empty 
    Method, = forms.IntegerField () 
    url = forms.URLField () 
    params = forms.CharField (max_length = 100 ) 

    # custom school test 
    # single parameter check. 1 @ 
    # DEF clean_method (self): 
    #      Method self.cleaned_data.get = ( 'Method') # to check that the above-described basic format, and then check the custom rule 
    #      IF Method Not in (0,1,2,3): 
    #          The raise the ValidationError ( 'value does not Method') 
    #      return Method 
    # single parameter check 2 @ 
    # DEF clean_title (Self): 
    #     title = self.cleaned_data.get('title')
    #     if models.Case.objects.filter(title=title).count()>0:
    #         raise ValidationError('标题重复')
    #     return title
    def clean(self):#多个参数组合校验
        method = self.cleaned_data.get('method')
        title = self.cleaned_data.get('title')
        if method not in (0,1,2,3) or models.Case.objects.filter(title=title).count()>0:
            raise ValidationError('Parameter error 12313123213 ' ) # thrown 
        return self.cleaned_data 

class CaseView (View):
     # increase data 
    DEF post (Self, Request): 
        form = CaseForm (of request.POST) # post method to get the requested data 
        # Start verification form.is_valid () returns a bool type of data is not returned through the return True False 
        IF form.is_valid ():
             # If the check returns a dictionary { 'title' by: xxx, 'desc': xxx , 'method' : XX, 'URL': XX, 'the params': XX} 
            Print (form.cleaned_data) 
            models.Case.objects.create ( ** form.cleaned_data) # dictionary preceded ** converted to title = xxx, desc = xxxx 
            = {Data 'code ' : 0, ' MSG ' : ' Success ' }
         the else :
             # form.errors.as_data () is a form carrying this greeting 
            Data = { ' code ' : -1, ' MSG ' : STR (form.errors. as_data ())}
         return jsonResponse (data)
     # lookup data 
    DEF GET (Self, Request): 
        case_sets = models.Case.objects.filter (is_delete = False)   # Search collection 
        data = []
         #Converting the query out into a dictionary by model_to_dict methods, and added to the data list, and finally returns [{ 'XX': XX}, { 'XX': XX}] 
        for C in case_sets: 
            D = model_to_dict (C) 
            data. the append (D) 
        Response = { ' code ' : 0, ' MSG ' : ' success ' , ' data ' : data}
         return jsonResponse (Response, json_dumps_params = { ' ensure_ascii ' : False})
     # delete data 
    DEF delete (Self, Request): 
        the above mentioned id = request.GET.get('id')
        models.Case.objects.filter(id=id).update(is_delete=True)
        response = {'code': 0, 'msg': '成功'}
        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})

The principle

 

Guess you like

Origin www.cnblogs.com/mhmh007/p/12162588.html