Evgenij LegotskojJune 23, 2017, 4:12 a.m.

Django - Tutorial 025. A set of useful batteries Django

The convenience of developing on Django is not only that it is already a developed Framework with rich functionality, but also the availability of a large number of high-quality batteries (packages) that implement the necessary functionality that it would be quite difficult to write independently, especially if you are developing Site alone.

In the process of more than half a year's development of the site on the COM domain, it was just such a package that greatly facilitates life and accelerates the development:

  1. django-ckeditor
  2. django-autocomplete-light
  3. django-tagging
  4. django-bootstrap3
  5. django-modeltranslation
  6. django-daterange-filter
  7. django-phonenumber-field
  8. django-rest-framework

django-ckeditor

CKEditor is a WYSIWYG HTML text editor with a lot of plug-ins. It was the first battery I added to the site. Because articles are more convenient to write with the help of the editor, and not take into account all the necessary layout, prescribing all the tags.

Also, in addition to editing CKEditor provides the ability to upload images.

But in the future I plan to remove the use of CKEditor on the site. This is due to a few points that I do not like in his work:

  1. The CKEditor is rendered after the page is loaded, that is, the user has to wait for the page to load and initialize the editor on the page.
    If the site does not actively use the ability to comment on articles, materials, etc, then this is not critical, but in my case I want to make neatly built-in comments without excessive functionality.
  2. When you move a form with the editor through a page using JavaScript or libraries (for example, jQuery), CKEditor disables the buttons. Most likely, you need to re-initialize the editor, but in my opinion it completely kills its usefulness with such User Case. Similar behavior of the form of answers and comments you can see on the forum site. When the user selects the answer that he wants to comment on, the form of the answer is moved to this answer, which makes using the site a little more convenient, allowing you not to flip the page from form to answer.
  3. Adding videos from YouTube, adding images, etc. Yes - this functionality is available for CKEditor, but its configuration and more complicated use of linking downloaded images to the user who uploaded them will be equivalent to writing new functionality and plug-ins, which can be even more labor-intensive than creating an additional window for uploading images to your own WYSIWIG. This functionality is expected on the site in the future, but I do not see it in a shared use with CKEditor.
  4. Design of CKEditor. To customize the design of this editor, you will have to write a separate style sheet, which is also an additional work that requires separate support. This effort can also be spent writing your own WYSIWIG

Summarize. CKEditor is indispensable for the initial launch of a site where text editing is required, but when developing a resource, especially if there are big plans, it is worthwhile to think about writing your own editor and to abandon CKEditor.

django-autocomplite-light

With the proliferation of content on the site, management and finding the right information becomes difficult. Therefore, auto-completion for fields in forms becomes irreplaceable. The most useful battery for such a functional is django-autocomplite-light .

This battery allows you to use auto-completion for:

  • Common fields of ForeignKey
  • For fields with multiple choice
  • For fields with GenericForeignKey
  • For fields Many to Many
  • Custom autocomplete options
  • etc.

In this case, you can use this autocomplete not only in the Admin panel, but also on the normal pages of the site.

django-tagging

Do you miss the tag system site? Then you need django-tagging. Particularly well, its power is revealed when used with django-autocomplite-light, which supports TagField from django-tagging, allowing you to offer tags when filling out the tag field, and automatically create missing tags.

For a long time, my hands did not reach me to make a complete tag system, and this battery saved the situation literally in one evening.

The site has been added a system of tags for Articles and Questions on the forum, which in forms looks like this:

In this image, you can see the tag field from the django-tagging battery using a field of django-autocomplite-light.

django-bootstrap3

This battery provides a set of template tags for more concise writing of templates using Bootstrap 3. After a six-month use of this battery, I have an opinion that not all functionality makes sense to use. For example, adding icons through this module is just an additional load on the site. It is much better to write a html code with these icons in mind. But at the same time this module is convenient for creating forms and pagination.

The site presents several articles on the use of django-bootstrap3:

django-modeltranslation

To create content in several languages, you can either add columns for each language in the data models yourself, or use a battery that will automatically add all the necessary fields and automatically provide the necessary column depending on the current language that the user has chosen. For this purpose, django-modeltranslation is appropriate.

It creates to the main column an additional column for each language that is used on the site. The templates will automatically select the required language.

django-daterange-filter

This is a very small module, with which you can add filtering by date range to the admin panel of the site. By default, this functionality is not provided in Django, which is very strange.

The filter looks like this:

django-phonenumber-field

An additional field that adds validation to the entered phone number. You can use it in contacts in the user profile, contact form, etc.

django-rest-framework

This is the most interesting battery for Django. In fact, this is an additional Framework for Django, which adds advanced features:

  • On the implementation of data models
  • More convenient work with queries that work with JSON
  • By organizing API for third-party services on the site
  • Additional features for working with OAuth1 and OAuth2 authentication

At the moment, the use of this framework on the site is not great, but with the increase in functionality, working through AJAX will grow.

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate
IM

Доброго времени суток Евгений.
А чем вас не устроила реаизация ManyToManyField + django-autocomplete-light вместо django-tagging. Чем он так хорош?

Добрый день, Игорь.

В первую очередь использовал tagging потому, что это уже готовое решение.

А так, я поизучал данный вопрос. И пришёл к мысли, что лучше использовать GenericForeignKey вместо ManyToManyField. А tagging как раз и использует GenericForeignKey. В данном случае будет одна таблица для всех видов контента, которые присутствуют на сайте. А если ManyToMany, то такие промежуточные таблицы будут множиться как кролики с каждым новым видом контента, а потом её придётся свой ModelManager писать, который будет возвращать QuerySet из всех помеченных объектов. В обще в обоих случаях есть свои плюсы и минусы, но для меня вариант с GenericForeignKey более предпочтительным является. Поскольку таких потенциальных моделей для тегирования на сайте уже несколько десятков набирается.

IM

Кстати да. Таблицы размножились и меня это тоже не устивает так как хочу юзать одну таблицу для всех приложений. Спасибо вам за совет. Буду использовать GenericForeignKey + django-autocomplete-light.

Единственный минус GenericForeignKey в том, что это псевдо связь, которая не является нормальным Foreign Key отношением, а значит при удалении контента могу остаться битые объекты с GenericForeignKey. Но думаю, что это можно легко поправить через обработку сигнала удаления контента, просто удалить все записи c GenericForeignKey на удалённый контент.

И ещё. Tagging также поддерживается в django-autocomplete-light. Поэтому я и не стал изобратать сво велосипед.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
TG

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
TG

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
TN

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
Last comments
r

Поздравляю всё Сообщество EVILEG с Новым Годом!!!

https://nutakugold.club/freenutakugold/ - the best generator woooow :) 2021 updated. hmm i found it. or https://issuu.com/nutakugoldcoins2021 Study reviews of matches prior to …

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Ошибка в конфиге инжинкса про статику в root последний слеш лишний путь в таком виде получается /home/user/myprojectenv/myproject/myproject//static
  • Jurij
  • Jan. 20, 2021, 1:34 p.m.

Qt/C++ - Lesson 061. Adding images to the application using the Drag And Drop method from the file manager

// Вместо отрисовки иконки и текста будем отрисовывать только одно изображение // с небольшими отступами в 5 пикселей QPixmap pix(m_model->data(index).toString()); …
m
  • magrif
  • Jan. 19, 2021, 12:37 p.m.

Qt Сертификация

Здравствуйте. Подскажите, оплачивать ваучер прямо в выбранном тестовом центре? Можно ли загранник предъявить? Или свой паспорт, а заполнить транслитом? А то там пишут: Your name must exactl…
r
  • retmas
  • Jan. 17, 2021, 4:09 a.m.

Qt/C++ - Tutorial 074. Generating pseudo-random numbers, using STD library random

Дмитрий, решает. Просто автор, видимо, не сильно озаботился изучением документации QRandomGenerator. Да и в листинге с использованием qrand вызов функции qsrand на каждой итерации цикла нав…
Now discuss on the forum
DK

QScrollArea dynamically add QCheckBoxes

QWidget *materialContainer = new QWidget(this);QVBoxLayout *materialLay = new QVBoxLayout();materialContainer->setLayout(materialLay);ui->_materialScrollArea->setWidget(materialContaine…

Ошибка при работе утилиты не удалось получить фабрику класса com для компонента с clsid

Всем привет! Мне для тестов нужна одна утилита. Она тестирует определенное оборудование. Поставил ее на новый ноут с Windows 10 Домашняя, 64-бит, версия 10.0.19041. Утилита работает, но спу…

Как в Android открыть свернутое приложение?

Это не вам, тот коммент судя по всему удалили, или я написал не туда

Qt: INTERNAL ERROR: failed to install GetMessage hook: 1158

ESP8266 и вправду не корректно закрывало соединение. Причина оказалась банальной: перед функцией ухода в глубокий сон ESP.deepSleep(60e6) необходимо было поставить небольшую задержку delay(1). В…
  • Nomad
  • Jan. 20, 2021, 8:48 a.m.

Ограничение доступа к ресурсу с по django-cors-headers

всем привет помогите разобраться гуглю и ниче не помогает есть проект с drf установил django-cors-headers добавил в INSTALLED_APPS добавил MIDDLEWARE слой для cor…
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB