Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB
Jan. 6, 2019, 12:48 p.m.

Django

Django, templatetags, python

I share my implementation of built-in tags to form breadcrumbs with support for schema.org markup, as well as support for bootstrap css.

Wrote these tags to speed up site development speed. Now the work moves much faster, because the code has become more compact, and correcting errors in the breadcrumbs markup has become much easier, since now you only need to correct the code in one place.

Jan. 5, 2019, 2:49 p.m.

Django

templatetags, template, Django

In Django - Lesson 035. Different templates for rendering different types of content in search results it was shown how to render different templates depending on what type of content drawn in the search results on the site. In this case, the key point was that it was not necessary to make the verification conditions for the selection of the template. The information about the balbalon was stored in the variable TEMPLATE_PREVIEW, through which the template was inserted into the include tag in the Django template.

{% include object.TEMPLATE_PREVIEW %}

In this method there is one big drawback. The fact is that the include tag with each of its calls is looking for a template. With a large load on the site - this can significantly increase the duration of the response from the server. To solve this problem, you need to somehow cache the pattern. Since different types of content use different templates, to do this using inclusion_tag is quite problematic.

This problem was solved by caching the template at the class level as a class variable.

Dec. 17, 2018, 5:51 p.m.

Django

Image, Django, avatar

To improve the ability to display information about users in the administrative panel of the site, implemented the ability to display user avatars, both in the special UserProfile model that has One-To-One relationship to the User model, and in the User model itself, it added an avatar display via inline form.

It looks like this:

List of user profiles

Oct. 27, 2018, 11:36 p.m.

Django

Django, Facebook, Social

I added authorization on the site through Facebook.

At the same time collected a couple of pitfalls.

Before Facebook , I already added in authorization through the social network VKontakte and Google . And here I needed to create a privacy policy page, since Facebook requires this page and also requires a user agreement, but I provided a privacy policy page. I think that with the growth of the site I will add a full-fledged page of the user agreement, although it is unknown when it will be. However, the site rules are described in sufficient detail.

Also came across a strict need for https from the site. Generally, if you consider that I have https from Let`s Encrypt , I didn’t think that there would be any problem, but as it turned out, by default django-social-auth forms the return address with HTTP protocol, and for using HTTPS You need to specify this in the settings.

And now let's see how this is done.

Oct. 24, 2018, 6:38 a.m.

Django

BeaftifulSoup4, Django, Python, HTML, Python 3

When developing a web site that adds the ability to write comments or publish articles that allow html layout, the mechanism for clearing unwanted html tags, in particular script and style tags, is important, since malicious scripts on a quality resource definitely should not be present. It will also be good to be able to clean up the style of the text, especially if the resource implies a uniform style. The discordance of screaming fonts is not needed by anyone, and adds problems with the layout.

To implement this mechanism, I use the Python package Beautiful Soup 4 and finally wrote one class, which essentially does everything I need. Removes unnecessary tags, adds necessary classes to tags, saves classes in tags, if you need to leave them during stripping, this is important for classes that are added at the stage of writing a comment, for example, when inserting a YouTube video or adding program code when the user selects which programming language should be represented in the program code block.

Oct. 8, 2018, 9:57 a.m.
Евгений Легоцкой

Добрый день, Дорогие пользователи EVILEG!

Большое количество функционала по формированию шаблонов перевожу на использование inclusion_tag и т.д.

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

{% load my_template_tags %}
{% my_tag %}

чем вручную писать все html теги

Но посетила мысль, а как запихать модуль тегов внутрь middleware, чтобы каждый раз не писать

{% load my_template_tags %}

а писать только

{% my_tag %}

Реализовывал кто-нибудь такое?


Oct. 8, 2018, 9:16 a.m.
Евгений Легоцкой

Добрый день, дорогие пользователи EVILEG!

Вот и я решил задать вопрос на своём форуме. Надеюсь на отклик. Давайте обсудим один вопрос.

Мне не даёт покоя одна мысль, где лучше прописывать Generic вьюшки в Django.

В документации есть два варианта, как использовать Generic вьюшки.

Первый вариант . Прописать всю информацию в Generic вьюшке прямо в файле urls.py

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('about/', TemplateView.as_view(template_name="about.html")),
]

Второй вариант . Наследоваться от Generic вьюшки, описать параметры во views.py, а потом уже подключить эту вьюшку в файле urls.py

views.py


from django.views.generic import TemplateView

class MyView(TemplateView):
    template_name = "about.html"

urls.py


from django.urls import path

from myapp.views import MyView

urlpatterns = [
    path('about/', MyView.as_view()),
]

Мне не даёт покоя одна мысль, даёт ли какой-то бонус в производительности или потреблении памяти, если наследоваться от Generic вьюшки, когда нужно переопределить 5-6 атрибутов, да или даже всего 1 атрибут. Или лучше сразу прописывать всё как в первом варианте прямо в urls.py. Или это скорее уже вопрос код стайла, который имеется внутри команды разработчиков?

Кто-нибудь задавлся подобным вопросом или проводил тесты подобного вопроса?




July 31, 2018, 6:56 a.m.

Django

ESNF-ICO, ESNF-DOC, ESNF-C, ESNF, ESNF-LD, Django, EVILEG

There was probably something that many users of the resource EVILEG would like to see among Web developers.

It was decided to open the sources of EVILEG, especially since I repeatedly received requests to show the source of the resource and even suggestions for the feasible improvement of the site code.

Thus, weighed all the pros and cons, I decided that sending the source code to EVILEG in Open Source is not such a bad idea.

July 16, 2018, 7:15 a.m.

Django

Social, Google, Django, Google API

The second social network through which you can authenticate on the site will be Google+.

I will not go into all the details of setting up and installing the Python Social Auth Django battery, as it was discussed in the previous article . But I note that this time the connection took only half an hour.

However, setting up access through the Google API was more complex than for VKontakte.

July 5, 2018, 7:05 a.m.

Django

Django, template, content, Search

Constant visitors of the site who use the search on the site, probably noticed that the display of articles differs from displaying comments in the search engine issue of the site. This was achieved by the fact that each content type has its own template for rendering, which is substituted for the rendering of the page, depending on what content was found in the search.

Let's look at the example of issuance.

You see, here the presentation of the comment differs from the article, but they are output in the framework of one search issue, as was done in the previous article.

But this is done much more elegantly than selecting via if else . Honestly, I myself really like this decision.

A
Jan. 22, 2019, 9:22 p.m.
Allyonz

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

  • Result:40points,
  • Rating points-8
A
Jan. 22, 2019, 2:15 p.m.
Alex

Qt - Test 001. Signals and slots

  • Result:89points,
  • Rating points6
IO
Jan. 20, 2019, 6:39 p.m.
Ivan Otreshko

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

  • Result:0points,
  • Rating points-10
Last comments
Jan. 22, 2019, 1:17 p.m.
Евгений Легоцкой

Создайте тогда тему здесь на форуме в разделе Qt с выкладками кода и вашими попытками внедрения делегата, позже гляну или может кто-то ещё глянет из опытных пользователей.
I
Jan. 22, 2019, 1:13 p.m.
IscanderChe

Не проще тогда использовать сразу кастомный делегат с чекбоксом? Я попробовал, но там засада в том, что чекбокс показывается только при щелчке на ячейку, а дефолтно показывается значение. Как ...
Jan. 22, 2019, 12:15 p.m.
Евгений Легоцкой

Если будет не приемлемо потом, то тогда через кастомный Item Delegate нужно будет перерисовать ячейки в той колонке.
I
Jan. 22, 2019, 12:09 p.m.
IscanderChe

Получилось приемлемо. Спасибо!Нюанс только в том, что поле рядом с чекбоксом не пропадает, оно просто пустое, что видно при выделении ячейки. Но этого достаточно.
Jan. 22, 2019, 11:50 a.m.
Евгений Легоцкой

Переопределить метод data для той колонки и роли Qt::DisplayRole, чтобы в том случае возвращался QVariant() я так думаю... Но возможно, что у вас там будут нюансы, если вы туда чекбокс за...
Now discuss on the forum
Jan. 23, 2019, 7:54 a.m.
Михаиллл

Зарание спасибо.А еще на эту тему можно будет сделать статью. Это контент будет уникальным.
Jan. 23, 2019, 7:37 a.m.
Евгений Легоцкой

Hello. Maybe the English will be better for you? I think russian is not native language for you, or did I mistake? Did I undesrtood rightly, that you mean this documentation ( ...
I
Jan. 22, 2019, 1:45 p.m.
IscanderChe

Всем добрый день. Суть задачи: надо, чтобы в одной из колонок QTableView вместо хранимого в QSqlTableModel значения выводился чекбокс и при смене состояния чекбокса значения в базе тоже ...
M
Jan. 22, 2019, 1:15 p.m.
Max-P85

Евгений, огромное спасибо, все работает!
Join us in social networks

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