102django_cbv-創(chuàng)新互聯(lián)

目錄

成都創(chuàng)新互聯(lián)不只是一家網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司;我們對(duì)營(yíng)銷、技術(shù)、服務(wù)都有自己獨(dú)特見(jiàn)解,公司采取“創(chuàng)意+綜合+營(yíng)銷”一體化的方式為您提供更專業(yè)的服務(wù)!我們經(jīng)歷的每一步也許不一定是最完美的,但每一步都有值得深思的意義。我們珍視每一份信任,關(guān)注我們的成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)質(zhì)量和服務(wù)品質(zhì),在得到用戶滿意的同時(shí),也能得到同行業(yè)的專業(yè)認(rèn)可,能夠?yàn)樾袠I(yè)創(chuàng)新發(fā)展助力。未來(lái)將繼續(xù)專注于技術(shù)創(chuàng)新,服務(wù)升級(jí),滿足企業(yè)一站式營(yíng)銷型網(wǎng)站建設(shè)需求,讓再小的成都品牌網(wǎng)站建設(shè)也能產(chǎn)生價(jià)值!

django.views.generic.TemplateView..1

django.views.generic.View..2

類的繼承和覆蓋:...5

自定義LoginRequiredMixin:...5

通用視圖:...6

django.views.generic.ListView..6

django.views.generic.DetailView..8

django.views.generic.FormView:...9

django.views.generic.CreateView:...9

django.views.generic.UpdateView:...9

cbv,class based view:

基于類的視圖,使編寫view更簡(jiǎn)潔,有復(fù)雜的繼承關(guān)系;

CBV和FBV兩者各有優(yōu)劣;

102django_cbv

django.views.generic.TemplateView

102django_cbv

UML圖;

Mixin增強(qiáng)功能,提供一些方法,如TemplateResponseMixin提供了render_to_response()渲染模板,ContextMixin提供get_context_data();

View提供get,post訪問(wèn)入口;

例,ver1:

def about(request):?? #ver1,F(xiàn)BV用法

return render(request, 'blog/about.html')

url(r'^about/', views.about, name='about'),

例,ver2:

from django.views.generic import TemplateView

app_name = 'blog'

urlpatterns = [

url(r'^$', views.index, name='index'),

url(r'^login/', views.auth_login, name='login'),

url(r'^logout/', views.auth_logout, name='logout'),

# url(r'^about/', views.about, name='about'),

url(r'^about/', TemplateView.as_view(template_name='blog/about.html')),?? #ver2,CBV用法1

]

例,ver3:

from django.views.generic import TemplateView

class AboutView(TemplateView):?? #ver3,CBV用法2

template_name = 'blog/about.html'

url(r'^about/', AboutView.as_view()),

django.views.generic.View

View源碼:

該類在沒(méi)更改原來(lái)django邏輯的情況下,可用于編寫view,每個(gè)http請(qǐng)求會(huì)使用對(duì)應(yīng)類的同名的方法進(jìn)行處理;

class View(object):

"""

Intentionally simple parent class for all views. Only implements

dispatch-by-method and simple sanity checking.

"""

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

def __init__(self, **kwargs):?? #檢查as_view()傳入的參數(shù)是否在類中定義

"""

Constructor. Called in the URLconf; can contain helpful extra

keyword arguments, and other things.

"""

# Go through keyword arguments, and either save their values to our

# instance, or raise an error.

for key, value in six.iteritems(kwargs):

setattr(self, key, value)

@classonlymethod

def as_view(cls, **initkwargs):?? #返回的是一個(gè)函數(shù)對(duì)象(裝飾器);template_name=’blog/about.html’模板名作為參數(shù)傳,或在類屬性中定義,傳入的參數(shù)可覆蓋類中定義的屬性

"""

Main entry point for a request-response process.

"""

for key in initkwargs:

if key in cls.http_method_names:

raise TypeError("You tried to pass in the %s method name as a "

"keyword argument to %s(). Don't do that."

????????% (key, cls.__name__))

if not hasattr(cls, key):

raise TypeError("%s() received an invalid keyword %r. as_view "

"only accepts arguments that are already "

"attributes of the class." % (cls.__name__, key))

def view(request, *args, **kwargs):

self = cls(**initkwargs)

if hasattr(self, 'get') and not hasattr(self, 'head'):

self.head = self.get

self.request = request

self.args = args

self.kwargs = kwargs

return self.dispatch(request, *args, **kwargs)

view.view_class = cls

view.view_initkwargs = initkwargs

# take name and docstring from class

update_wrapper(view, cls, updated=())

# and possible attributes set by decorators

# like csrf_exempt from dispatch

update_wrapper(view, cls.dispatch, assigned=())

return view

def dispatch(self, request, *args, **kwargs):?? #根據(jù)用戶的request method路由到get、post方法

# Try to dispatch to the right method; if a method doesn't exist,

# defer to the error handler. Also defer to the error handler if the

# request method isn't on the approved list.

???if request.method.lower() in self.http_method_names:

handler = getattr(self, request.method.lower(), self.http_method_not_allowed)

else:

handler = self.http_method_not_allowed

return handler(request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):

logger.warning(

'Method Not Allowed (%s): %s', request.method, request.path,

extra={'status_code': 405, 'request': request}

)

return http.HttpResponseNotAllowed(self._allowed_methods())

def options(self, request, *args, **kwargs):

"""

Handles responding to requests for the OPTIONS HTTP verb.

"""

response = http.HttpResponse()

response['Allow'] = ', '.join(self._allowed_methods())

response['Content-Length'] = '0'

return response

def _allowed_methods(self):

return [m.upper() for m in self.http_method_names if hasattr(self, m)]

