Ag baint úsáide as meascáin le tuairimí rangbhunaitheLink to this heading
Soláthraíonn tuairimí rang-bhunaithe ionsuite Django go leor feidhmiúlachta, ach b'fhéidir gur mhaith leat cuid de a úsáid ar leithligh. Mar shampla, b'fhéidir gur mhaith leat dearcadh a scríobh a léiríonn teimpléad chun an freagra HTTP a dhéanamh, ach ní féidir leat:class: ~django.views.generic.base.templateView a úsáid; b'fhéidir nach gcaithfidh tú teimpléad a rinneadh ach ar POST `, le GET` ag déanamh rud éigin eile go hiomlán. Cé go bhféadfá: class: ~django.template.response.templateResponse a úsáid go díreach, is dócha go mbeidh cód dúblach mar thoradh air seo.
Ar an gcúis seo, soláthraíonn Django roinnt meascáin freisin a sholáthraíonn feidhmiúlacht níos scoite. Tá rindreáil teimpléad, mar shampla, ionfhabhtaithe in:class: ~Django.Views.Generic.Base.TemplateResponseMixin. Tá doiciméadú tagartha Django: doc: `doiciméadú iomlán de na meascáin go lé@@</ref/class-based-views/mixins> ir'.
Freagraí comhthéacs agus teimpléLink to this heading
Cuirtear dhá mheascán lárnach ar fáil a chuidíonn le comhéadan comhsheasmhach a sholáthar chun oibriú le teimpléid i dtuairimí rangbhunaithe.
TemplateResponseMixinEvery built in view which returns a
TemplateResponsewill call therender_to_response()method thatTemplateResponseMixinprovides. Most of the time this will be called for you (for instance, it is called by theget()method implemented by bothTemplateViewandDetailView); similarly, it's unlikely that you'll need to override it, although if you want your response to return something not rendered via a Django template then you'll want to do it. For an example of this, see the JSONResponseMixin example.Glaonn ``render_to_response () ``féin: meth: ~django.views.generic.base.templateResponseMixin.get_template_names, a fhéachfaidh suas:attr: ~Django.Views.Generic.Base.TemplateResponseMixin.Template_Names ar an radharc rang-bhunaithe; dhá mixins eile (:class: ~Django.Views.Generic.Detail.SingleObjectTemplateResponseMixin agus:class: ~Django.Views.Generic.List.MultipleObjectTemplateResponseMixin) athsháraigh é seo chun réamhshocruithe níos solúbtha a sholáthar agus tú ag déileáil le rudaí iarbhír.
ContextMixinEvery built in view which needs context data, such as for rendering a template (including
TemplateResponseMixinabove), should callget_context_data()passing any data they want to ensure is in there as keyword arguments.get_context_data()returns a dictionary; inContextMixinit returns its keyword arguments, but it is common to override this to add more members to the dictionary. You can also use theextra_contextattribute.
Tuairimí cineálacha aicmbunaithe Django a thógáilLink to this heading
Féachaimis ar an gcaoi a ndéantar dhá cheann de thuairimí cineálacha aicmbunaithe Django a thógtar as meascáin a sholáthraíonn feidhmiúlacht scoite. Déanfaimid breithniú:class: ~django.views.generic.detail.detailView, a thugann dearcadh “mionsonraithe” ar réad, agus:class: ~django.views.generic.list.listView, a thabharfaidh liosta rudaí, de ghnáth ó shuíomh ceisteanna, agus iad a leathanaigh roghnach. Tabharfaidh sé seo ceithre mheascáin in aithne dúinn a sholáthraíonn feidhmiúlacht úsáideach eatarthu agus iad ag obair le réad Django amháin, nó le rudaí iolracha.
Tá meascáin ann freisin leis na tuairimí eagarthóireachta cineálacha (:class: ~django.views.generic.edit.formView, agus na radhairc samhail-shonrach: class: ~django.views.generic.edit.createView, :class: ~django.views.generic.edit.updateView agus:class: ~django.views.generic.Edit.deleteView), agus sna tuairimí cineálacha dáta-bhunaithe. Tá siad seo clúdaithe sa doiciméadú tagartha: 'mixin tagartha'</ref/class-based-views/mixins>.
``DetailView ``: ag obair le réad amháin DjangoLink to this heading
Chun mionsonraí réada a thaispeáint, ní mór dúinn dhá rud a dhéanamh go bunúsach: ní mór dúinn breathnú suas ar an réad agus ansin caithfimid a:class: ~django.template.Response.TemplateResponse le teimpléad oiriúnach, agus an réad sin mar chomhthéacs.
To get the object, DetailView
relies on SingleObjectMixin,
which provides a
get_object()
method that figures out the object based on the URL of the request (it
looks for pk and slug keyword arguments as declared in the
URLConf, and looks the object up either from the
model attribute
on the view, or the
queryset
attribute if that's provided). SingleObjectMixin also overrides
get_context_data(),
which is used across all Django's built in class-based views to supply
context data for template renders.
To then make a TemplateResponse,
DetailView uses
SingleObjectTemplateResponseMixin, which
extends TemplateResponseMixin, overriding
get_template_names() as
discussed above. It actually provides a fairly sophisticated set of options,
but the main one that most people are going to use is
<app_label>/<model_name>_detail.html. The _detail part can be changed
by setting
template_name_suffix
on a subclass to something else. (For instance, the generic edit views use _form for create and
update views, and _confirm_delete for delete views.)
ListView: ag obair le go leor rudaí DjangoLink to this heading
Leanann liostaí rudaí thart ar an bpatrún céanna: teastaíonn liosta rudaí (leathanaithe b'fhéidir) uainn, de ghnáth a:class: ~django.db.models.query.querySet, agus ansin ní mór dúinn a dhéanamh a:class: ~django.template.response.templateResponse le teimpléad oiriúnach ag baint úsáide as an liosta rudaí sin.
Chun na rudaí a fháil, úsáideann :class: ~Django.Views.Generic.List.ListView: Class: ~Django.Views.Generic.List.MultipleObjectMixin, a sholáthraíonn an bheath:meth: ~Django.Views.Generic.List.MultipleObjectMixin.get_QuerySet agus:meth: ~django..S.Generic.List.MultipleObjectMixin.Paginate_QuerySet. Murab ionann agus la:class: ~django.views.generic.detail.singleObjectMixin, ní gá codanna den URL a chur amach chun an tacar ceisteanna a oibriú leis, mar sin úsáideann an réamhshocraithe:attr: ~Django.Views.Generic.List.MultipleObjectMixin.QuerySet nó:attr: ~Django.Views.Generic.List.MultipleObjectMixin.QuerySet nó:attr: ~Django.Views.Generic.Generic.List.MultipleObjectMixin.QuerySet nó: attr: ~django.views.Generic.Generic.List.MultipleObjectMixin.Tréith IC.List.MultipleObjectMixin.Model ar an rang amharc. Cúis choitianta chun athrú: meth: ~django.views.generic.list.multipleObjectMixin.get_querySet anseo ná na rudaí a athrú go dinimiciúil, mar shampla ag brath ar an úsáideoir reatha nó poist a eisiamh sa todhchaí do bhlag.
MultipleObjectMixin also overrides
get_context_data() to
include appropriate context variables for pagination (providing
dummies if pagination is disabled). It relies on object_list being
passed in as a keyword argument, which ListView arranges for
it.
<django.views.generic.list.MultipleObjectTemplateResponseMixin><app_label><model_name>Chun a dhéanamh a:class: ~django.template.Response.TemplateResponse, :class: ListView ansin úsáideas:class: ~django.views.generic.list.multipleObjectTemplateResponseMiXin; mar le:class: ~django.views.generic.detail.singleObjectTemplateResponseMixin thuas, Sáraíonn sé seo get_template_names () ``chun: meth: `raon roghanna `a sholáthar, agus is é an ceann is coitianta a úsáidtear ná/_list.html``, agus an chuid _list á ghlacadh arís ó:attr: ~django.views.generic.list. MultipleObjectTemplateResponseMixin.Template_Name_Suffix tréith. (Úsáideann na tuairimí cineálacha dáta-bhunaithe iarmhairtí mar _archive, _archive_year` agus mar sin de chun teimpléid éagsúla a úsáid do na tuairimí speisialaithe liosta dáta-bhunaithe.)
Ag baint úsáide as meascáin radharc rang-bhunaithe DjangoLink to this heading
Anois chonaic muid conas a úsáideann tuairimí cineálacha aicmbunaithe Django na meascáin a chuirtear ar fáil, féachaimis ar bhealaí eile is féidir linn iad a chur le chéile. Táimid fós ag cur le chéile iad le tuairimí rang-bhunaithe ionsuite, nó tuairimí cineálacha eile bunaithe ar rang, ach tá raon fadhbanna níos annamh ann is féidir leat a réiteach ná mar a sholáthraíonn Django as an mbosca.
Ag baint úsáide as SingleObjectMixin le ViewLink to this heading
Más mian linn dearcadh rang-bhunaithe a scríobh nach bhfreagraíonn ach do POST `, déanfaimid fo-class:class: ~django.views.generic.base.view agus scríobhfaimid modh post () sa fho-rang. Mar sin féin más mian linn go n-oibreoidh ár bpróiseáil ar réad áirithe, a aithnítear ón URL, beidh muid ag iarraidh an fheidhmiúlacht a sholáthraí:class: ~django.views.generic.detail.singleObjectMixin.
We'll demonstrate this with the Author model we used in the generic
class-based views introduction.
views.pyfrom django.http import HttpResponseForbidden, HttpResponseRedirect
from django.urls import reverse
from django.views import View
from django.views.generic.detail import SingleObjectMixin
from books.models import Author
class RecordInterestView(SingleObjectMixin, View):
"""Records the current user's interest in an author."""
model = Author
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
# Look up the author we're interested in.
self.object = self.get_object()
# Actually record interest somehow here!
return HttpResponseRedirect(
reverse("author-detail", kwargs={"pk": self.object.pk})
)
Go praiticiúil is dócha gur mhaith leat an spéis i siopa luach eochair a thaifeadadh seachas i mbunachar sonraí coibhneasta, mar sin tá an beagán sin fágtha againn amach. Is é an t-aon chuid den dearcadh a chaithfidh a bheith buartha fao:class: ~django.views.generic.detail.singleObjectMixin an áit ar mhaith linn breathnú suas ar an údar atá suim againn ann, rud a dhéanann sé le glao ar ``self.get_object () ``. Tugann an mixin aire dúinn gach rud eile.
Is féidir linn é seo a cheangal isteach inár URLanna go héasca go leor:
urls.pyfrom django.urls import path
from books.views import RecordInterestView
urlpatterns = [
# ...
path(
"author/<int:pk>/interest/",
RecordInterestView.as_view(),
name="author-interest",
),
]
Tabhair faoi deara an grúpa ainmnithe pk`, a úsáideann: meth: ~django.views.generic.detail.singleObjectMixin.get_Object chun an sampla ``Author ``a fheiceáil suas. D'fhéadfá slag a úsáid freisin, nó aon cheann de na gnéithe eile de:class: ~Django.Views.Generic.Detail.SingleObjectMixin.
Ag baint úsáide as SingleObjectMixin le ``ListView ``Link to this heading
ListView provides built-in
pagination, but you might want to paginate a list of objects that are
all linked (by a foreign key) to another object. In our publishing
example, you might want to paginate through all the books by a
particular publisher.
Bealach amháin chun é seo a dhéanamh ná: class: ListView a chomhcheangal la:class: ~django.views.generic.detail.singleObjectMixin, ionas gur féidir leis an tacar ceisteanna don liosta leathanaigh leabhar crochadh as an foilsitheoir a aimsítear mar an réad aonair. D'fhonn é seo a dhéanamh, ní mór dúinn dhá cheist éagsúla a bheith againn:
- Tacar fiosrúcháin
Bookle húsáid ag:class: ~Django.Views.Generic.List.ListView <backwards-related-objects>Ós rud é go bhfuil rochtain againn ar an Foilsitheoir ``a gcuid leabhair ba mhaith linn a liostáil, déanaimid ``get_queryset ()` a shárú agus úsáidimid an
Publisher`:ref: `bainisteoir eochair eachtrach ar ais `.Publisherqueryset for use inget_object()Beidh muid ag brath ar chur i bhfeidhm réamhshocraithe
get_object () ``chun an réad ceart ``Publishera fháil. Mar sin féin, ní mór dúinn argóintqueryseta rith go sainráite mar ar shlí eile ghlaoigh cur i bhfeidhm réamhshocraitheget_object () ```get_queryset ()a bhfuil athbhreithnithe againn chun rudaíBooka thabhairt ar ais in ionadPublishercinn.
Anois is féidir linn ``PublisherDetailView ``nua a scríobh:
from django.views.generic import ListView
from django.views.generic.detail import SingleObjectMixin
from books.models import Publisher
class PublisherDetailView(SingleObjectMixin, ListView):
paginate_by = 2
template_name = "books/publisher_detail.html"
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=Publisher.objects.all())
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["publisher"] = self.object
return context
def get_queryset(self):
return self.object.book_set.all()
Tabhair faoi deara conas a shocraímid self.object laistigh de get () ``ionas gur féidir linn é a úsáid arís níos déanaí i ``get_context_data () agus get_queryset () ``. Mura socraíonn tú ``template_name, réamhshocróidh an teimpléad ar an rogha gnáth:class: ListView, arb é sa chás seo ” books/book_list.html “ toisc gur liosta leabhair é; :class: ListView níl aon rud aige fao:class: ~django.views.generic.detail.singleObjectMixin, mar sin níl aon leid aige Is é an dearcadh a bhaineann le ``Foilsitheoir ``.
Tá an paginate_by beag d'aon ghnó sa sampla mar sin ní gá duit go leor leabhar a chruthú chun an leathanaigh a fheiceáil ag obair! Seo an teimpléad ba mhaith leat a úsáid:
{% extends "base.html" %}
{% block content %}
<h2>Publisher {{ publisher.name }}</h2>
<ol>
{% for book in page_obj %}
<li>{{ book.title }}</li>
{% endfor %}
</ol>
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
{% endblock %}
Seachain aon rud níos castaLink to this heading
Go ginearálta is féidir leat: class: ~Django.Views.Generic.Base.TemplateResponseMixin agus:class: ~Django.Views.Generic.Detail.SingleObjectMixin nuair a theastaíonn a bhfeidhmiúlacht uait. Mar a thaispeántar thuas, le beagán cúraim is féidir leat fiú SingleObjectMixin a chomhcheangal la:class: ~django.views.Generic.List.ListView. Mar sin féin éiríonn rudaí níos casta de réir mar a dhéanann tú iarracht é sin a dhéanamh, agus is é riail mhaith ordóige:
Chun a thaispeáint cad a tharlaíonn nuair a dhéanann tú iarracht a bheith níos sofaisticiúla, taispeánann muid sampla a íobraíonn inléiteacht agus inchothabháil nuair a bhíonn réiteach níos simplí ann. Ar dtús, féachaimis ar iarracht naif chun: class: ~django.views.generic.detailView a chomhcheangal le: :class: ~django.views.generic.edit.formMixin chun a chumas dúinn ``POST ``django:Class: ~django.forms.forms.form ar an URL céanna agus muid ag taispeáint réad ag baint úsáide:class: Detail:`Amharc.
Ag baint úsáide as FormMixin le ``DetailView ``Link to this heading
Smaoinigh ar ais ar ár sampla níos luaithe maidir le húsáid: class: View agus:class: ~django.views.generic.detail.singleObjectMixin le chéile. Bhíomar ag taifeadadh spéis úsáideora in údar áirithe; abair anois gur mhaith linn ligean dóibh teachtaireacht a fhágáil ag rá cén fáth gur maith leo iad. Arís, glacaimis leis nach bhfuilimid chun é seo a stóráil i mbunachar sonraí coibhneasta ach ina ionad sin i rud éigin níos esoteric nach mbeidh imní orainn faoi anseo.
Ag an bpointe seo tá sé nádúrtha teacht ar a:class: ~django.forms.form chun an fhaisnéis a sheoltar ó bhrabhsálaí an úsáideora chuig Django a chumhdú. Abair freisin go bhfuil infheistíocht mhór againn i REST, mar sin ba mhaith linn an URL céanna a úsáid chun an t-údar a thaispeáint agus chun an teachtaireacht a ghabháil ón úsáideoir. Déanaimis ár “AuthorDetailView” a athscríobh chun é sin a dhéanamh.
Coinneoimid an láimhseáil GET ó:class: detailView, cé go mbeidh orainn a:class: ~django.forms.form a chur isteach sna sonraí comhthéacs ionas gur féidir linn é a rinneadh sa teimpléad. Beidh muid ag iarraidh próiseáil foirme a tharraingt isteach ó:class: ~django.views.generic.edit.formMixin, agus beagán cód a scríobh ionas go gcuirfear an fhoirm ar POST` glaoch go cuí ar an bhfoirm.
Breathnaíonn ár “AuthorDetailView” nua mar seo:
# CAUTION: you almost certainly do not want to do this.
# It is provided as part of a discussion of problems you can
# run into when combining different generic class-based view
# functionality that is not designed to be used together.
from django import forms
from django.http import HttpResponseForbidden
from django.urls import reverse
from django.views.generic import DetailView
from django.views.generic.edit import FormMixin
from books.models import Author
class AuthorInterestForm(forms.Form):
message = forms.CharField()
class AuthorDetailView(FormMixin, DetailView):
model = Author
form_class = AuthorInterestForm
def get_success_url(self):
return reverse("author-detail", kwargs={"pk": self.object.pk})
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
# Here, we would record the user's interest using the message
# passed in form.cleaned_data['message']
return super().form_valid(form)
Soláthraíonn get_success_url () ``áit éigin le atreorú chuig, a úsáidtear i bhfeidhm réamhshocraithe ``form_valid (). Caithfimid ár “post ()” féin a sholáthar mar a luadh níos luaithe.
Réiteach níos fearrLink to this heading
Tá líon na n-idirghníomhaíochtaí caolchúiseach idir:class: ~django.views.generic.edit.formMixin agus:class: detailView ag tástáil ár gcumas rudaí a bhainistiú cheana féin. Ní dócha go mbeadh tú ag iarraidh an cineál seo ranga a scríobh tú féin.
Sa chás seo, d'fhéadfá an modh ``post () a scríobh tú féin, ag coinneáil: class: `DetailView mar an t-aon fheidhmiúlacht chineálach, cé go bhfuil go leor dúbailte i gceist le cód láimhseála ag scríbhneo:class: ~django.forms.form.
De rogha air sin, bheadh sé níos lú oibre fós ná an cur chuige thuas dearcadh ar leithligh a bheith agat chun an fhoirm a phróiseáil, a d'fhéadfaí úsáid: class: ~django.views.generic.edit.formView ar leithligh ó:class: detailView gan imní.
Réiteach malartach níos fearrLink to this heading
Is é an rud atá againn i ndáiríre ag iarraidh a dhéanamh anseo ná dhá dhearcadh éagsúla bunaithe ar rang a úsáid ón URL céanna. Mar sin, cén fáth nach ndéanfaidh sé sin díreach? Tá rannán an-shoiléir againn anseo: ba chóir go bhfaighidh iarratais GET an:class: detailView (leis na:class: ~django.forms.form curtha leis na sonraí comhthéacs), agus ba chóir go bhfaighidh iarratais ``POST ``an:class: FormView. Déanaimis na tuairimí sin a bhunú ar dtús.
Tá an dearcadh AuthorDetailView beagnach mar an gcéanna len:ref: nuair a thugamar AuthorDetailView isteach ar dtús `<generic-views-extra-work>; caithfimid ár ``get_context_data () ``féin a scríobh chun an `AuthorInterestForm` a chur ar fáil don teimpléad. Sceapfaimid an “get_object ()” a shárú ó roimhe seo le haghaidh soiléireachta:
from django import forms
from django.views.generic import DetailView
from books.models import Author
class AuthorInterestForm(forms.Form):
message = forms.CharField()
class AuthorDetailView(DetailView):
model = Author
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = AuthorInterestForm()
return context
Ansin is é an AuthorInterestFormView` a:class: FormView, ach caithfimid a thabhairt isteach: class: ~django.views.generic.detail.singleObjectMixin ionas gur féidir linn an t-údar atá á caint air a fháil, agus caithfimid cuimhneamh ar template_name a shocrú chun a chinntiú go ndéanfaidh earráidí foirme an teimpléad céanna le AuthorDetailView` ag baint úsáide as GET:
from django.http import HttpResponseForbidden
from django.urls import reverse
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
class AuthorInterestFormView(SingleObjectMixin, FormView):
template_name = "books/author_detail.html"
form_class = AuthorInterestForm
model = Author
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_success_url(self):
return reverse("author-detail", kwargs={"pk": self.object.pk})
Finally we bring this together in a new AuthorView view. We
already know that calling as_view() on
a class-based view gives us something that behaves exactly like a function
based view, so we can do that at the point we choose between the two subviews.
You can pass through keyword arguments to
as_view() in the same way you
would in your URLconf, such as if you wanted the AuthorInterestFormView
behavior to also appear at another URL but using a different template:
from django.views import View
class AuthorView(View):
def get(self, request, *args, **kwargs):
view = AuthorDetailView.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = AuthorInterestFormView.as_view()
return view(request, *args, **kwargs)
Is féidir an cur chuige seo a úsáid freisin le haon tuairimí cineálacha eile bunaithe ar aicme nó le do thuairimí rang-bhunaithe féin a thagann oidhreacht go díreach ó:class: View nó:class: TemplateView, toisc go gcoinníonn sé na tuairimí éagsúla chomh scartha agus is féidir.
Níos mó ná HTML amháinLink to this heading
Is é an áit a bhfuil tuairimí bunaithe ar rang-bhunaithe nuair is mian leat an rud céanna a dhéanamh arís agus arís eile. Cuir i gcás go bhfuil API á scríobh agat, agus ba cheart do gach radharc JSON a thabhairt ar ais in ionad HTML rindreáilte
Is féidir linn rang mixin a chruthú le húsáid inár dtuairimí go léir, ag láimhseáil an tiontú go JSON uair amháin.
Mar shampla, d'fhéadfadh go mbeadh cuma mar seo ar mheascán JSON:
from django.http import JsonResponse
class JSONResponseMixin:
"""
A mixin that can be used to render a JSON response.
"""
def render_to_json_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
return JsonResponse(self.get_data(context), **response_kwargs)
def get_data(self, context):
"""
Returns an object that will be serialized as JSON by json.dumps().
"""
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return context
This mixin provides a render_to_json_response() method with the same
signature as
render_to_response().
To use it, we need to mix it into a TemplateView for example, and override
render_to_response() to call render_to_json_response() instead:
from django.views.generic import TemplateView
class JSONView(JSONResponseMixin, TemplateView):
def render_to_response(self, context, **response_kwargs):
return self.render_to_json_response(context, **response_kwargs)
Mar an gcéanna d'fhéadfaimis ár meascán a úsáid le ceann de na tuairimí cineálacha. Is féidir linn ár leagan féin de:class: ~django.views.generic.detail.detailView a dhéanamh trí JSONResponseMixin a mheascadh leis na:class: ~django.views.generic.detail.detail.baseDetailView -- (an: class: ~Django.Views.Generic.DetailView sula ndéantar iompar rindreála teimpléad measctha):
from django.views.generic.detail import BaseDetailView
class JSONDetailView(JSONResponseMixin, BaseDetailView):
def render_to_response(self, context, **response_kwargs):
return self.render_to_json_response(context, **response_kwargs)
Is féidir an dearcadh seo a imscaradh ar an mbealach céanna le haon ain:class: ~django.views.generic.detail.detailView, leis an iompar céanna go díreach -- ach amháin i gcás formáid na freagartha.
If you want to be really adventurous, you could even mix a
DetailView subclass that is able
to return both HTML and JSON content, depending on some property of
the HTTP request, such as a query argument or an HTTP header. Mix in both the
JSONResponseMixin and a
SingleObjectTemplateResponseMixin,
and override the implementation of
render_to_response()
to defer to the appropriate rendering method depending on the type of response
that the user requested:
from django.views.generic.detail import SingleObjectTemplateResponseMixin
class HybridDetailView(
JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView
):
def render_to_response(self, context):
# Look for a 'format=json' GET argument
if self.request.GET.get("format") == "json":
return self.render_to_json_response(context)
else:
return super().render_to_response(context)
Because of the way that Python resolves method overloading, the call to
super().render_to_response(context) ends up calling the
render_to_response()
implementation of TemplateResponseMixin.