form

form操做動態select數據html

forms.pypython

from django import forms
from django.forms import fields
from django.forms import widgets
from django.forms.models import ModelChoiceField
from app01 import models
class UserInfoForm(forms.Form):
    user = fields.CharField(
        required=True,
        widget=widgets.Textarea(attrs={'class':'c1'})
    )
    pwd = fields.CharField(
        max_length=12,
        widget=widgets.PasswordInput(attrs={'class':'c1'})
    )
  #方式一 user_type
= fields.ChoiceField( # choices=[(1,'普通用戶'),(2,'超級用戶')],
     choices = [], widget = widgets.Select )
  #方式二 user_type2
= fields.CharField(widget=widgets.Select(choices=[]))
  #方式三 models.py中須要加上def __str__(self):return self.name
  user_type3
= ModelChoiceField( empty_label='請選擇用戶類型', to_field_name='name',#html的源碼裏面value=name對應值 queryset=models.UserType.objects.all() ) def __init__(self,*args,**kwargs): super(UserInfoForm, self).__init__(*args,**kwargs) self.fields['user_type'].choices = models.UserType.objects.values_list('id','name')#在執行構造函數的時候去數據庫取數據,value_list返回的是列表裏面加元祖 self.fields['user_type2'].widget.choices = models.UserType.objects.values_list('id','name')

 

views.pyjquery

from django.shortcuts import render
from app01.forms import UserInfoForm
from app01 import models
# Create your views here.
def index(request):
    obj = UserInfoForm()
    # obj.fields['user_type'].choices = models.UserType.objects.values_list('id','name')
    #類裏面的靜態字段,必須從新去數據庫取值賦值,或者在forms.py中構造函數中取值
    return render(request,'index.html',{'obj':obj})

index.htmlajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>
        {{ obj.user }}
    </p>
    <p>
        {{ obj.pwd }}
    </p>
    <p>
        {{ obj.user_type }}
        {{ obj.user_type2 }}
    </p>
</body>
</html>

 form內置鉤子數據庫

經過obj.is_valid()查看源碼django

用戶註冊在提交的時候須要判斷用戶是否已經註冊,用clean_namejson

驗證過程:app

  正則+clean_字段->clean(__all__)->_post_clean函數

forms.pypost

class RegisterForm(forms.Form):
    user = fields.CharField()
    email = fields.EmailField()
    def clean_name(self):
        c = models.User.objects.filter(name=self.cleaned_data['user']).count()
        if c:
            return self.cleaned_data['user']
        else:
            raise ValidationError('用戶名已經存在',code='xxx')
    def clean(self):
        return self.cleaned_data#總體錯誤信息在__all__裏

 

序列化

QuerySet

第一種:

  from django.core import serializers

  v = models.tb.objects.all()

  data = serializers.serialize('json',v)

第二種

import json
from django.core.exceptions import ValidationError

class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field,ValidationError):
            return{'code':field.code,'messages':field.messages}
        else:
            return json.JSONEncoder.default(self,field)

v= models.tb.objects.values('id','name')
v = list(v)
v = json.dumps(v,cls=JsonCustomEncoder)

ajax提交 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form id="info">{% csrf_token %}
        <p><input type="text" name="username"/></p>
        <p><input type="password"name="pwd"/></p>
        <a id="submit">提交</a>
    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $('#submit').click(function () {
                $.ajax({
                    url:'/login/',
                    type:'POST',
                    data:$('#info').serialize(),#獲取form表單中的全部
                    success:function (arg) {
                        console.log(arg);
                        arg = JSON.parse(arg);
                        console.log(arg);

                    },
                    error:function () {
                        
                    }
                })
            })

        })
    </script>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
from app01.forms import LoginForm
import json
from django.core.exceptions import ValidationError

class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field,ValidationError):
            return{'code':field.code,'messages':field.messages}
        else:
            return json.JSONEncoder.default(self,field)