例,ver1,F(xiàn)BV:

def my_view(request):

if request.method == 'GET':

return HttpResponse('get it')

elif request.method == 'POST':

return HttpResponse('post it')

elif request.method == 'HEAD':

return HttpResponse('head it')

例,ver2,CBV,省去了if判斷:

from django.views.generic import View

class MyView(View):

def get(self, request):

return HttpResponse('get it')

def post(self, request):

return HttpResponse('post it')

def head(self, request):

return HttpResponse('head it')

# url(r'^myview', views.my_view),

url(r'^myview', MyView.as_view()),

類的繼承和覆蓋:

class GreetingView(View):

greeting = 'good day'

def get(self, request):

return HttpResponse(self.greeting)

class MorningGreetingView(GreetingView):

greeting = 'morning to yo'

自定義LoginRequiredMixin:

class LoginRequiredMixin:

@classmethod

def as_view(cls, **initkwargs):

view = super(LoginRequiredMixin, cls).as_view(**initkwargs)

return login_required(view)

class MyView(LoginRequiredMixin, View):

pass

裝飾類:

from django.utils.decorators import method_decorator

class ProtectedView(TemplateView):

template_name = 'blog/about.html'

@method_decorator(login_required)

def dispatch(self, *args, **kwargs):

return super(ProtectedView, self).dispatch(*args, **kwargs)

通用視圖:

generic class based view和class based view概念上不是一回事;

class based view是用類的方式寫view;

generic class based view是用class based view方式將常用的CRUD封裝成可擴(kuò)展的類,使用時(shí)直接繼承,快速實(shí)現(xiàn);

django.views.generic.ListView

多對(duì)象;

默認(rèn)提供的上下文是object_list,也可用context_object_name指定;

queryset、get_queryset、model;

可指定template_name;

102django_cbv

例,ver1:

def publisher_list(request):

publishers = Publisher.objects.all()

return render(request, 'books/publishers.html', {'publishers': publishers})

例,ver2:

from django.views.generic import ListView

class PublisherList(ListView):?? #默認(rèn)去找suffix為list的模板,即publisher_list.html;publisher_list.html模板;默認(rèn)的context為object_list

model = Publisher?? #返回Publisher.object.all(),多對(duì)象

# template_name = 'books/publishers.html'?? #

# context_object_name =??? #提供上下文

# queryset = Publisher.objects.all()?? #model|queryset|get_queryset()三者關(guān)系

# def get_queryset(self):

#?????? return Publisher.objects.all()

<body>

<ul>

{% for publisher in object_list%}

<h4>{{ publisher }}</h4>

{% endfor %}

</ul>

</body>

# url(r'^$', views.publisher_list, name='publishers'),

url(r'^$', PublisherList.as_view(), name='publisher'),

django.views.generic.DetailView

單個(gè)對(duì)象的詳情;

get_context_data();

context_object_name;

102django_cbv

<body>

<ul>

<h4>{{ publisher }}</h4>

{% for book in book_list %}

{{ book }}<br/>

{{ book.publisher }}

{% endfor %}

</ul>

</body>

from django.views.generic import DetailView

from .models import Book

class PublisherDetail(DetailView):

model = Publisher

context_object_name = 'publisher'

def get_context_data(self, **kwargs):

context = super(PublisherDetail, self).get_context_data(**kwargs)

context['book_list'] = Book.objects.all()

return context

url(r'^$', PublisherList.as_view(), name='publisher'),

url(r'^(?P<pk>[0-9]+)/$', PublisherDetail.as_view()),

django.views.generic.FormView:

class PublisherForm(forms.Form):

name = forms.CharField(label=_('Your name'), max_length=30)

address = forms.CharField(max_length=50)

city = forms.CharField(max_length=60)

state_province = forms.CharField(max_length=30)

country = forms.CharField(max_length=20)

website = forms.CharField(max_length=50)

def send_mail(self):

print('~~~~~~~~~~~send_mail()?? OK')

from django.views.generic import FormView

class PublisherView(FormView):

form_class = PublisherForm

template_name = 'books/books_add.html'

success_url = '/books/'

def form_valid(self, form):

form.send_mail()

return super(PublisherView, self).form_valid(form)

url(r'^$', PublisherList.as_view(), name='publisher'),

url(r'^add', PublisherView.as_view()),

django.views.generic.CreateView:

根據(jù)model和fields動(dòng)態(tài)構(gòu)建form,另form_class = forms.AuthorForm等價(jià)于model和fields;

model + fields = form_class,另get_form_class、get_form;

template_name,不指定默認(rèn)找suffix為_(kāi)form.html;

success_url,get_success_url;

form_valid()、form_invalid(),注意重寫都要調(diào)用父類方法;

get_context_data;

success_message、get_success_message;

102django_cbv

from django.views.generic import CreateView

from .models import Author

class AuthorCreate(CreateView):

model = Author

fields = ['first_name', 'last_name', 'email']

success_url = '/books/'

def form_valid(self, form):

return super().form_valid(form)

def get_context_data(self, **kwargs):

context = {'extra': 'some context'}

kwargs.update(context)

return super().get_context_data(**kwargs)

url(r'^author/', AuthorCreate.as_view()),

django.views.generic.UpdateView:

102django_cbv

django.views.generic.DeleteView:

要有刪除確認(rèn)頁(yè)面;

102django_cbv


另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

網(wǎng)頁(yè)題目:102django_cbv-創(chuàng)新互聯(lián)
當(dāng)前URL:http://www.bm7419.com/article42/iphhc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開(kāi)發(fā)、品牌網(wǎng)站制作App設(shè)計(jì)、品牌網(wǎng)站建設(shè)電子商務(wù)、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)