django中搜索表單

http://www.qwolf.com/?p=162

 

1.搜索
(1) 在URLconf (mysite.urls )添加搜索視圖。
(r’^search/$’,'mysite.books.views.search’)
(2) 在視圖模塊(mysite.books.views )中寫這個 search 視圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.db.models import Q
from django.shortcuts import render_to_response
from books.models import Book

def search(request):
    query = request.GET.get('q', '')
    if query:
        qset = (
            Q(title__icontains=query) |
            Q(authors__first_name__icontains=query) |
            Q(authors__last_name__icontains=query)
        )
        results = Book.objects.filter(qset).distinct()
    else:
        results = []
    return render_to_response("books/search.html", {
        "results": results,
        "query": query
    })

(3)添加模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Search{% if query %} Results{% endif %}</title>
</head>
<body>
  <h1>Search</h1>
  <form action="." method="GET">
    <label for="q">Search: </label>
    <input type="text" name="q" value="{{ query|escape }}"/>
    <input type="submit" value="Search"/>
  </form>

  {% if query %}
    <h2>Results for "{{ query|escape }}":</h2>

    {% if results %}
      <ul>
      {% for book in results %}
        <li>{{ book|escape }}
      {% endfor %}
      </li></ul>
    {% else %}
      <p>No books found</p>
    {% endif %}
  {% endif %}
</body>
</html>


2.回饋表單
(1)添加URL (r’^contact/$’, ‘mysite.books.views.contact’)
(2)在books目錄下建forms.py 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/local/bin/python
# coding: utf-8

from django import forms

TOPIC_CHOICES = (
    ('general', 'General enquiry'),
    ('bug', 'Bug report'),
    ('suggestion', 'Suggestion'),
)

class ContactForm(forms.Form):
    topic = forms.ChoiceField(choices=TOPIC_CHOICES)
    message = forms.CharField()
    sender = forms.EmailField(required=False)
    #自定義驗證
    def clean_message(self):
        message = self.cleaned_data.get('message', '')
        num_words = len(message.split())
        if num_words < 4:
           raise forms.ValidationError("Not enough words!")
        return message

此處需注意添加頂端兩行,否則中文註釋會出錯
(3)添加視圖函數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import ContactForm
from django.core.mail import send_mail
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
           topic = form.cleaned_data['topic']
           message = form.cleaned_data['message']
           sender = form.cleaned_data.get('sender', '[email protected]')
           send_mail(
               'Feedback from your site, topic: %s' % topic,
               message, sender,
               ['[email protected]']
           )
           return HttpResponseRedirect('/contact/thanks/')                      

    else:
        form = ContactForm()
   
    return render_to_response('contact.html', {'form': form})

爲使發email成功,需配置settings.py

1
2
3
4
5
EMAIL_HOST=127.0.0.1' #你的smtp 服務器ip 地址或名稱
EMAIL_PORT=None #不處理就用Noe,否則指明port
EMAIL_HOST_USER='
' #現在大部分郵箱都要求你輸入 郵箱的全名
EMAIL_HOST_PASSWORD='
' #你的口令
EMAIL_USE_TLS=None #不處理就用None

(4)添加模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Contact us</title>

</head>
<body>
    <h1>Contact us</h1>
    <form action="." method="POST">
        <div class="fieldWrapper">
            {{ form.topic.errors }}
            <label for="id_topic">Kind of feedback:</label>
            {{ form.topic }}
        </div>
        <div class="fieldWrapper">
            {{ form.message.errors }}
            <label for="id_message">Your message:</label>
            {{ form.message }}
        </div>
        <div class="fieldWrapper">
            {{ form.sender.errors }}
            <label for="id_sender">Your email (optional):</label>
            {{ form.sender }}
        </div>
        <p><input type="submit" value="Submit"/></p>
    </form>
   
</body>
</html>

3. 從模型創建表單
(1)創建URL
(r'^add_publisher/$', 'mysite.books.views.add_publisher')
(2)在forms.py創建一個新Form

1
2
3
4
5
from django import forms
from models import *
class PublisherForm(forms.ModelForm):
    class Meta:
        model = Publisher

(3)創建視圖函數

1
2
3
4
5
6
7
8
9
10
from forms import ContactForm,PublisherForm
def add_publisher(request):
    if request.method == 'POST':
        form = PublisherForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/add_publisher/thanks/')
    else:
        form = PublisherForm()
    return render_to_response('books/add_publisher.html', {'form': form})

(4)創建模板文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Add Publisher</title>
</head>
<body>
    <h1>Add Publisher</h1>
    <form action="." method="POST">
        <table>
            {{ form.as_table }}
        </table>
        <p><input type="submit" value="Submit"/></p>
    </form>
</body>
</html>

轉載請註明來源:http://www.qwolf.com/?p=162
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章