[ Pobierz całość w formacie PDF ]
.views import LoginRequiredMixinfrom.models import Flavorclass FlavorDetailView(LoginRequiredMixin, DetailView):model = FlavorTIP: Don't Forget the CBV Mixin Order!Remember that:LoginRequiredMixinmust always go on the far left side.e base view class must always go on the far right side.If you forget and switch the order, you will get broken or unpredictable results.8.3.2 Performing Custom Actions on Views With Valid FormsWhen you need to perform a custom action on a view with a valid form, theformvalid()methodis where the CBV work ow sends the request.E.from django.views.generic import CreateViewfrom braces.views import LoginRequiredMixinfrom.models import Flavor74 8.3: General Tips for Django CBVsclass FlavorCreateView(LoginRequiredMixin, CreateView):model = Flavordef form_valid(self, form):# Do custom logic herereturn super(FlavorCreateView, self).form_valid(form)To perform custom logic on form data that has already been validated, simplyadd the logic to formvalid().e return value of formvalid() should be adjango.http.HttpResponseRedirect.8.3.3 Performing Custom Actions on Views With Invalid FormsWhen you need to perform a custom action on a view with an invalid form, theforminvalid()method is where the Django CBV work ow sends the request.is method should return adjango.http.HttpResponse.E.from django.views.generic import CreateViewfrom braces.views import LoginRequiredMixinfrom.models import Flavorclass FlavorCreateView(LoginRequiredMixin, CreateView):model = Flavordef form_invalid(self, form):# Do custom logic herereturn super(FlavorCreateView, self).form_invalid(form)Just as you can add logic toformvalid(), you can also add logic toforminvalid().75 Chapter 8: Best Practices for Class-Based ViewsYou ll see an example of overriding both of these methods in chapter 10, More ings To Know AboutForms, subsection 10.2.1,  Form Data Is Saved to the Form, en the Model Instance.Additional References:http://pydanny.com/tag/class-based-views.htmlwww.python.org/download/releases/2.3/mro/Figure 8.2: e other CBV: class-based vanilla ice cream.8.4 How CBVs and Forms Fit TogetherA common source of confusion with CBVs is their usage with Django forms.Using our favorite example of the ice cream avor tracking app, let s chart out a couple of examplesof how form-related views might t together.First, let s de ne a avor model to use in this section s view examples:76 8.4: How CBVs and Forms Fit TogetherE.# flavors/models.pyfrom django.core.urlresolvers import reversefrom django.db import modelsclass Flavor(models.Model):title = models.CharField(max_length=255)slug = models.SlugField()scoops_remaining = models.IntegerField(default=0)def get_absolute_url(self):return reverse("flavor_detail", kwargs={"slug": self.slug})Now, let s explore some common Django form scenarios that most Django users run into at onepoint or another.8.4.1 Views + ModelForm Exampleis is the simplest and most common Django form scenario.Typically when you create a model,you want to be able to add new records and update existing records that correspond to the model.In this example, we ll show you how to construct a set of views that will create, update and displayFlavor records.We ll also demonstrate how to provide con rmation of changes.Here we have the following views:1FlavorCreateView corresponds to a form for adding new avors.2FlavorUpdateView corresponds to a form for editing existing avors.3FlavorDetailView corresponds to the con rmation page for both avor creation and avorupdates.To visualize our views:77 Chapter 8: Best Practices for Class-Based ViewsFigure 8.3: Views + ModelForm FlowNote that we stick as closely as possible to Django naming conventions.FlavorCreateViewsub-classes Django sCreateView,FlavorUpdateViewsubclasses Django sUpdateView, andFla-vorDetailViewsubclasses Django sDetailView.Writing these views is easy, since it s mostly a matter of using what Django gives us:E.# flavors/views.pyfrom django.views.generic import CreateView, UpdateView, DetailViewfrom braces.views import LoginRequiredMixinfrom.models import Flavorclass FlavorCreateView(LoginRequiredMixin, CreateView):model = Flavorclass FlavorUpdateView(LoginRequiredMixin, UpdateView):model = Flavorclass FlavorDetailView(DetailView):model = FlavorSimple at rst glance, right? We accomplish so much with just a little bit of code!78 8.4: How CBVs and Forms Fit TogetherBut wait, there s a catch.If we wire these views into a urls.py module and create the necessary tem-plates, we ll uncover a problem:e FlavorDetailView is not a con rmation page.For now, that statement is correct.Fortunately, we can x it quickly with a few modi cations toexisting views and templates.e rst step in the x is to usedjango.contrib.messagesto inform the user visiting theFla-vorDetailViewthat they just added or updated the avor.We ll need to override the FlavorCreateView.formvalid() and FlavorUpdate-View.formvalid() methods.We can do this conveniently for both views with a Flavo-rActionMixin.For the con rmation page x, we change avors/views.py to contain the following:E.# flavors/views.pyfrom django.contrib import messagesfrom django.views.generic import CreateView, UpdateView, DetailViewfrom braces.views import LoginRequiredMixinfrom.models import Flavorclass FlavorActionMixin(object):@propertydef action(self):msg = "{0} is missing action.".format(self.__class__)raise NotImplementedError(msg)def form_valid(self, form):msg = "Flavor {0}!".format(self.action)messages.info(self.request, msg)return super(FlavorActionMixin, self) [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • fisis2.htw.pl
  • Copyright © 2016 (...) chciaÅ‚bym posiadać wszystkie oczy na ziemi, żeby patrzeć na Ciebie.
    Design: Solitaire