Django2.0中文(Form)

2022-05-14 13:58:55 浏览数 (1)

1 HttpRequest的对象属性: request.path //// /aa/ request.get_host() //主机名 request.get_full_path() // /admin?r=xx request.is_secure() /// https?? request.META //字典 HTTP_REFERER HTTP_USER_AGENT REMOTE_ADDR

request.GET / request.POST 2

urls.py

views.py

def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q'] else: message = 'You submitted an empty form.' return HttpResponse(message) 3 from django.http import HttpResponse from django.shortcuts import render_to_response from mysite.books.models import Book

def search_form(request): return render_to_response('search_form.html')

def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] books = Book.objects.filter(title__icontains=q) return render_to_response('search_results.html', {'books': books, 'query': q}) else: return render_to_response('search_form.html', {'error': True})

<html> <head> <title>Search</title> </head> <body> {% if error %} <p style="color: red;">Please submit a search term.</p> {% endif %} <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>

///////常用post 处理模版 4 def search(request): error = False if 'q' in request.GET: q = request.GET['q'] if not q: error = True else: books = Book.objects.filter(title__icontains=q) return render_to_response('search_results.html', {'books': books, 'query': q}) return render_to_response('search_form.html', {'error': error})

<html> <head> <title>Search</title> </head> <body> {% if error %} <p style="color: red;">Please submit a search term 20 characters or shorter.</p> {% endif %} <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>

5 errors list <html> <head> <title>Search</title> </head> <body> {% if errors %} <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>

6 <html> <head> <title>Contact us</title> </head> <body> <h1>Contact us</h1>

代码语言:javascript复制
{% 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"></p>
    <p>Your e-mail (optional): <input type="text" name="email"></p>
    <p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
    <input type="submit" value="Submit">
</form>

</body> </html>

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( request.POST['subject'], request.POST['message'], request.POST.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') return render_to_response('contact_form.html', {'errors': errors})

7

views.py

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( request.POST['subject'], request.POST['message'], request.POST.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') return render_to_response('contact_form.html', { 'errors': errors, 'subject': request.POST.get('subject', ''), 'message': request.POST.get('message', ''), 'email': request.POST.get('email', ''), })

contact_form.html

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

代码语言:javascript复制
{% 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>

8 from django import forms required=True from django import forms

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

f.as_ul() f.as_table() f.as_p() f.is_valid() //是否验证 f.cleaned_data 最终,如果一个Form实体的数据是合法的,它就会有一个可用的cleaned_data属性。 这是一个包含干净的提交数据的字典。 Django的form框架不但校验数据,它还会把它们转换成相应的Python类型数据,这叫做清理数据

9 forms.Form的用法:

views.py

from django.shortcuts import render_to_response from mysite.contact.forms import ContactForm

def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render_to_response('contact_form.html', {'form': form})

contact_form.html

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

代码语言:javascript复制
{% if form.errors %}
    <p style="color: red;">
        Please correct the error{{ form.errors|pluralize }} below.
    </p>
{% endif %}

<form action="" method="post">
    <table>
        {{ form.as_table }}
    </table>
    <input type="submit" value="Submit">
</form>

</body> </html>

10 改变使用的标签 widget forms.Textarea from django import forms

class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea )

11 max_length 12 initial 设置表单初始值 def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm( initial={'subject': 'I love your site!'} ) return render_to_response('contact_form.html', {'form': form})

13 自定义数据校验方法:clean_xxxx from django import forms

class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea)

代码语言:javascript复制
def clean_message(self):
    message = self.cleaned_data['message']
    num_words = len(message.split())
    if num_words < 4:
        raise forms.ValidationError("Not enough words!")
    return message

Django的form系统自动寻找匹配的函数方法,该方法名称以clean_开头,并以字段名称结束。 如果有这样的方法,它将在校验时被调用。

特别地,clean_message()方法将在指定字段的默认校验逻辑执行* 之后* 被调用。(本例中,在必填CharField这个校验逻辑之后。)因为字段数据已经被部分处理,所以它被从self.cleaned_data中提取出来了。同样,我们不必担心数据是否为空,因为它已经被校验过了。

我们简单地使用了len()和split()的组合来计算单词的数量。 如果用户输入字数不足,我们抛出一个forms.ValidationError型异常。这个异常的描述会被作为错误列表中的一项显示给用户。

在函数的末尾显式地返回字段的值非常重要。 我们可以在我们自定义的校验方法中修改它的值(或者把它转换成另一种Python类型)。 如果我们忘记了这一步,None值就会返回,原始的数据就丢失掉了。

14 email = forms.EmailField(required=False, label='Your e-mail address' ) 15 errors list css <style type="text/css"> ul.errorlist { margin: 0; padding: 0; } .errorlist li { background-color: red; color: white; display: block; font-size: 10px; margin: 0 0 3px; padding: 4px 5px; } </style>

16 <html> <head> <title>Contact us</title> </head> <body> <h1>Contact us</h1>

代码语言:javascript复制
{% if form.errors %}
    <p style="color: red;">
        Please correct the error{{ form.errors|pluralize }} below.
    </p>
{% endif %}

<form action="" method="post">
    <div class="field">
        {{ form.subject.errors }}
        <label for="id_subject">Subject:</label>
        {{ form.subject }}
    </div>
    <div class="field">
        {{ form.email.errors }}
        <label for="id_email">Your e-mail address:</label>
        {{ form.email }}
    </div>
    <div class="field">
        {{ form.message.errors }}
        <label for="id_message">Message:</label>
        {{ form.message }}
    </div>
    <input type="submit" value="Submit">
</form>

</body> </html>

0 人点赞