def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    elif request.method == 'POST':
        ret = {'status':True,'error':None,'data':None}
        obj = LoginForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            # ret['error'] = obj.errors.as_json()#返回字符串
            ret['error'] = obj.errors.as_data()#返回字典   key-validationerror
        result = json.dumps(ret,cls=JsonCustomEncoder)
        # return HttpResponse(json.dumps(ret))
        return HttpResponse(result)

 

 

ModelForm組件

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
ModelForm
     a.   class  Meta:
             model,                            # 對應Model的
             fields = None ,                      # 字段
             exclude = None ,                     # 排除字段
             labels = None ,                      # 提示信息
             help_texts = None ,                  # 幫助提示信息
             widgets = None ,                     # 自定義插件
             error_messages = None ,              # 自定義錯誤信息(總體錯誤信息from django.core.exceptions import NON_FIELD_ERRORS)
             field_classes = None                # 自定義字段類 (也能夠自定義字段)
             localized_fields = ( 'birth_date' ,)  # 本地化,如:根據不一樣時區顯示數據
             如:
                 數據庫中
                     2016 - 12 - 27  04 : 10 : 57
                 setting中的配置
                     TIME_ZONE  =  'Asia/Shanghai'
                     USE_TZ  =  True
                 則顯示:
                     2016 - 12 - 27  12 : 10 : 57
     b. 驗證執行過程
         is_valid  - > full_clean  - > 鉤子  - > 總體錯誤
 
     c. 字典字段驗證
         def  clean_字段名( self ):
             # 能夠拋出異常
             # from django.core.exceptions import ValidationError
             return  "新值"
     d. 用於驗證
         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. 用於建立
         model_form_obj  =  XXOOModelForm(request.POST)
         #### 頁面顯示,並提交 #####
         # 默認保存多對多
             obj  =  form.save(commit = True )
         # 不作任何操做,內部定義 save_m2m(用於保存多對多)
             obj  =  form.save(commit = False )
             obj.save()       # 保存單表信息
             obj.save_m2m()   # 保存關聯多對多信息
 
     f. 用於更新和初始化
         obj  =  model.tb.objects.get( id = 1 )
         model_form_obj  =  XXOOModelForm(request.POST,instance = obj)
         ...
 
         PS: 單純初始化
             model_form_obj  =  XXOOModelForm(initial = {...})

 

forms.py

from django import forms
from django.forms import fields
from django.forms import widgets as Fwidgets
from app01 import models


class UserInfoModelForm(forms.ModelForm):
   #自定義 
  is_rmb
= fields.CharField( widget=Fwidgets.CheckboxInput() ) class Meta: model = models.UserInfo fields = '__all__' # fields = ['username','pwd'] # exclude = ['username'] labels={ 'username':'用戶名', 'email':'郵件' } widgets = { 'username':Fwidgets.Textarea(attrs={'class':'c1'}) } error_messages = { 'email':{ 'required':'郵箱不能爲空', } }

views.py

from django.shortcuts import render
from app01 import forms
from app01 import models
# Create your views here.
def index(request):
    if request.method == 'GET':
        obj = forms.UserInfoModelForm()
        return render(request,'index.html',{'obj':obj})
    elif request.method == 'POST':
        obj = forms.UserInfoModelForm(request.POST)
        if obj.is_valid():
            obj.save()
        return render(request, 'index.html', {'obj': obj})

def user_list(request):
    obj = models.UserInfo.objects.all().select_related('type')
    return render(request,'user_list.html',{'obj':obj})

def edit(request,nid):
    if request.method=='GET':
        obj = models.UserInfo.objects.filter(id=nid).first()
        mf = forms.UserInfoModelForm(instance=obj)
        return render(request,'user_edit.html',{'mf':mf,'id':nid})
    elif request.method == 'POST':
        obj = models.UserInfo.objects.filter(id=nid).first()
        mf = forms.UserInfoModelForm(request.POST,instance=obj)
        if mf.is_valid():
            mf.save()
        else:
            print(mf.errors.as_json())
        return render(request, 'user_edit.html', {'mf': mf, 'id': nid})
相關文章
相關標籤/搜索