что такое миксины django

Documentation

Using mixins with class-based views¶

This is an advanced topic. A working knowledge of Django’s class-based views is advised before exploring these techniques.

Context and template responses¶

Two central mixins are provided that help in providing a consistent interface to working with templates in class-based views.

ContextMixin Every built in view which needs context data, such as for rendering a template (including TemplateResponseMixin above), should call 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 attribute.

Building up Django’s generic class-based views¶

DetailView : working with a single Django object¶

To show the detail of an object, we basically need to do two things: we need to look up the object and then we need to make a TemplateResponse with a suitable template, and that object as context.

ListView : working with many Django objects¶

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.

Using Django’s class-based view mixins¶

Now we’ve seen how Django’s generic class-based views use the provided mixins, let’s look at other ways we can combine them. We’re still going to be combining them with either built-in class-based views, or other generic class-based views, but there are a range of rarer problems you can solve than are provided for by Django out of the box.

Not all mixins can be used together, and not all generic class based views can be used with all other mixins. Here we present a few examples that do work; if you want to bring together other functionality then you’ll have to consider interactions between attributes and methods that overlap between the different classes you’re using, and how method resolution order will affect which versions of the methods will be called in what order.

The reference documentation for Django’s class-based views and class-based view mixins will help you in understanding which attributes and methods are likely to cause conflict between different classes and mixins.

Using SingleObjectMixin with View¶

We can hook this into our URLs easily enough:

Using SingleObjectMixin with ListView ¶

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.

Now we can write a new PublisherDetailView :

The paginate_by is deliberately small in the example so you don’t have to create lots of books to see the pagination working! Here’s the template you’d want to use:

Avoid anything more complex¶

Using FormMixin with DetailView ¶

Think back to our earlier example of using View and SingleObjectMixin together. We were recording a user’s interest in a particular author; say now that we want to let them leave a message saying why they like them. Again, let’s assume we’re not going to store this in a relational database but instead in something more esoteric that we won’t worry about here.

At this point it’s natural to reach for a Form to encapsulate the information sent from the user’s browser to Django. Say also that we’re heavily invested in REST, so we want to use the same URL for displaying the author as for capturing the message from the user. Let’s rewrite our AuthorDetailView to do that.

Our new AuthorDetailView looks like this:

A better solution¶

The number of subtle interactions between FormMixin and DetailView is already testing our ability to manage things. It’s unlikely you’d want to write this kind of class yourself.

In this case, you could write the post() method yourself, keeping DetailView as the only generic functionality, although writing Form handling code involves a lot of duplication.

Alternatively, it would still be less work than the above approach to have a separate view for processing the form, which could use FormView distinct from DetailView without concerns.

An alternative better solution¶

The AuthorDetailView view is almost the same as when we first introduced AuthorDetailView ; we have to write our own get_context_data() to make the AuthorInterestForm available to the template. We’ll skip the get_object() override from before for clarity:

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:

More than just HTML¶

Where class-based views shine is when you want to do the same thing many times. Suppose you’re writing an API, and every view should return JSON instead of rendered HTML.

We can create a mixin class to use in all of our views, handling the conversion to JSON once.

For example, a JSON mixin might look something like this:

Check out the Serializing Django objects documentation for more information on how to correctly transform Django models and querysets into JSON.

Equally we could use our mixin with one of the generic views. We can make our own version of DetailView by mixing JSONResponseMixin with the BaseDetailView – (the DetailView before template rendering behavior has been mixed in):

Источник

Использование миксинов с представлениями на основе классов ¶

Это сложный предмет. Мы рекомендуем, чтобы у вас были хорошие предварительные знания о представлениях на основе классов Django, прежде чем изучать эти методы.

Контекст и шаблонные ответы ¶

Доступны два центральных класса миксинов, которые помогают представить согласованный интерфейс для работы с шаблонами в представлениях на основе классов.

