Evgenii Legotckoi
Evgenii LegotckoiJune 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.

Do you like it? Share on social networks!

ИМ
  • Dec. 28, 2018, 4:29 p.m.
  • (edited)

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

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

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

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

ИМ
  • Dec. 29, 2018, 9:03 a.m.

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

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

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

IscanderChe
  • Jan. 28, 2021, 1:52 a.m.

Добрый день.

А что посоветуете для ведения блога?

Evgenii Legotckoi
  • Jan. 28, 2021, 3:41 a.m.
  • (edited)

Добрый день.

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

  • django-autocomplete-light
  • django-tagging
  • django-bootstrap4
  • django-modeltranslation

От ckeditora я отказался, для чистого кастома он не подходит, тем более, что я использую markdown разметку.

django-daterange-filter и django-phonenumber-field опционально, если потребуется. Впрочем фильтровкой даты часто пользуюсь.

django-rest-framework нужен для API и если что-то через JavaScript забираться будет. Так что для обычного блога на ранней стадии он может быть и не нужен

IscanderChe
  • Jan. 28, 2021, 6:49 a.m.

А какие-то готовые движки под django для блогов есть или надо самому всё с нуля кодить?

Evgenii Legotckoi
  • Jan. 28, 2021, 6:59 a.m.

Вот тут понятия не имею, вроде как есть какие-то, но не интересовался. Также год назад я начал делать платформу блоговую из Evileg, но у меня забуксовало всё. Надо себя брать в руки и наконец делать.

IscanderChe
  • Jan. 28, 2021, 7:38 a.m.

Понятно. Спасибо за рекомендации!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 p.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 9:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 10:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 5:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 5:44 p.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 4, 2024, 5:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 3, 2024, 2:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 4:22 p.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks