銆恉jango銆慺orm
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了銆恉jango銆慺orm相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/cts' title='cts'>cts
value pos 璺緞 鏂囦欢 渚濊禆 oat 鏍囩 charsetform
缁勪欢缁勮鍔熻兘锛?/span>
- 鐢熸垚html鏍囩
- 楠岃瘉鐢ㄦ埛鏁版嵁锛堟樉绀洪敊璇俊鎭級
- HTML Form鎻愪氦淇濈暀涓婃鎻愪氦鏁版嵁
- 鍒濆鍖栭〉闈㈡樉绀哄唴瀹?/li>
1.鍒涘缓Form绫绘椂锛屼富瑕佹秹鍙婂埌 銆愬瓧娈点€?鍜?銆愭彃浠躲€戯紝瀛楁鐢ㄤ簬瀵圭敤鎴疯姹傛暟鎹殑楠岃瘉锛屾彃浠剁敤浜庤嚜鍔ㄧ敓鎴怘TML;
鈶?Django鍐呯疆瀛楁濡備笅锛?/span>
Field
required=True, 鏄惁鍏佽涓虹┖
widget=None, HTML鎻掍欢
label=None, 鐢ㄤ簬鐢熸垚Label鏍囩鎴栨樉绀哄唴瀹? initial=None, 鍒濆鍊? help_text=鈥樷€? 甯姪淇℃伅(鍦ㄦ爣绛炬梺杈规樉绀?
error_messages=None, 閿欒淇℃伅 {鈥榬equired鈥? 鈥樹笉鑳戒负绌衡€? 鈥榠nvalid鈥? 鈥樻牸寮忛敊璇€榼
show_hidden_initial=False, 鏄惁鍦ㄥ綋鍓嶆彃浠跺悗闈㈠啀鍔犱竴涓殣钘忕殑涓斿叿鏈夐粯璁ゅ€肩殑鎻掍欢锛堝彲鐢ㄤ簬妫€楠屼袱娆¤緭鍏ユ槸鍚︿竴鐩达級
validators=[], 鑷畾涔夐獙璇佽鍒? localize=False, 鏄惁鏀寔鏈湴鍖? disabled=False, 鏄惁鍙互缂栬緫
label_suffix=None Label鍐呭鍚庣紑
CharField(Field)
max_length=None, 鏈€澶ч暱搴? min_length=None, 鏈€灏忛暱搴? strip=True 鏄惁绉婚櫎鐢ㄦ埛杈撳叆绌虹櫧
IntegerField(Field)
max_value=None, 鏈€澶у€? min_value=None, 鏈€灏忓€?
FloatField(IntegerField)
...
DecimalField(IntegerField)
max_value=None, 鏈€澶у€? min_value=None, 鏈€灏忓€? max_digits=None, 鎬婚暱搴? decimal_places=None, 灏忔暟浣嶉暱搴?
BaseTemporalField(Field)
input_formats=None 鏃堕棿鏍煎紡鍖?
DateField(BaseTemporalField) 鏍煎紡锛?015-09-01
TimeField(BaseTemporalField) 鏍煎紡锛?1:12
DateTimeField(BaseTemporalField)鏍煎紡锛?015-09-01 11:12
DurationField(Field) 鏃堕棿闂撮殧锛?d %H:%M:%S.%f
...
RegexField(CharField)
regex, 鑷畾鍒舵鍒欒〃杈惧紡
max_length=None, 鏈€澶ч暱搴? min_length=None, 鏈€灏忛暱搴? error_message=None, 蹇界暐锛岄敊璇俊鎭娇鐢?error_messages={鈥榠nvalid鈥? 鈥?..鈥榼
EmailField(CharField)
...
FileField(Field)
allow_empty_file=False 鏄惁鍏佽绌烘枃浠?
ImageField(FileField)
...
娉細闇€瑕丳IL妯″潡锛宲ip3 install Pillow
浠ヤ笂涓や釜瀛楀吀浣跨敤鏃讹紝闇€瑕佹敞鎰忎袱鐐癸細
- form琛ㄥ崟涓?enctype="multipart/form-data"
- view鍑芥暟涓?obj = MyForm(request.POST, request.FILES)
URLField(Field)
...
BooleanField(Field)
...
NullBooleanField(BooleanField)
...
ChoiceField(Field)
...
choices=(), 閫夐」锛屽锛歝hoices = ((0,鈥樹笂娴封€?,(1,鈥樺寳浜€?,)
required=True, 鏄惁蹇呭~
widget=None, 鎻掍欢锛岄粯璁elect鎻掍欢
label=None, Label鍐呭
initial=None, 鍒濆鍊? help_text=鈥樷€? 甯姪鎻愮ず
ModelChoiceField(ChoiceField)
... django.forms.models.ModelChoiceField
queryset, # 鏌ヨ鏁版嵁搴撲腑鐨勬暟鎹? empty_label="---------", # 榛樿绌烘樉绀哄唴瀹? to_field_name=None, # HTML涓璿alue鐨勫€煎搴旂殑瀛楁
limit_choices_to=None # ModelForm涓queryset浜屾绛涢€?
ModelMultipleChoiceField(ModelChoiceField)
... django.forms.models.ModelMultipleChoiceField
TypedChoiceField(ChoiceField)
coerce = lambda val: val 瀵归€変腑鐨勫€艰繘琛屼竴娆¤浆鎹? empty_value= 鈥樷€? 绌哄€肩殑榛樿鍊?
MultipleChoiceField(ChoiceField)
...
TypedMultipleChoiceField(MultipleChoiceField)
coerce = lambda val: val 瀵归€変腑鐨勬瘡涓€涓€艰繘琛屼竴娆¤浆鎹? empty_value= 鈥樷€? 绌哄€肩殑榛樿鍊?
ComboField(Field)
fields=() 浣跨敤澶氫釜楠岃瘉锛屽涓嬶細鍗抽獙璇佹渶澶ч暱搴?0锛屽張楠岃瘉閭鏍煎紡
fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
MultiValueField(Field)
PS: 鎶借薄绫伙紝瀛愮被涓彲浠ュ疄鐜拌仛鍚堝涓瓧鍏稿幓鍖归厤涓€涓€硷紝瑕侀厤鍚圡ultiWidget浣跨敤
SplitDateTimeField(MultiValueField)
input_date_formats=None, 鏍煎紡鍒楄〃锛歔鈥?Y--%m--%d鈥? 鈥?m%d/%Y鈥? 鈥?m/%d/%y鈥榏
input_time_formats=None 鏍煎紡鍒楄〃锛歔鈥?H:%M:%S鈥? 鈥?H:%M:%S.%f鈥? 鈥?H:%M鈥榏
FilePathField(ChoiceField) 鏂囦欢閫夐」锛岀洰褰曚笅鏂囦欢鏄剧ず鍦ㄩ〉闈腑
path, 鏂囦欢澶硅矾寰? match=None, 姝e垯鍖归厤
recursive=False, 閫掑綊涓嬮潰鐨勬枃浠跺す
allow_files=True, 鍏佽鏂囦欢
allow_folders=False, 鍏佽鏂囦欢澶? required=True,
widget=None,
label=None,
initial=None,
help_text=鈥樷€?
GenericIPAddressField
protocol=鈥榖oth鈥? both,ipv4,ipv6鏀寔鐨処P鏍煎紡
unpack_ipv4=False 瑙f瀽ipv4鍦板潃锛屽鏋滄槸::ffff:192.0.2.1鏃跺€欙紝鍙В鏋愪负192.0.2.1锛?PS锛歱rotocol蹇呴』涓篵oth鎵嶈兘鍚敤
SlugField(CharField) 鏁板瓧锛屽瓧姣嶏紝涓嬪垝绾匡紝鍑忓彿锛堣繛瀛楃锛? ...
UUIDField(CharField) uuid绫诲瀷
...銆€銆€銆€
- 甯哥敤瀛楁(閲嶇偣锛?/span>
ChoiceField ***** MultipleChoiceField CharField IntegerField DecimalField DateField DateTimeField EmailField GenericIPAddressField FileField RegexField
鈶?Django鍐呯疆鎻掍欢锛?/span>
TextInput(Input) NumberInput(TextInput) EmailInput(TextInput) URLInput(TextInput) PasswordInput(TextInput) HiddenInput(TextInput) Textarea(Widget) DateInput(DateTimeBaseInput) DateTimeInput(DateTimeBaseInput) TimeInput(DateTimeBaseInput) CheckboxInput Select NullBooleanSelect SelectMultiple Radioselect CheckboxSelectMultiple FileInput ClearableFileInput MultipleHiddenInput SplitDateTimeWidget SplitHiddenDateTimeWidget SelectDateWidget
甯哥敤閫夋嫨鎻掍欢
# 鍗時adio锛屽€间负瀛楃涓?# user = fields.CharField( # initial=2, # widget=widgets.RadioSelect(choices=((1,鈥樹笂娴封€?,(2,鈥樺寳浜€?,)) # ) # 鍗時adio锛屽€间负瀛楃涓?# user = fields.ChoiceField( # choices=((1, 鈥樹笂娴封€?, (2, 鈥樺寳浜€?,), # initial=2, # widget=widgets.RadioSelect # ) # 鍗晄elect锛屽€间负瀛楃涓?# user = fields.CharField( # initial=2, # widget=widgets.Select(choices=((1,鈥樹笂娴封€?,(2,鈥樺寳浜€?,)) # ) # 鍗晄elect锛屽€间负瀛楃涓?# user = fields.ChoiceField( # choices=((1, 鈥樹笂娴封€?, (2, 鈥樺寳浜€?,), # initial=2, # widget=widgets.Select # ) # 澶氶€塻elect锛屽€间负鍒楄〃 # user = fields.MultipleChoiceField( # choices=((1,鈥樹笂娴封€?,(2,鈥樺寳浜€?,), # initial=[1,], # widget=widgets.SelectMultiple # ) # 鍗昪heckbox # user = fields.CharField( # widget=widgets.CheckboxInput() # ) # 澶氶€塩heckbox,鍊间负鍒楄〃 # user = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, 鈥樹笂娴封€?, (2, 鈥樺寳浜€?,), # widget=widgets.CheckboxSelectMultiple # )
2.琛ㄥ崟楠岃瘉
from django.conf.urls import url from django.contrib import admin from app01 import views from app02 import views as v2 urlpatterns = [ url(r鈥?/span>^f1.html$鈥?/span>, v2.f1), ]
from django.shortcuts import render,HttpResponse,redirect from django import forms from django.forms import fields class F1From(forms.Form): user = fields.CharField( max_length=18,min_length=6,required=True, error_messages={ 鈥?/span>required鈥?/span>: 鈥?/span>鐢ㄦ埛涓嶈兘涓虹┖鈥?/span>, 鈥?/span>max_length鈥?/span>: 鈥?/span>澶暱浜?/span>鈥?/span>, 鈥?/span>min_length鈥?/span>: 鈥?/span>澶煭浜?/span>鈥?/span>, 鈥?/span>invalid鈥?/span>: 鈥?/span>鏍煎紡涓嶆纭?/span>鈥?/span>,#鏍煎紡涓嶆纭兘鏄痠nvalid } ) pwd = fields.CharField( min_length=6, required=True, error_messages={ 鈥?/span>required鈥?/span> : 鈥?/span>瀵嗙爜涓嶈兘涓虹┖鈥?/span>, 鈥?/span>min_length鈥?/span>: 鈥?/span>澶煭浜?/span>鈥?/span>, 鈥?/span>invalid鈥?/span> : 鈥?/span>瀵嗙爜鏍煎紡涓嶆纭?/span>鈥?/span>, } ) email = fields.EmailField(required=True, error_messages={ 鈥?/span>required鈥?/span> : 鈥?/span>閭涓嶈兘涓虹┖鈥?/span> , 鈥?/span>invalid鈥?/span> : 鈥?/span>鏍煎紡闇€涓洪偖绠辨牸寮?/span>鈥?/span>, } ) age = fields.IntegerField( required=True, error_messages={ 鈥?/span>required鈥?/span>: 鈥?/span>骞撮緞涓嶈兘涓虹┖鈥?/span>, 鈥?/span>invalid鈥?/span> : 鈥?/span>骞撮緞闇€涓烘暟瀛?/span>鈥?/span>, } ) def f1(request): if request.method == "GET": obj = F1From() return render(request,鈥?/span>f1.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj}) else: # u = request.POST.get(鈥榰ser鈥? # p = request.POST.get(鈥榩wd鈥? # e = request.POST.get(鈥榚mail鈥? # a = request.POST.get(鈥榓ge鈥? # 1.妫€鏌ユ槸鍚︿负绌?/span> # 2.妫€鏌ユ牸寮忔槸鍚︽纭?/span> # print(u,p,e,a) obj = F1From(request.POST) # 鏄惁鍏ㄩ儴楠岃瘉鎴愬姛 if obj.is_valid(): #鐢ㄦ埛鎻愪氦鐨勬暟鎹?/span> print(鈥?/span>楠岃瘉鎴愬姛鈥?/span>,obj.cleaned_data) return redirect(鈥?/span>http://www.baidu.com鈥?/span>) # return render(request,鈥榝1.html鈥?{鈥榦bj鈥?obj}) else: print(鈥?/span>楠岃瘉澶辫触鈥?/span>,obj.errors) return render(request,鈥?/span>f1.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/f1.html" method="POST"> <P>鐢ㄦ埛: {{ obj.user }}{{ obj.errors.user.0 }}</P>{# 涓€涓緭鍏ラ」鍙兘鍖呭惈澶氱鏍煎紡閿欒锛屽彇绗竴涓?.0 #} <P>瀵嗙爜: {{ obj.pwd }}{{ obj.errors.pwd.0 }}</P> <P>閭: {{ obj.email }}{{ obj.errors.email.0 }}</P> <P>骞撮緞: {{ obj.age }}{{ obj.errors.age.0 }}</P> <input type="submit" value="form鎻愪氦"/> </form> </body> </html>
鏁堟灉灞曠ず锛?/p>
3銆佸垵濮嬪寲榛樿鍊尖€斺€?span style="color: #ff0000">form琛ㄥ崟绠€鍗?strong>鏇存敼鍗曡〃鏁版嵁搴?/span>鏁版嵁锛堝锛屾敼锛屾煡锛?/strong>
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r鈥?/span>^admin/鈥?/span>, admin.site.urls), url(r鈥?/span>^users/鈥?/span>, views.users), url(r鈥?/span>^add_user/鈥?/span>, views.add_user), url(r鈥?/span>^edit_user-(d+)/鈥?/span>, views.edit_user), ]
from django.shortcuts import render,HttpResponse,redirect from app01 import models def users(request): user_list = models.UserInfo.objects.all() return render(request,鈥?/span>users.html鈥?/span>,{鈥?/span>user_list鈥?/span>:user_list}) from app01.forms import UserForm def add_user(request): if request.method == 鈥?/span>GET鈥?/span>: obj = UserForm() return render(request,鈥?/span>add_user.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj}) else: obj = UserForm(request.POST) if obj.is_valid(): print(鈥?/span>楠岃瘉鎴愬姛鈥?/span>,obj.cleaned_data) # models.UserInfo.objects.create( # username = obj.cleaned_data[鈥榰sername鈥榏, # email = obj.cleaned_data[鈥榚mail鈥榏, # ) # 鍚庨潰涓€鍙ュ彲浠ョ洿鎺ヤ唬鏇夸笂闈㈣鍙?/span> models.UserInfo.objects.create(**obj.cleaned_data) return redirect(鈥?/span>/users/鈥?/span>) else: print(鈥?/span>楠岃瘉澶辫触鈥?/span>,obj.errors) return render(request,鈥?/span>add_user.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj}) def edit_user(request,nid): if request.method == 鈥?/span>GET鈥?/span>: # p = request.GET.get(鈥榥id鈥? data = models.UserInfo.objects.filter(id=nid).first() # 鎷垮埌涓€涓璞?/span> obj = UserForm({鈥?/span>username鈥?/span>:data.username,鈥?/span>email鈥?/span>:data.email}) return render(request,鈥?/span>edit.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj,鈥?/span>nid鈥?/span>:nid }) else: obj = UserForm(request.POST) if obj.is_valid(): models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data) return redirect(鈥?/span>/users/鈥?/span>) else: return render(request, 鈥?/span>edit.html鈥?/span>, {鈥?/span>obj鈥?/span>: obj, 鈥?/span>nid鈥?/span>: nid})
# !/usr/bin/env python # -*- coding: utf-8 -*- # Author:daly from django import forms as dforms from django.forms import fields class UserForm(dforms.Form): username = fields.CharField( required=True, min_length=6, error_messages={ 鈥?/span>required鈥?/span>:"鐢ㄦ埛涓嶈兘涓虹┖", 鈥?/span>min_length鈥?/span>:鈥?/span>澶煭浜?/span>鈥?/span>, } ) email = fields.EmailField( required=True, error_messages={ 鈥?/span>required鈥?/span>: "閭涓嶈兘涓虹┖", 鈥?/span>invalid鈥?/span>:鈥?/span>閭鏍煎紡閿欒鈥?/span>, } )
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)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/add_user/">娣诲姞</a> <ul> {% for row in user_list %} <li>{{ row.id }}-{{ row.username }}-{{ row.email }}|<a href="/edit_user-{{ row.id }}">缂栬緫</a></li> {% endfor %} </ul> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/add_user/" novalidate> {% csrf_token %} <p>鐢ㄦ埛锛歿{ obj.username }}{{ obj.errors.username.0 }}</p> <p>閭锛歿{ obj.email }}{{ obj.errors.email.0 }}</p> <input type="submit" value="鎻愪氦"/> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/edit_user-{{ nid }}/" method="post" novalidate> {% csrf_token %} <p>鐢ㄦ埛锛歿{ obj.username }}{{ obj.errors.username.0 }}</p> <p>閭锛歿{ obj.email }}{{ obj.errors.email.0 }}</p> <input type="submit" value="鎻愪氦"/> </form> </body> </html>
鏁堟灉灞曠ず锛?/p>
4.鍔ㄦ€佹洿鏂板疄鏃舵暟鎹?/span>
鍦ㄤ娇鐢ㄩ€夋嫨鏍囩鏃讹紝闇€瑕佹敞鎰廲hoices鐨勯€夐」鍙互浠庢暟鎹簱涓幏鍙栵紝浣嗘槸鐢变簬鏄潤鎬佸瓧娈碉紙绫诲彉閲忥級 ***鑾峰彇鐨勫€兼棤娉曞疄鏃舵洿鏂?**锛岄偅涔堥渶瑕佽嚜瀹氫箟鏋勯€犳柟娉曚粠鑰岃揪鍒版鐩殑銆?/span>
鏂规硶涓€锛?鎺ㄨ崘)
from django.conf.urls import url from django.contrib import admin from app01 import views from app02 import views as v2 urlpatterns = [ url(r鈥?/span>^love/鈥?/span>, v2.love), ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>闈炶瘹鍕挎壈</h1> <P>浠锋牸锛歿{ obj.prive }}</P> <P>浜哄憳锛歿{ obj.user_id }}</P> </body> </html>
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)
from django.shortcuts import render from django import forms from django.forms import fields from django.forms import widgets from app01 import models class LoveForm(forms.Form): user_id = fields.IntegerField( widget=widgets.Select( # choices=[(0,鈥樿嫻鏋溾€?,(1,鈥樻ⅷ瀛愨€?,(2,鈥橀钑夆€?], #鑷繁鍒涘缓 # choices= models.UserInfo.objects.values_list(鈥榠d鈥?鈥榰sername鈥? #涔熷彲浠ヤ粠鏁版嵁搴撳彇鏁版嵁 ) ) prive = fields.IntegerField() def __init__(self,*args,**kwargs): #鎷疯礉鎵€鏈夐潤鎬佸瓧娈碉紝澶嶅埗缁檚elf.fields (椤哄簭锛歴uper->self.fields) super(LoveForm,self).__init__(*args,**kwargs) self.fields[鈥?/span>user_id鈥?/span>].widget.choices = models.UserInfo.objects.values_list(鈥?/span>id鈥?/span>,鈥?/span>username鈥?/span>) def love(requset): obj = LoveForm() return render(requset,鈥?/span>love.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj})
鏁堟灉灞曠ず锛?/p>
鏂规硶浜岋細(渚濊禆浜巑odel涓殑__str__鏂规硶锛屽涓猻lecte妗嗕笉閫傜敤锛岃€﹀悎鎬уお寮?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>闈炶瘹鍕挎壈</h1> <P>浠锋牸锛歿{ obj.prive }}</P> <P>浜哄憳锛歿{ obj.user_id }}</P> <P>浜哄憳锛歿{ obj.user_id2 }}</P> <!--鏂板--> </body> </html>
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) def __str__(self): #鏂板 return self.username #鏂板
from django.shortcuts import render from django import forms from django.forms import fields from django.forms import widgets from app01 import models class LoveForm(forms.Form): user_id = fields.IntegerField( widget=widgets.Select( # choices=[(0,鈥樿嫻鏋溾€?,(1,鈥樻ⅷ瀛愨€?,(2,鈥橀钑夆€?], #鑷繁鍒涘缓 # choices= models.UserInfo.objects.values_list(鈥榠d鈥?鈥榰sername鈥? #涔熷彲浠ヤ粠鏁版嵁搴撳彇鏁版嵁 ) ) prive = fields.IntegerField() from django.forms.models import ModelChoiceField #鏂板 user_id2 =ModelChoiceField( #鏂板 queryset=models.UserInfo.objects.all(), #鏂板 to_field_name=鈥?/span>id鈥?/span>, #鏂板 ) #鏂板 def __init__(self,*args,**kwargs): #鎷疯礉鎵€鏈夐潤鎬佸瓧娈碉紝澶嶅埗缁檚elf.fields (椤哄簭锛歴uper->self.fields) super(LoveForm,self).__init__(*args,**kwargs) self.fields[鈥?/span>user_id鈥?/span>].widget.choices = models.UserInfo.objects.values_list(鈥?/span>id鈥?/span>,鈥?/span>username鈥?/span>) def love(requset): obj = LoveForm() return render(requset,鈥?/span>love.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj})
鏁堟灉灞曠ず锛?/p>
5.Ajax鎻愪氦楠岃瘉锛堥獙璇侊紱鏃犻渶涓婃鍐呭锛?/strong>
銆€- 杩斿洖HttpResponse
銆€- 鍓嶇锛氳烦杞垨閿欒淇℃伅
濡傛灉鎯宠ajax鎻愪氦鏁版嵁鍒癲jango鍚庡彴锛屽椤甸潰杩涜璺宠浆锛岄渶瑕佸湪ajax 涓獙璇佸悗杩涜璺宠浆锛屽湪鍚庡彴杩涜璺宠浆涓嶇敓鏁?
from django.conf.urls import url from django.contrib import admin from app01 import views from app02 import views as v2 urlpatterns = [ url(r鈥?/span>^ajax/鈥?/span>, v2.ajax), ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/ajax/" method="post" novalidate> {% csrf_token %} {{ obj.as_p }} <input type="button" value="ajax鎻愪氦" id="btn"/> </form> <script src="/static/jquery-3.1.1.js/"></script> <script> $(function () { $(鈥?/span>#btn鈥?/span>).click(function () { $.ajax({ url:鈥?/span>/ajax/鈥?/span>, type:鈥?/span>POST鈥?/span>, data:$(鈥?/span>#fm鈥?/span>).serialize(), dataType:鈥?/span>JSON鈥?/span>, success:function (arg) { //arg:鐘舵€侊紝閿欒淇℃伅 if (arg.status == 鈥?/span>閽?/span>鈥?/span>){ window.location.href="http://www.baidu.com" } console.log(arg); } }) }) }) </script> </body> </html>
class AjaxForm(forms.Form): prive = fields.IntegerField() user_id = fields.IntegerField( widget=widgets.Select( choices=[(0,鈥?/span>鑻规灉鈥?/span>),(1,鈥?/span>姊ㄥ瓙鈥?/span>),(2,鈥?/span>棣欒晧鈥?/span>)], ) ) def ajax(request): if request.method == 鈥?/span>GET鈥?/span>: obj = AjaxForm() return render(request,鈥?/span>ajax.html鈥?/span>,{鈥?/span>obj鈥?/span>:obj}) else: ret = {鈥?/span>status鈥?/span>:鈥?/span>娌¢挶鈥?/span>,鈥?/span>message鈥?/span>:None} import json obj = AjaxForm(request.POST) # print(obj.cleaned_data) if obj.is_valid(): print(obj.cleaned_data) # return redirect(鈥榟ttp://www.baidu.com鈥? ret[鈥?/span>status鈥?/span>]=鈥?/span>閽?/span>鈥?/span> return HttpResponse(json.dumps(ret)) else: print(type(obj.errors)) from django.forms.utils import ErrorDict print(obj.errors.as_ul()) print(obj.errors.as_json()) print(obj.errors.as_data()) ret[鈥?/span>message鈥?/span>]= obj.errors return HttpResponse(json.dumps(ret))
鑷畾涔夐獙璇佽鍒?from缁勪欢鎵╁睍)
鏂瑰紡涓€锛?/span>
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( validators=[RegexValidator(r鈥榐[0-9]+$鈥? 鈥樿杈撳叆鏁板瓧鈥?, RegexValidator(r鈥榐159[0-9]+$鈥? 鈥樻暟瀛楀繀椤讳互159寮€澶粹€?], )
鏂瑰紡浜岋細銆€
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.RegexField(r鈥榐[0-9]+$鈥?error_messages={鈥榠nvalid鈥? 鈥樻牸寮忛敊璇€榼)
鍩轰簬婧愮爜娴佺▼
a. 鍗曞瓧娈碉紙clean_field锛?/span>
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,鈥榓lex鈥?,(1,鈥樺垬鐨撳鈥?,(2,鈥樻潹寤衡€?,]) ) # 鑷畾涔夋柟娉?clean_瀛楁鍚?# 蹇呴』杩斿洖鍊約elf.cleaned_data[鈥榰sername鈥榏 # 濡傛灉鍑洪敊锛歳aise ValidationError(鈥樼敤鎴峰悕宸插瓨鍦ㄢ€? def clean_username(self): v = self.cleaned_data[鈥榰sername鈥榏 if models.UserInfo.objects.filter(username=v).count(): # 鏁翠綋閿欎簡 # 鑷繁璇︾粏閿欒淇℃伅 raise ValidationError(鈥樼敤鎴峰悕宸插瓨鍦ㄢ€? return v def clean_user_id(self): return self.cleaned_data[鈥榰ser_id鈥榏
b. 鏁翠綋閿欒楠岃瘉锛坈lean_form锛?/span>
class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,鈥榓lex鈥?,(1,鈥樺垬鐨撳鈥?,(2,鈥樻潹寤衡€?,]) ) # 鑷畾涔夋柟娉?clean_瀛楁鍚? # 蹇呴』杩斿洖鍊約elf.cleaned_data[鈥榰sername鈥榏 # 濡傛灉鍑洪敊锛歳aise ValidationError(鈥樼敤鎴峰悕宸插瓨鍦ㄢ€? def clean_username(self): v = self.cleaned_data[鈥榰sername鈥榏 if models.UserInfo.objects.filter(username=v).count(): # 鏁翠綋閿欎簡 # 鑷繁璇︾粏閿欒淇℃伅 raise ValidationError(鈥樼敤鎴峰悕宸插瓨鍦ㄢ€? return v def clean_user_id(self): return self.cleaned_data[鈥榰ser_id鈥榏 def clean(self): value_dict = self.cleaned_data v1 = value_dict.get(鈥榰sername鈥? v2 = value_dict.get(鈥榰ser_id鈥? if v1 == 鈥榬oot鈥?and v2==1: raise ValidationError(鈥樻暣浣撻敊璇俊鎭€? return self.cleaned_data
銆€銆€
以上是关于銆恉jango銆慺orm的主要内容,如果未能解决你的问题,请参考以下文章