render_to_response() вызывает сам себя, get_template_names() который template_name по умолчанию обращается к атрибуту представления. Два других миксина ( SingleObjectTemplateResponseMixin и MultipleObjectTemplateResponseMixin ) переопределяют этот метод, чтобы обеспечить более гибкие настройки по умолчанию, когда дело доходит до управления реальными объектами.

Создание представлений на основе классов Django ¶

Давайте посмотрим, как два представления Django на основе классов построены из миксинов, которые обеспечивают изолированную функциональность. Мы рассмотрим, DetailView кто создает подробное представление объекта и ListView кто создает список объектов, обычно из набора запросов, с необязательной разбивкой на страницы. Это приведет нас к рассмотрению четырех миксинов, которые в сочетании обеспечивают полезную функциональность при обработке одного объекта Django или набора объектов.

DetailView : обработка одного объекта Django ¶

Чтобы отобразить детали объекта, в основном нужно сделать две вещи: получить объект, затем создать ответ, TemplateResponse используя соответствующий шаблон, передав объект в контексте.

ListView : обработка нескольких объектов Django ¶

Использование миксинов представлений на основе классов Django ¶

Теперь мы увидели, как общие представления на основе классов Django используют предоставленные миксины, давайте рассмотрим другие способы их комбинирования. Мы по-прежнему собираемся комбинировать их либо со встроенными представлениями на основе классов, либо с другими общими представлениями на основе классов, но существует ряд более редких проблем, которые вы можете решить, чем это предусмотрено Django из коробки.

Вы не можете комбинировать все миксины, а также не можете комбинировать каждый миксин со всеми общими представлениями на основе классов. Здесь мы представляем несколько эффективных примеров; если вы хотите создать другие функции, вам нужно будет изучить взаимодействия между атрибутами и перекрывающимися методами между различными используемыми классами, а также то, как порядок разрешения методов влияет на версию вызываемых методов и порядок этих звонков.

Справочная документация представлений на основе классов и представлений на основе миксинов классов Django поможет вам понять, какие атрибуты и методы могут быть источником конфликта между различными классами и миксинами.

Использование SingleObjectMixin с View ¶

Мы можем довольно легко подключить это представление к нашим URL-адресам:

Использование SingleObjectMixin с ListView ¶

ListView включает разбиение на страницы, но, например, может быть желательно разбить на страницы список объектов, которые все связаны (внешним ключом) с другим объектом. В нашем примере публикации вы можете захотеть разбить на страницы все книги от определенного издателя.

Теперь мы можем написать новое представление PublisherDetail :

В этом paginate_by примере мы намеренно установили небольшое число, чтобы вам не пришлось создавать много книг, чтобы увидеть, как работает нумерация страниц! Вот шаблон, который вы можете использовать:

Риск слишком большой сложности ¶

Использование FormMixin с DetailView ¶

Вот как выглядит наше новое представление AuthorDetail :

Лучшее решение ¶

Количество тонких взаимодействий между FormMixin и DetailView уже проверяет наши концептуальные способности. Маловероятно, что вы сами захотите написать такой класс.

Лучшее альтернативное решение ¶

Вы можете передать аргументы ключевого слова так as_view() же, как и в вашем URLconf, например, если вы хотите, чтобы AuthorInterest поведение также отображалось на другом URL, но с использованием другого шаблона:

Больше, чем просто HTML-код ¶

Представления на основе классов особенно полезны, когда вам нужно повторить аналогичный процесс несколько раз. Представьте, что вам нужно написать API, и каждое представление должно возвращать JSON вместо создания HTML-страницы.

Затем можно создать класс миксина, чтобы использовать его в каждом представлении, тем самым управляя преобразованием в формат JSON в одном месте.

Например, класс миксина для JSON может выглядеть так:

См. Документацию по сериализации объектов Django для получения дополнительной информации о том, как правильно преобразовать модели Django и наборы запросов в формат JSON.

Источник

Documentation

Single object mixins¶

SingleObjectMixin ¶

Provides a mechanism for looking up an object associated with the current HTTP request.

Methods and Attributes

queryset is a class attribute with a mutable value so care must be taken when using it directly. Before using it, either call its all() method or retrieve it with get_queryset() which takes care of the cloning behind the scenes.

