入门笔记翻译整理自:https://docs.djangoproject.com/en/1.8/topics/
*该笔记将对各个模块进行单独介绍
*Class-based views
视图是接受请求并返回响应的可调用对象。
1. 用法举例
1 from django.conf.urls import url 2 from django.views.generic import TemplateView 3 4 urlpatterns = [ 5 url(r‘^about/‘, TemplateView.as_view(template_name="about.html")), 6 ]
或者
1 # some_app/views.py 2 from django.views.generic import TemplateView 3 4 class AboutView(TemplateView): 5 template_name = "about.html"
1 # urls.py 2 from django.conf.urls import url 3 from some_app.views import AboutView 4 5 urlpatterns = [ 6 url(r‘^about/‘, AboutView.as_view()), 7 ]
2. 比较两种视图
普通视图:
1 from django.http import HttpResponse 2 3 def my_view(request): 4 if request.method == ‘GET‘: 5 # <view logic> 6 return HttpResponse(‘result‘)
基于类的视图:
1 from django.http import HttpResponse 2 from django.views.generic import View 3 4 class MyView(View): 5 def get(self, request): 6 # <view logic> 7 return HttpResponse(‘result‘)
1 # urls.py 2 from django.conf.urls import url 3 from myapp.views import MyView 4 5 urlpatterns = [ 6 url(r‘^about/‘, MyView.as_view()), 7 ]
3. 内置基于类的通用视图
略过。
4. 类通用视图处理表单
例如:
1 # forms.py 2 3 from django import forms 4 5 class ContactForm(forms.Form): 6 name = forms.CharField() 7 message = forms.CharField(widget=forms.Textarea) 8 9 def send_email(self): 10 # send email using the self.cleaned_data dictionary 11 pass
1 # views.py 2 3 from myapp.forms import ContactForm 4 from django.views.generic.edit import FormView 5 6 class ContactView(FormView): 7 template_name = ‘contact.html‘ 8 form_class = ContactForm 9 success_url = ‘/thanks/‘ 10 11 def form_valid(self, form): 12 # This method is called when valid form data has been POSTed. 13 # It should return an HttpResponse. 14 form.send_email() 15 return super(ContactView, self).form_valid(form)
5. 在类视图中使用混合体(mixins)
略。
-- The End --
时间: 2024-11-08 23:10:03