功能:在A網頁提交一個評論Forms_B,提交之后自動刷新頁面,能夠顯示剛剛的畫面
思路:利用一個已經創建的表單,通過視圖讓其在網頁中表現出來,填寫玩信息之后提交,會提交到一個新的視圖里面去做接受,接受之后重定向到另外一個地方。(是什么地方)
步驟:
一、在app里面的forms.py里面新建一個表單:
1 #blog/forms.py 2 from django import forms 3 4 class CommentForm(forms.Form): 5 ''' 6 評論表單 7 ''' 8 #author使用CharField字段,字段內使用三個參數,分別是widget, max_length, error_messages 9 author = forms.CharField( 10 #為各個需要渲染的字段指定渲染成什么Html組件,主要是為了添加css樣式 11 widget=forms.TextInput(attrs={"id": "author", "class": "comment_input", 12 "required": "required","size": "25", "tabindex": "1"}), 13 max_length=50,error_messages={"required":"username不能為空",}) 14 email = forms.EmailField(widget=forms.TextInput(attrs={"id":"email","type":"email","class": "comment_input", 15 "required":"required","size":"25", "tabindex":"2"}), 16 max_length=50, error_messages={"required":"email不能為空",}) 17 url = forms.URLField(widget=forms.TextInput(attrs={"id":"url","type":"url","class": "comment_input", 18 "size":"25", "tabindex":"3"}), 19 max_length=100, required=False) 20 comment = forms.CharField(widget=forms.Textarea(attrs={"id":"comment","class": "message_input", 21 "required": "required", "cols": "25", 22 "rows": "5", "tabindex": "4"}), 23 error_messages={"required":"評論不能為空",}) 24 article = forms.CharField(widget=forms.HiddenInput())
二、在文章詳情視圖里面讓接入表單
1 def article(request): 2 # 評論表單 3 comment_form = CommentForm({'author': request.user.username, 4 'email': request.user.email, 5 'url': request.user.url, 6 'article': id} if request.user.is_authenticated() else{'article': id}) 7 return render(request, 'article.html', locals())
三、在模板中將視圖體現出來
1 <form action="{% url 'comment_post' %}" method="post"> 2 {% csrf_token %} 3 <p>{{ comment_form.author }} 4 <label for="author">Name (required)</label></p> 5 6 <p>{{ comment_form.email }} 7 <label for="email">Email (Will NOT be published) (required)</label></p> 8 9 <p>{{ comment_form.url }} 10 <label for="url">URL</label></p> 11 12 <p>{{ comment_form.comment }}</p> 13 14 <p> 15 {{ comment_form.article }} 16 <input name="submit" type="submit" id="submit" tabindex="5" value="Submit" class="button" /> 17 </p> 18 </form>
四、模板中的提交鏈接到URL中
url(r'^comment/post/$', comment_post, name='comment_post'),
五、在視圖中接收提交的內容,並且重定向
1 # 提交評論 2 def comment_post(request): 3 try: 4 #獲取表單內填入的內容 5 comment_form=CommentForm(request.POST) 6 #進行驗證的第一個表單驗證 7 if comment_form.is_vaild(): 8 #獲取表單信息 9 #cleaned_data()用來把接收到的文字清洗為符合django的字符 10 #create是一個在一步操作中同時創建對象並且保存的便捷方法。 11 comment=Comment.objects.create(username=comment_form.cleaned_data["author"], 12 eamil=comment_form.cleaned_data["email"], 13 url=comment_form.cleaned_data["url"], 14 content=comment_form.cleaned_data["comment"], 15 article_id=comment_form.cleaned_data["article"], 16 #如果用戶已經登錄,則獲取已經登錄的用戶,非登錄用戶將返回None 17 #此處用的if語句有些特殊。 18 user=request.user if request.user.is_authenticated() else None) 19 comment.save() #保存實例 20 else: 21 return render(request, "failure.html", {"reason":comment_form.erros}) 22 except Exception as e: 23 logger.error(e) 24 #重定向到進來之前的網頁 25 #HTTP_REFERER是http的頭文件的一部分,當瀏覽器向web服務器發送請求的時候,一般會帶上Referer,告訴服務器我是從哪個頁面鏈接過來的,服務器借此獲得一些信息用於處理。 26 return redirect(request.META['HTTP_REFERER'])
''' #判斷用戶是不是登錄,也可以用這個寫法,79行的寫法也很簡單 if request.user.is_authenticated(): #判斷用戶是否登錄 user=request.user #獲取已經登錄的用戶 else: user=request.user #非登錄用戶將返回AnonymousUser '''
request.META是一個里面包含了所有本次http請求的Header信息,比如用戶IP,用戶Agent
常見的鍵值有:
HTTP_REFERER,進站前鏈接網頁,如果有的話。
redirec是重定向
redirec是重定向