[ Pobierz całość w formacie PDF ]
.Here, we reuse a similarformvalid()override method by creating a mixin to inherit fromin multiple views.Now we re using Django s messages framework to display con rmation messages to the user uponevery successful add or edit.We de ne aFlavorActionMixinwhose job is to queue up a con r-mation message corresponding to the action performed in a view.TIP: Mixins Should Inherit From ObjectPlease take notice that theFlavorActionMixininherits from Python s object type ratherthan a pre-existing mixin or view.It s important that mixins have as shallow inheritance chainas possible.Simplicity is a virtue!After a avor is created or updated, a list of messages is passed to the context of theFlavorDe-tailView.We can see these messages if we add the following code to the views template and thencreate or update a avor:E.{# templates/flavors/flavor_detail.html #}{% if messages %}80 8.4: How CBVs and Forms Fit Together{% for message in messages %}{{ message }}{% endfor %}{% endif %}TIP: Reuse the Messages Template Code!It is common practice to put the above code into your project s base HTML template.Doingthis allows message support for templates in your project.To recap, this example demonstrated yet again how to override theformvalid()method, incorpo-rate this into a mixin, how to incorporate multiple mixins into a view, and gave a quick introductionto the very usefuldjango.contrib.messagesframework.8.4.2 Views + Form ExampleSometimes you want to use a DjangoFormrather than aModelForm.Search forms are a particularlygood use case for this, but you ll run into other scenarios where this is true as well.In this example, we ll create a simple avor search form.is involves creating a HTML form thatdoesn t modify any avor data.e form s action will query the ORM, and the records found will belisted on a search results page.Our intention is that when using our avor search page, if users do a avor search for  Dough ,they should be sent to a page listing ice cream avors like  Chocolate Chip Cookie Dough,  FudgeBrownie Dough,  Peanut Butter Cookie Dough, and other avors containing the string  Doughin their title.Mmm, we de nitely want this feature in our web application.81 Chapter 8: Best Practices for Class-Based Viewsere are more complex ways to implement this, but for our simple use case, all we need is a singleview.We ll use aFlavorListViewfor both the search page and the search results page.Here s an overview of our implementation:Figure 8.4: Views + Form FlowIn this scenario, we want to follow the standard internet convention for search pages, where  q isused for the search query parameter.We also want to accept a GET request rather than a POSTrequest, which is unusual for forms but perfectly ne for this use case.Remember, this form doesn tadd, edit, or delete objects, so we don t need a POST request here.To return matching search results based on the search query, we need to modify the standard querysetsupplied by theListView.To do this, we override theListView's getqueryset()method.We add the following code to avors/views.py:E.from django.views.generic import ListViewfrom.models import Flavorclass FlavorListView(ListView):model = Flavordef get_queryset(self):# Fetch the queryset from the parent get_querysetqueryset = super(FlavorListView, self).get_queryset()# Get the q GET parameterq = self.request.GET.get("q")if q:# Return a filtered querysetreturn queryset.filter(title__icontains=q)82 8.5: Summary# Return the base querysetreturn querysetNow, instead of listing all of the avors, we list only the avors whose titles contain the search string.As we mentioned, search forms are unusual in that unlike nearly every other HTML form theyspecify a GET request in the HTML form.is is because search forms are not changing data, butsimply retrieving information from the server.e search form should look something like this:E.{# templates/flavors/_flavor_search.html #}{% comment %}Usage: {% include "flavors/_flavor_search.html" %}{% endcomment %}searchTIP: Specify the Form Target in Search FormsWe also take care to specify the URL in the form action, because we ve found that searchforms are often included in several pages.is is why we pre x them with   and create themin such a way as to be included in other templates.Once we get past overriding theListView's getqueryset()method, the rest of this exampleis just a simple HTML form.We like this kind of simplicity.8.5 Summaryis chapter covered:Using mixins with CBVs83 Chapter 8: Best Practices for Class-Based ViewsWhich Django CBV should be used for which taskGeneral tips for CBV usageConnecting CBVs to formse next chapter explores common CBV/form patterns.Knowledge of these is helpful to have inyour developer toolbox.84 9 | Common Patterns for FormsDjango forms are powerful, exible, extensible, and robust.For this reason, the Django admin andCBVs use them extensively.In fact, all the major Django API frameworks use ModelForms as partof their validation because of their powerful validation features.Combining forms, models, and views allows us to get a lot of work done for little effort.e learningcurve is worth it: once you learn to work uently with these components, you ll nd that Djangoprovides the ability to create an amazing amount of useful, stable functionality at an amazing pace.PACKAGE TIP: Useful Form-Related Packagesdjango- oppyforms for rendering Django inputs in HTML5.django-crispy-forms for advanced form layout controls.By default, forms are renderedwith Twitter Bootstrap form elements and styles.is package plays well with django-oppyforms, so they are often used together [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • igraszki.htw.pl