Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

Django - Tutorial 025. A set of useful batteries Django

Battery, tagging, Framework, Django, ckeditor, REST, django-bootstrap3

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 .

ИМ

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

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

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

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

ИМ

Кстати да. Таблицы размножились и меня это тоже не устивает так как хочу юзать одну таблицу для всех приложений. Спасибо вам за совет. Буду использовать 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
v
Jan. 17, 2019, 11:51 a.m.
vitalir12

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

  • Result:20points,
  • Rating points-10
v
Jan. 17, 2019, 11:49 a.m.
vitalir12

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
v
Jan. 17, 2019, 11:13 a.m.
vitalir12

C++ - Тест 003. Условия и циклы

  • Result:28points,
  • Rating points-10
Last comments
I
Jan. 16, 2019, 8:06 a.m.
IscanderChe

Заработало. Забыл model->select(); вписать.
I
Jan. 16, 2019, 8:02 a.m.
IscanderChe

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
I
Jan. 16, 2019, 7:43 a.m.
IscanderChe

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.
nayk1982

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.
Михаиллл

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.
BlinCT

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

For registered users on the site there is a minimum amount of advertising