溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

py_Django之表單

發(fā)布時(shí)間:2020-07-06 00:07:52 來源:網(wǎng)絡(luò) 閱讀:374 作者:lc994811089 欄目:開發(fā)技術(shù)



HttpRequest----request


常用的

request.path除域名以外的請求路徑,以正斜杠開頭"/hello/"
request.get_host()主機(jī)名(比如,通常所說的域名)"127.0.0.1:8000" or"www.example.com"
request.get_full_path()請求路徑,可能包含查詢字符串"/hello/?print=true"
request.is_secure()如果通過HTTPS訪問,則此方法返回True, 否則返回False
request.META是一個(gè)Python字典,包含了所有本次HTTP請求的Header信息很多東西
HTTP_REFERER進(jìn)站前鏈接網(wǎng)頁
HTTP_USER_AGENT

"Mozilla/5.0 (X11; U; Linux i686; fr-FR;

rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17"

REMOTE_ADDR"12.345.67.89,23.456.78.90"
request.GET類字典對象,POST數(shù)據(jù)是來自HTML中的〈form〉標(biāo)簽提交的
request.POST類字典對象,GET數(shù)據(jù)可能來自〈form〉提交也可能是URL中的查詢字符串(例如/search/?q=django)


三種常見返回

from django.http import HttpResponse
def hello(request):
    return HttpResponse("Hello world")
    
from django.shortcuts import render_to_response
def search_form(request):
    return render_to_response('search_form.html')
    
from django.http import HttpResponseRedirect
    return HttpResponseRedirect('/contact/thanks/')




典型的數(shù)據(jù)交互


一個(gè)get例子

def search(request):
    errors = []      # 收集錯誤信息交給前端(簡單處理后顯示)  
    if 'q' in request.GET:   
        q = request.GET['q']       
        if not q:        
            errors.append('Enter a search term.')          
        elif len(q) > 20:       
            errors.append('Please enter at most 20 characters.')           
        else:  
            books = Book.objects.filter(title__icontains=q)
    # 數(shù)據(jù)庫的操作見  icontains(大小寫無關(guān)的LIKE)      
            return render_to_response('search_results.html',{'books': books, 'query': q})           
    return render_to_response('search_form.html',{'errors': errors })
    #  若用戶刷新一個(gè)包含POST表單的頁面,那么請求將會重新發(fā)送造成重復(fù)。重定向嘍
# search_form.html
<html>
<head>
    <title>Search</title>
</head>
<body>
    {% if errors %}        # 顯示錯誤<p ><p>會更漂亮點(diǎn)
        <ul>
            {% for error in errors %}
            <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}
    <form action="/search/" method="get">
        <input type="text" name="q">       # 后端通過 q 拿值
        <input type="submit" value="Search">
    </form>
</body>
</html>
# search_results.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<p>You searched for: <strong>{{ query }}</strong></p>

{% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    # 模板的過濾器    length 返回變量的長度     pluralize  單詞的復(fù)數(shù)形式,如列表字符串個(gè)數(shù)大于1,返回s,否則返回空串
    <ul>
        {% for book in books %}
        <li>{{ book.title }}</li>
        {% endfor %}
    </ul>
{% else %}
    <p>No books matched your search criteria.</p>
{% endif %}

</body>
</html>


一個(gè)post的例子

# views.py

from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def contact(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('subject', ''):
            errors.append('Enter a subject.')
        if not request.POST.get('message', ''):
            errors.append('Enter a message.')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('Enter a valid e-mail address.')
        if not errors:
            send_mail(         # 四個(gè)必選參數(shù): 主題,正文,寄信人和收件人列表。
                request.POST['subject'],
                request.POST['message'],
                request.POST.get('email', 'noreply@example.com'),
                ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
            #  若用戶刷新一個(gè)包含POST表單的頁面,那么請求將會重新發(fā)送造成重復(fù)。
            #  所以重定向,應(yīng)每次都給成功的POST請求做重定向。
    return render(request, 'contact_form.html', {
        'errors': errors,        
        'subject': request.POST.get('subject', ''),
        'message': request.POST.get('message', ''),
        'email': request.POST.get('email', ''),
    })
                # 驗(yàn)證失敗后,返回客戶端的表單中各字段最好是填有原來提交的數(shù)據(jù)
                
                
# contact_form.html

<html>
<head>
    <title>Contact us</title>
</head>
<body>
    <h2>Contact us</h2>

    {% if errors %}
        <ul>
            {% for error in errors %}
            <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}

    <form action="/contact/" method="post">
        <p>Subject: <input type="text" name="subject" value="{{ subject }}"></p>
        <p>Your e-mail (optional): <input type="text" name="email" value="{{ email }}"></p>
        <p>Message: <textarea name="message" rows="10" cols="50"> {{ message }} </textarea></p>
        <input type="submit" value="Submit">
    </form>
</body>
</html>













詳解form表單


有點(diǎn)類似模型,定義各個(gè)字段的類型

from django import forms
 
class ContactForm(forms.Form):
  subject = forms.CharField()
  email = forms.EmailField(required=False)
  message = forms.CharField()




form將數(shù)據(jù)格式化成html的形式

>>> from contact.forms import ContactForm
>>> f = ContactForm()
>>> print f
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>

默認(rèn)是tr th  可以換成下面兩種形式

>>> print f.as_ul()
<li><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></li>
>>> print f.as_p()
<p><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></p>




對每個(gè)字段取值

>>> print f['subject']
<input type="text" name="subject" id="id_subject" />
>>> print f['message']
<input type="text" name="message" id="id_message" />



創(chuàng)建時(shí)賦值(字典形式)

>>> f = ContactForm({'subject': 'Hello', 'email': 'adrian@example.com', 'message': 'Nice site!'})



判斷

>>> f.is_bound                一旦你對一個(gè)Form實(shí)體賦值,你就得到了一個(gè)綁定form
True
>>> f.is_valid()               判斷是否合法,默認(rèn)都是必需填參數(shù)
True



errors

每一個(gè)邦定Form實(shí)體都有一個(gè)errors屬性,它為你提供了一個(gè)字段與錯誤消息相映射的字典表。

>>> f = ContactForm({'subject': 'Hello', 'message': ''})
>>> f.errors                                    # 不合法的賦值的字段,會成為字典里的items
{'message': [u'This field is required.']}
>>> f['subject'].errors
[]




清理數(shù)據(jù)

>>> f = ContactForm({subject': Hello, email: adrian@example.com, message: Nice site!})
>>> f.is_valid()  # 如果一個(gè)Form實(shí)體的數(shù)據(jù)是合法的,它就會有一個(gè)可用的cleaned_data屬性。
True
>>> f.cleaned_data    #  這是一個(gè)包含干凈的提交數(shù)據(jù)的字典。
{message': uNice site!, email: uadrian@example.com, subject: uHello}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

py dj j
AI