Designates the name of the variable to use in the context.

This attribute can help mitigate insecure direct object reference attacks. When applications allow access to individual objects by a sequential primary key, an attacker could brute-force guess all URLs; thereby obtaining a list of all objects in the application. If users with access to individual objects should be prevented from obtaining this list, setting query_pk_and_slug to True will help prevent the guessing of URLs as each URL will require two correct, non-sequential arguments. Using a unique slug may serve the same purpose, but this scheme allows you to have non-unique slugs.

Returns the queryset that will be used to retrieve the object that this view will display. By default, get_queryset() returns the value of the queryset attribute if it is set, otherwise it constructs a QuerySet by calling the all() method on the model attribute’s default manager.

Returns context data for displaying the object.

The base implementation of this method requires that the self.object attribute be set by the view (even if None ). Be sure to do this if you are using this mixin without one of the built-in views that does so.

It returns a dictionary with these contents:

Context variables override values from template context processors

SingleObjectTemplateResponseMixin ¶

Extends

Methods and Attributes

Returns a list of candidate template names. Returns the following list:

Источник

Миксины для нескольких объектов ¶

MultipleObjectMixin ¶

Примесь, которую можно использовать для отображения списка объектов.

Если paginate_by указано, Django разбивает на страницы результаты, возвращаемые this. Вы можете указать номер страницы в URL-адресе одним из двух способов:

Используйте page параметр в URLconf. Например, вот как может выглядеть ваш URLconf:

Передайте номер страницы через page параметр строки запроса. Например, URL-адрес будет выглядеть так:

В качестве особого случая вам также разрешено использовать last в качестве значения для page :

Это позволяет получить доступ к последней странице результатов без предварительного определения количества страниц.

Обратите внимание, что это page должен быть действительный номер страницы или значение last ; любое другое значение page приведет к ошибке 404.

Расширяется

Методы и атрибуты

Целое число, указывающее, сколько объектов должно отображаться на странице. Если это задано, представление будет разбивать paginate_by объекты на страницы с объектами на странице. Представление будет ожидать либо page параметр строки запроса (через request.GET ), либо page переменную, указанную в URLconf.

Обозначает имя переменной для использования в контексте.

Получите список элементов для этого представления. Это должно быть итеративным и может быть набором запросов (в котором будет разрешено поведение, зависящее от набора запросов).

Возврат ordering по умолчанию.

get_paginate_by ( набор запросов ) ¶

Возвращает контекстные данные для отображения списка объектов.

Контекст

MultipleObjectTemplateResponseMixin ¶

Расширяется

Методы и атрибуты

Возвращает список возможных имен шаблонов. Возвращает следующий список:

Источник

Access Mixins¶

The raise_exception attribute allows for these scenarios, in case a permission is denied:

LoginRequiredMixin¶

This mixin is rather simple and is generally the first inherited class in any view. If you don’t have an authenticated user, there’s no need to go any further. If you’ve used Django before you are probably familiar with the login_required decorator. This mixin replicates the decorator’s functionality.

PermissionRequiredMixin¶

This mixin was originally written by Daniel Sokolowski (code here), but this version eliminates an unneeded render if the permissions check fails.

If you are using Django’s built in auth system, superusers automatically have all permissions in your system.

The PermissionRequiredMixin also offers a check_permissions method that should be overridden if you need custom permissions checking.

MultiplePermissionsRequiredMixin¶

If you are using Django’s built in auth system, superusers automatically have all permissions in your system.

The MultiplePermissionsRequiredMixin also offers a check_permissions method that should be overridden if you need custom permissions checking.

GroupRequiredMixin¶

The GroupRequiredMixin ensures that the requesting user is in the group or groups specified. This view mixin can handle multiple groups by setting the mandatory group_required attribute as a list or tuple.

The mixin assumes you’re using Django’s default Group model and that your user model provides groups as a ManyToMany relationship. If this is not the case, you’ll need to override check_membership in the mixin to handle your custom set up.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *