銆恉jango銆慺orm

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了銆恉jango銆慺orm相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/cts' title='cts'>cts   value   pos   璺緞   鏂囦欢   渚濊禆   oat   鏍囩   charset   

form

缁勪欢缁勮鍔熻兘锛?/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.琛ㄥ崟楠岃瘉

鎶€鏈垎浜浘鐗? id=
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),
]
project/urls.py
鎶€鏈垎浜浘鐗? id=
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})
app02/views.py
鎶€鏈垎浜浘鐗? id=
<!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>
templates/f1.html

鏁堟灉灞曠ず锛?/p>

鎶€鏈垎浜浘鐗? src=          鎶€鏈垎浜浘鐗? src=鎶€鏈垎浜浘鐗? src=

3銆佸垵濮嬪寲榛樿鍊尖€斺€?span style="color: #ff0000">form琛ㄥ崟绠€鍗?strong>鏇存敼鍗曡〃鏁版嵁搴?/span>鏁版嵁锛堝锛屾敼锛屾煡锛?/strong>

鎶€鏈垎浜浘鐗? id=
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),
]
project/urls.py
鎶€鏈垎浜浘鐗? id=
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})
app01/views.py
鎶€鏈垎浜浘鐗? id=
# !/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>,
        }
    )
app01/forms.py
鎶€鏈垎浜浘鐗? id=
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)
app01/models.py
鎶€鏈垎浜浘鐗? id=
<!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>
templates/users.html
鎶€鏈垎浜浘鐗? id=
<!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>
templates/add_user.html
鎶€鏈垎浜浘鐗? id=
<!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>
templates/edit.html

鏁堟灉灞曠ず锛?/p>

鎶€鏈垎浜浘鐗? src=

 4.鍔ㄦ€佹洿鏂板疄鏃舵暟鎹?/span>

鍦ㄤ娇鐢ㄩ€夋嫨鏍囩鏃讹紝闇€瑕佹敞鎰廲hoices鐨勯€夐」鍙互浠庢暟鎹簱涓幏鍙栵紝浣嗘槸鐢变簬鏄潤鎬佸瓧娈碉紙绫诲彉閲忥級 ***鑾峰彇鐨勫€兼棤娉曞疄鏃舵洿鏂?**锛岄偅涔堥渶瑕佽嚜瀹氫箟鏋勯€犳柟娉曚粠鑰岃揪鍒版鐩殑銆?/span>

鏂规硶涓€锛?鎺ㄨ崘)

鎶€鏈垎浜浘鐗? id=
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),
]
project/urls.py
鎶€鏈垎浜浘鐗? id=
<!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>
templates/love.html
鎶€鏈垎浜浘鐗? id=
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)
app01/models.py
鎶€鏈垎浜浘鐗? id=
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})
app02/views.py

鏁堟灉灞曠ず锛?/p>

鎶€鏈垎浜浘鐗? src=

 鏂规硶浜岋細(渚濊禆浜巑odel涓殑__str__鏂规硶锛屽涓猻lecte妗嗕笉閫傜敤锛岃€﹀悎鎬уお寮?

鎶€鏈垎浜浘鐗? id=
<!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>
templates/love.html
鎶€鏈垎浜浘鐗? id=
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  #鏂板
app01/models.py
鎶€鏈垎浜浘鐗? id=
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})
app02/views.py

鏁堟灉灞曠ず锛?/p>

鎶€鏈垎浜浘鐗? src=

 5.Ajax鎻愪氦楠岃瘉锛堥獙璇侊紱鏃犻渶涓婃鍐呭锛?/strong>

銆€- 杩斿洖HttpResponse
銆€- 鍓嶇锛氳烦杞垨閿欒淇℃伅

濡傛灉鎯宠ajax鎻愪氦鏁版嵁鍒癲jango鍚庡彴锛屽椤甸潰杩涜璺宠浆锛岄渶瑕佸湪ajax 涓獙璇佸悗杩涜璺宠浆锛屽湪鍚庡彴杩涜璺宠浆涓嶇敓鏁?

鎶€鏈垎浜浘鐗? id=
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),
]
project/urls.py
鎶€鏈垎浜浘鐗? id=
<!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>
templates/ajax.html
鎶€鏈垎浜浘鐗? id=
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))
app02/views.py

鎶€鏈垎浜浘鐗? src=

鎶€鏈垎浜浘鐗? src=

鑷畾涔夐獙璇佽鍒?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的主要内容,如果未能解决你的问题,请参考以下文章

jango路由层

jango 全链路详解

jango模板语言初识

jango进阶篇-session-默认5中类型

jango/Flask/Tornado三大web框架性能分析

jango下一对一对应查询,django列类型,分页,CSR攻击