---
title: "Ag baint úsáide as meascáin le tuairimí rangbhunaithe"
version: 6.1
locale: ga
source: https://docs.djangoproject.com/ga/6.1/topics/class-based-views/mixins/
canonical: https://djangodocs.dev/ga/6.1/topics/class-based-views/mixins/
---
# Ag baint úsáide as meascáin le tuairimí rangbhunaithe

> **Caution**
>
> This is an advanced topic. A working knowledge of [Django's
> class-based views](/ga/6.1/topics/class-based-views/) is advised before
> exploring these techniques.

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é

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.

**[`TemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin)**

  Every built in view which returns a
  [`TemplateResponse`](/ga/6.1/ref/template-response/#django.template.response.TemplateResponse) will call the
  [`render_to_response()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.render_to_response)
  method that `TemplateResponseMixin` provides. Most of the time this
  will be called for you (for instance, it is called by the `get()` method
  implemented by both [`TemplateView`](/ga/6.1/ref/class-based-views/base/#django.views.generic.base.TemplateView) and
  [`DetailView`](/ga/6.1/ref/class-based-views/generic-display/#django.views.generic.detail.DetailView)); 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](#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.

**[`ContextMixin`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin)**

  Every built in view which needs context data, such as for rendering a
  template (including `TemplateResponseMixin` above), should call
  [`get_context_data()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data) passing
  any data they want to ensure is in there as keyword arguments.
  `get_context_data()` returns a dictionary; in `ContextMixin` it
  returns its keyword arguments, but it is common to override this to add
  more members to the dictionary. You can also use the
  [`extra_context`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.extra_context) attribute.

## Tuairimí cineálacha aicmbunaithe Django a thógáil

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 Django

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`](/ga/6.1/ref/class-based-views/generic-display/#django.views.generic.detail.DetailView)
relies on [`SingleObjectMixin`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin),
which provides a
[`get_object()`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.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`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.model) attribute
on the view, or the
[`queryset`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.queryset)
attribute if that's provided). `SingleObjectMixin` also overrides
[`get_context_data()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.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`](/ga/6.1/ref/template-response/#django.template.response.TemplateResponse),
[`DetailView`](/ga/6.1/ref/class-based-views/flattened-index/#DetailView) uses
[`SingleObjectTemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectTemplateResponseMixin), which
extends [`TemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin), overriding
[`get_template_names()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.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`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix)
on a subclass to something else. (For instance, the [generic edit views](/ga/6.1/topics/class-based-views/generic-editing/) use `_form` for create and
update views, and `_confirm_delete` for delete views.)

### `ListView`: ag obair le go leor rudaí Django

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`](/ga/6.1/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin) also overrides
[`get_context_data()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.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`](/ga/6.1/ref/class-based-views/flattened-index/#ListView) arranges for
it.

To make a [`TemplateResponse`](/ga/6.1/ref/template-response/#django.template.response.TemplateResponse),
[`ListView`](/ga/6.1/ref/class-based-views/flattened-index/#ListView) then uses
[`MultipleObjectTemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectTemplateResponseMixin).
As with [`SingleObjectTemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectTemplateResponseMixin)
above, this overrides
[`get_template_names()`](/ga/6.1/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectTemplateResponseMixin.get_template_names)
to provide a range of options, with the most commonly-used being
`<app_label>/<model_name>_list.html`, with the `_list` part again
being taken from the
[`template_name_suffix`](/ga/6.1/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix)
attribute. (The date based generic views use suffixes such as `_archive`,
`_archive_year` and so on to use different templates for the various
specialized date-based list views.)

## Ag baint úsáide as meascáin radharc rang-bhunaithe Django

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.

> **Warning**
>
> Ní féidir gach meascán a úsáid le chéile, agus ní féidir gach tuairim chineálach bunaithe ar rang a úsáid le gach meascán eile. Cuirimid cúpla sampla i láthair anseo a oibríonn; más mian leat feidhmiúlacht eile a thabhairt le chéile ansin beidh ort machnamh a dhéanamh ar idirghníomhaíochtaí idir tréithe agus modhanna a fhorluíonn idir na ranganna éagsúla atá á úsáid agat, agus conas a rachaidh 'ordú réitigh modh' \_ i bhfeidhm ar na leaganacha de na modhanna a ghlaofar san ord.
>
> Cuideoidh an doiciméadú tagartha do Djangos:doc: tuairimí rang-bhunaithe agus:doc: meascáin amhairc range-bhunaithe '\</ref/class-based-views/index\> leat tuiscint a fháil ar na tréithe agus na modhanna is dócha a chruthóidh\</ref/class-based-views/mixins\> coinbhleacht idir ranganna agus meascáin éagsúla.
>
> Má tá amhras ort, is minic gur fearr siúl agus do chuid oibre a bhunú ar:class: View nó:class: TemplateView, b'fhéidir le:class: ~django.views.generic.detail.singleObjectMixin agus:class: ~django.views.generic.list.multipleObjectMixin. Cé gur dócha go scríobhfaidh tú níos mó cód, is dóichí go mbeidh sé intuigthe go soiléir do dhuine eile ag teacht chuige níos déanaí, agus le níos lú idirghníomhaíochtaí a bheith buartha faoi, sábhálfaidh tú roinnt smaointeoireachta duit féin. (Ar ndóigh, is féidir leat tumadh i gcónaí i bhfeidhm Django ar na tuairimí cineálacha aicmbunaithe le haghaidh inspioráide maidir le conas dul i ngleic le fadhbanna.)

### Ag baint úsáide as `SingleObjectMixin` le View

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](/ga/6.1/topics/class-based-views/generic-display/).

*`views.py`*

```python
from 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.py`*

```python
from 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 \`\`

[`ListView`](/ga/6.1/ref/class-based-views/generic-display/#django.views.generic.list.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 `Book` le 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 .

**`Publisher` queryset for use in [`get_object()`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object)**

  Beidh muid ag brath ar chur i bhfeidhm réamhshocraithe ```get_object () ``chun an réad ceart ``Publisher``` a fháil. Mar sin féin, ní mór dúinn argóint `queryset` a rith go sainráite mar ar shlí eile ghlaoigh cur i bhfeidhm réamhshocraithe ````get_object () ```get_queryset ()```` a bhfuil athbhreithnithe againn chun rudaí `Book` a thabhairt ar ais in ionad `Publisher` cinn.

> **Note**
>
> Caithfimid smaoineamh go cúramach ar ```get_context_data () ``. Ós rud é go gcuirfidh an bheath:class: `~django.views.generic.detail.singleObjectMixin` agus:class: `ListView` rudaí sna sonraí comhthéacs faoi luach ``context_object_name``` má tá sé socraithe, cinnteoimid go sainráite go bhfuil an ```Publisher ``sna sonraí comhthéacs. :class: Cuirfidh `ListView` an ``page_obj``` oiriúnach agus `paginator` dúinn ar choinníoll go gcuimhnimid glaoch ar super () .

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:

```html+django
{% 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 casta

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:

> **Hint**
>
> Each of your views should use only mixins or views from one of the groups
> of generic class-based views: [detail, list](/ga/6.1/topics/class-based-views/generic-display/), [editing](/ga/6.1/topics/class-based-views/generic-editing/) and date. For example it's
> fine to combine [`TemplateView`](/ga/6.1/ref/class-based-views/flattened-index/#TemplateView) (built in view) with
> [`MultipleObjectMixin`](/ga/6.1/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin) (generic list), but
> you're likely to have problems combining `SingleObjectMixin` (generic
> detail) with `MultipleObjectMixin` (generic list).

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 \`\`

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](https://en.wikipedia.org/wiki/Representational_state_transfer), 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.

> **Note**
>
> Úsáidimid: class: ~django.views.generic.edit.formMixin agus cuirimid post () \`\`i bhfeidhm féin seachas iarracht a mheascadh le:class: \`FormView (a sholáthraíonn `post ()` oiriúnach cheana féin) toisc go gcuireann an dá thuairim get () i bhfeidhm, agus bheadh rudaí i bhfad níos mearbhall.

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 fearr

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 fearr

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()`](/ga/6.1/ref/class-based-views/base/#django.views.generic.base.View.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()`](/ga/6.1/ref/class-based-views/base/#django.views.generic.base.View.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áin

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
```

> **Note**
>
> Amharc ar an doiciméad:doc: /topics/sraitheoireach le haghaidh tuilleadh faisnéise maidir le conas samhlacha agus ceisteanna ceisteanna Django a athrú i gceart go JSON.

This mixin provides a `render_to_json_response()` method with the same
signature as
[`render_to_response()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.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`](/ga/6.1/ref/class-based-views/generic-display/#django.views.generic.detail.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`](/ga/6.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectTemplateResponseMixin),
and override the implementation of
[`render_to_response()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.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()`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.render_to_response)
implementation of [`TemplateResponseMixin`](/ga/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin).
