---
title: "Láimhseáil foirme le tuairimí rangbhunaithe"
version: 6.0
locale: ga
source: https://docs.djangoproject.com/ga/6.0/topics/class-based-views/generic-editing/
canonical: https://djangodocs.dev/ga/6.0/topics/class-based-views/generic-editing/
---
# Láimhseáil foirme le tuairimí rangbhunaithe

De ghnáth bíonn 3 bhealach ag próiseáil foirme

- GET tosaigh (foirm bán nó réamh-phobail)
- POST le sonraí neamhbhailí (de ghnáth foirm athtaispeáint le hearráidí)
- POST le sonraí bailí (próiseáil na sonraí agus athreorú de ghnáth)

\<using-a-form-in-a-view\>Is minic a bhíonn go leor cód boilerplate arís agus arís eile mar thoradh air seo a chur i bhfeidhm tú féin (féach: Foirm a úsáid i radharc ). Chun cabhrú leis seo a sheachaint, soláthraíonn Django bailiúchán de thuairimí cineálacha bunaithe ar rang le haghaidh próiseála foirme.

## Foirmeacha bunús

Mar gheall ar fhoirm teagmhála:

*`foirme.py`*

```python
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

    def send_email(self):
        # send email using the self.cleaned_data dictionary
        pass
```

Is féidir an radharc a thógáil ag baint úsáide as `FormView`:

*`views.py`*

```python
from myapp.forms import ContactForm
from django.views.generic.edit import FormView

class ContactFormView(FormView):
    template_name = "contact.html"
    form_class = ContactForm
    success_url = "/thanks/"

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.send_email()
        return super().form_valid(form)
```

Nótaí:

- FormView oidhreachtaí: class: ~Django.Views.Generic.Base.TemplateResponseMixin mar sin: attr: ~Django.Views.Generic.Base.TemplateResponseMixin.Template\_Name is féidir a úsáid anseo.
- Níl i bhfeidhm réamhshocraithe le haghaidh: meth: ~django.views.generic.edit.formmixin.form\_valid ach a atreorú chuig an:attr: ~django.views.generic.edit.formmixin.success\_URL.

## Foirmeacha múnla

