Django(Chapter07 表单)

1. HttpRequest对象包含当前请求URL的一些信息:
                         
属性/方法 说明 举例
request.path 除域名以外的请求路径,以正斜杠开头 "/hello/"
request.get_host 主机名(比如,通常所说的域名) "172.0.0.1:8000"or "www.example.com"
request.get_full_path() 请求路径,可能包含查询字符串 "/hello/?print=true"
request.is_secure 如果通过HTTPS访问,则此方法返回True,否则返回False True或者False

  
2. 有关request的其他信息:
   request.META是一个Python字典,包含了所有本次HTTP请求的Header信息。
   这个字典中几个常见的键值:
       HTTP_REFERER, HTTP_USER_AGENT, REMOTE_ADDR
   request.GET和request.POST,二者都是类字典对象,可以通过它们来访问
   GET和POST数据。

3. POST数据是来自HTML中的<form>标签提交的,而GET数据可能来自<form>提交也可能
   是URL中的查询字符串(the query string)。


4. 一个简单的例子:
   在books app中
   4.1 建立好models.py,建立好数据库
   4.2 建立好App,并添加到settings.py文件中
      
        INSTALLED_APPS = (
            'mysite.books',
        )
       

   4.3 添加好模板的路径,在settings.py中设置
      
        import os
        TEMPLATE_DIRS = (
            os.path.join(os.path.dirname(__file__), 'books').replace('\\','/'),                  
        ) 
       

   4.4 添加好url
   4.5 添加视图(views.py):
      
        from django.shortcuts import render_to_response

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

        from django.http import HttpResponse
        from django.shortcuts import render_to_response
        from mysite.books.models import Book

        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)
                return render_to_response('search_results.html',{'books':books, 'query':q})

            return render_to_response('search_form.html', { 'errors': errors })

       


   4.6 html显示
   search_form.html
  
    <html>
    <head>
        <title>Search</title>
    </head>

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

   这里的action="",代表了和当前请求在同一级目录。

   search_results.html
  
    <p>You searched for:<strong>{{ query }}</strong></p>
    {% if books %}
        <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
        <ul>
            {% for book in books %}
            <li>{{ book.title }}</li>
            {% endfor %}
        </ul>
    {% else %}
        <p>No books matched your search criteria.</p>
    {% endif %}
   


5. 第一个Form类
   Django带有一个form库,称为django.forms
   这个类做了几件事情:
       a. 将自己显示成HTML
          新建一个contacts app,并建立一个forms.py,代码如下
         
           from django import forms

           class ContactForm(forms.Form):
               subject = forms.CharField(min_length=5,max_length=100)
               email = forms.EmailField(required=False, label='Your e-mail address')
               message = forms.CharField(widget=forms.Textarea)

              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
          

       b. 提供验证
          >>> from contact.forms import ContactForm
          >>> f = ContactForm()
          >>> print f         
          >>> print f.as_ul()
          >>> print f.as_p()
          >>> print f['subject']
          >>> f = ContactForm({'subject':'Hello', 'email':'[email protected]', 'message':'Nice site!'})
          >>> f.is_bound
          >>> f.is_valid()
          >>> f['subject'].errors
          >>> f=ContactForm({'subject':'Hello','message':''})
          >>> f.errors
   2 contacts app中的views.py
    
      from django.core.mail import send_mail
      from django.shortcuts import render_to_response
      from mysite.contacts.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', '[email protected]'),
                    ['[email protected]'],
                    )
            return HttpResponseRedirect('/contacts/thanks/')
          else:
              form = ContactForm(
                initial={'subject':'I love your site!'})

         return render_to_response('contact_form.html',{'form':form})
     

    
    3. html(contact_form.html)
    
     <html>                                                                
    <head>
        <title>Contact us</title>
        <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>
    </head>

    <body>
        <h1>Contact us</h2>

        {% if form.errors %}
            <p style="color:red;">
            Please correct the error{{ form.errors|pluralize }} below.
            </p>
        {% endif %}

        <form action="" method="post">
            {% csrf_token %}
            <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>
     

你可能感兴趣的:(django,表单)