Generic views really shine when working with models. These generic
views will automatically create a [`ModelForm`](/ga/6.0/topics/forms/modelforms/#django.forms.ModelForm), so long as
they can work out which model class to use:

- Má thugtar tréith: attr: ~Django.Views.Generic.Edit.ModelFormMixin.Model, úsáidfear an rang samhail sin.
- If [`get_object()`](/ga/6.0/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object)
  returns an object, the class of that object will be used.
- Má thugtar a:attr: ~django.views.generic.detail.singleObjectMixin.QuerySet, úsáidfear an tsamhail don tacar ceisteanna sin.

Model form views provide a
[`form_valid()`](/ga/6.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.form_valid) implementation
that saves the model automatically. You can override this if you have any
special requirements; see below for examples.

You don't even need to provide a `success_url` for
[`CreateView`](/ga/6.0/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView) or
[`UpdateView`](/ga/6.0/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView) \- they will use
[`get_absolute_url()`](/ga/6.0/ref/models/instances/#django.db.models.Model.get_absolute_url) on the model object if
available.

Más mian leat saincheap:class: ~django.forms.modelForm a úsáid (mar shampla chun bailíochtú breise a chur leis), socraí:attr: ~django.views.generic.edit.formmixin.form\_class ar do radharc.

> **Note**
>
> Agus rang foirme saincheaptha á shonrú agat, ní mór duit an tsamhail a shonrú fós, cé go bhféadfadh an: attr: ~django.views.generic.edit.formmixin.form\_class a bheith a:class: ~django.forms.modelform.

First we need to add [`get_absolute_url()`](/ga/6.0/ref/models/instances/#django.db.models.Model.get_absolute_url) to our
`Author` class:

*`models.py`*

```python
from django.db import models
from django.urls import reverse

class Author(models.Model):
    name = models.CharField(max_length=200)

    def get_absolute_url(self):
        return reverse("author-detail", kwargs={"pk": self.pk})
```

Ansin is féidir linn: class: CreateView agus cairde a úsáid chun an obair iarbhír a dhéanamh. Tabhair faoi deara conas a bhfuilimid díreach ag cumrú na tuairimí cineálacha bunaithe ar rang anseo; ní gá dúinn aon loighic a scríobh muid féin:

*`views.py`*

```python
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from myapp.models import Author

class AuthorCreateView(CreateView):
    model = Author
    fields = ["name"]

class AuthorUpdateView(UpdateView):
    model = Author
    fields = ["name"]

class AuthorDeleteView(DeleteView):
    model = Author
    success_url = reverse_lazy("author-list")
```

> **Note**
>
> Caithfimid úsáid: func: ~django.urls.reverse\_lazy in ionad reverse () , toisc nach luchtaítear na urls nuair a allmhairítear an comhad.

Oibríonn an tréith `fields` ar an mbealach céanna leis an tréith `fields` ar an rang `Meta` istigh ar:class: ~django.forms.ModelForm. Mura sainmhíníonn tú an rang foirme ar bhealach eile, tá an tréith ag teastáil agus ardóidh an dearcadh an:exc: ~Django.Core.Exceptions.ImProperlyConfigured eisceacht mura bhfuil sé.

Má shonraíonn tú na tréithe: attr: ~Django.Views.Generic.Edit.ModelFormMixin.Fields agus:attr: ~Django.Views.Generic.Edit.FormMixin.Form\_Class ardófar eisceacht, agó:exc: ~Django.Core.Exceptions.ImProperlyConfigured eisceacht.

Faoi dheireadh, cuirimid na tuairimí nua seo isteach sa URLConf:

*`urls.py`*

```python
from django.urls import path
from myapp.views import AuthorCreateView, AuthorDeleteView, AuthorUpdateView

urlpatterns = [
    # ...
    path("author/add/", AuthorCreateView.as_view(), name="author-add"),
    path("author/<int:pk>/", AuthorUpdateView.as_view(), name="author-update"),
    path("author/<int:pk>/delete/", AuthorDeleteView.as_view(), name="author-delete"),
]
```

> **Note**
>
> Na tuairimí seo oidhre:class: ~django.views.generic.detail.singleObjectTemplateResponseMixin a úsáideas:attr: ~django.views.generic.detail.singleObjectTemplateResponseMixin.Template\_Name\_Suffix chun an: attr: ~django.views.generic.base.templateResponseMixin.Template\_Name\_Suffix a thógáil ixin.template\_name\` bunaithe ar an tsamhail.
>
> Sa sampla seo:
>
> - [`CreateView`](/ga/6.0/ref/class-based-views/flattened-index/#CreateView) and [`UpdateView`](/ga/6.0/ref/class-based-views/flattened-index/#UpdateView) use `myapp/author_form.html`
> - [`DeleteView`](/ga/6.0/ref/class-based-views/flattened-index/#DeleteView) uses `myapp/author_confirm_delete.html`
>
> Más mian leat teimpléid ar leithligh a bheith agat dó:class: CreateView agus:class: UpdateView, is féidir leat a shocrú fiú:attr: ~django.views.generic.base.templateResponseMixin.Template\_Name nó:attr: ~django.views.generic.detail.singleObjectTemplateResponsemixin.Template\_Name\_Name\_Suaireacht “ar do rang amharc.

## Múnlaí agus `request.user`

Chun an t-úsáideoir a chruthaigh réad a rianú ag baint úsáide as a:class: CreateView, is féidir leat saincheap:class: ~django.forms.ModelForm a úsáid chun é seo a dhéanamh. Ar dtús, cuir an eochair eachtrach leis an tsamhail leis an tsamhail:

*`models.py`*

```python
from django.contrib.auth.models import User
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)

    # ...
```

In the view, ensure that you don't include `created_by` in the list of fields
to edit, and override
[`form_valid()`](/ga/6.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.form_valid) to add the user:

*`views.py`*

```python
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreateView(LoginRequiredMixin, CreateView):
    model = Author
    fields = ["name"]

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)
```

[`LoginRequiredMixin`](/ga/6.0/topics/auth/default/#django.contrib.auth.mixins.LoginRequiredMixin) prevents users who
aren't logged in from accessing the form. If you omit that, you'll need to
handle unauthorized users in [`form_valid()`](/ga/6.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.form_valid).

## Sampla idirbheartaíochta ábhair

Seo sampla a thaispeánann conas a d'fhéadfá dul i bhfeidhm foirm a oibríonn le sreabhadh oibre atá bunaithe ar API chomh maith le foirm 'gnáth' POSTs:

```
from django.http import JsonResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class JsonableResponseMixin:
    """
    Mixin to add JSON support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """

    def form_invalid(self, form):
        response = super().form_invalid(form)
        if self.request.accepts("text/html"):
            return response
        else:
            return JsonResponse(form.errors, status=400)

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super().form_valid(form)
        if self.request.accepts("text/html"):
            return response
        else:
            data = {
                "pk": self.object.pk,
            }
            return JsonResponse(data)

class AuthorCreateView(JsonableResponseMixin, CreateView):
    model = Author
    fields = ["name"]
```

The above example assumes that if the client supports `text/html`, that they
would prefer it. However, this may not always be true. When requesting a
`.css` file, many browsers will send the header
`Accept: text/css,*/*;q=0.1`, indicating that they would prefer CSS, but
anything else is fine. This means `request.accepts("text/html")` will be
`True`.

To determine the correct format, taking into consideration the client's
preference, use [`django.http.HttpRequest.get_preferred_type()`](/ga/6.0/ref/request-response/#django.http.HttpRequest.get_preferred_type):

```
class JsonableResponseMixin:
    """
    Mixin to add JSON support to a form.
    Must be used with an object-based FormView (e.g. CreateView).
    """

    accepted_media_types = ["text/html", "application/json"]

    def dispatch(self, request, *args, **kwargs):
        if request.get_preferred_type(self.accepted_media_types) is None:
            # No format in common.
            return HttpResponse(
                status_code=406, headers={"Accept": ",".join(self.accepted_media_types)}
            )

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

    def form_invalid(self, form):
        response = super().form_invalid(form)
        accepted_type = self.request.get_preferred_type(self.accepted_media_types)
        if accepted_type == "text/html":
            return response
        elif accepted_type == "application/json":
            return JsonResponse(form.errors, status=400)

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super().form_valid(form)
        accepted_type = self.request.get_preferred_type(self.accepted_media_types)
        if accepted_type == "text/html":
            return response
        elif accepted_type == "application/json":
            data = {
                "pk": self.object.pk,
            }
            return JsonResponse(data)
```

> **Changed in Django 5.2**
>
> The [`HttpRequest.get_preferred_type()`](/ga/6.0/ref/request-response/#django.http.HttpRequest.get_preferred_type) method was added.
