March 26, 2017, 5:45 a.m.

Django

model, Django, наследование

After refactoring on the site, four main entities were identified, in which common properties were identified, namely:

  • Article - articles
  • Comment - comments
  • ForumTopic - Forum themes (questions)
  • ForumPost - Answers to forum topics

Of course, and so it was clear that these entities can have the same data fields, the same methods, etc. But when developing this site, I myself simultaneously study Python and Django. Therefore, the project has the character of chaotic introduction of small ToDo with subsequent refactoring in the study of the best approaches. Therefore, after studying the inheritance capabilities of models in Django, one general abstract data model was identified, PostBase , which has four fields that are repeated in all the above modeled models.

There is one important point here: A model that is declared abstract will not create a table in the database.

To create an abstract model, you must set the abstract variable to True for the Meta class.

March 15, 2017, 6:12 p.m.

Django

Pagination, Django, django-bootstrap3, ListView

In one of the previous articles , the option of introducing a page with articles pagination was shown, which can be the main page of the site, for example. In this case, django-bootstrap3 was used.

But if the page does not represent any special functionality, in addition to displaying the list of articles, for example, then you must use the generic classes. One of which is ListView . This will reduce the program code of the project and, accordingly, simplify it.

The ListView class allows you to specify a template that will be rendered to display the table, specify a data model or queryset that will need to be shown, as well as the number of objects per page that will be displayed when paginated.

IndexView

Let's recall how the previous View of the class looked to display the list of pages.

class IndexView(View):
 
    def get(self, request):
        context = {}
        # Taking all of the published article, sorted by date of publication
        all_articles = Article.objects.filter(article_status=True).order_by('-article_date')
        # Create Pagination, in which we send article and show,
        # that there will be 10 pieces on one page
        current_page = Paginator(all_articles, 10)
 
        # Pagination in django_bootstrap3 send response in this view:
        # "GET /?page=2 HTTP/1.0" 200,
        # So you need to pick up the page and try to pass it in Paginator, to find the page
        page = request.GET.get('page')
        try:
            # If there is, then choose this page
            context['article_lists'] = current_page.page(page)  
        except PageNotAnInteger:
            # If None, then select the first page
            context['article_lists'] = current_page.page(1)  
        except EmptyPage:
            # If you have gone beyond the last page, it returns the last
            context['article_lists'] = current_page.page(current_page.num_pages) 
 
        return render_to_response('home/index.html', context)
Jan. 22, 2017, 8:05 a.m.

Django

SSL, Django, HTTPS, letsencrypt, Nginx

Yesterday I received a letter from Google , since I use Google Search Console to monitor the indexing of site in Google search engine. The essence of the letter is that Google Chrome will report unsafe site that uses the http protocol on pages that require a password. And when you consider that on my site authorization form located on every page, it means that a warning will be on all pages of the site. Not the most pleasant situation, so I had to quickly get an SSL certificate and configure https.

At the moment there CA Let`s Encrypt, which gives out free certificates for a period of 90 days. This CA is supported by organizations such as the Electronic Frontier Foundation (EFF), Mozilla Foundation, Akamai, Cisco Systems.

The process of obtaining and installing the certificate is automated, but in the case of a site that is running on Django and Nginx , will need further work on Nginx server settings.

Jan. 9, 2017, 2:45 p.m.

Django

IP, brute force, брутфорс, Django, блокировка, подбор пароля

After we replaced the login page Django on his own customized login page , the time has come to use this substitution for the purpose of improving the security of the site. For example, the introduction of an IP attacker blocking when attempting to password guessing.

I propose such blocking variant: the three failed attempting to enter a password IP blocked for 15 minutes, if such blocking occurs for 15 minutes 3 times, then blocked IP for 24 hours.

To implement the blocking we required model, which will be located 4 fields:

  • IP address;
  • The number of password attempts;
  • Unblock time;
  • Blocking Status - True - if blocked, False - if not blocked.

Just show the result of blockages in the admin site for a couple of months already accumulated a small collection.

Jan. 7, 2017, 1:20 p.m.

Django

авторизация, Django, login

In order to make the registration of the login page in the same style with the design throughout the site, you can prepare a design template and replace the url pattern to give us an view of the desired page with the desired pattern. It may also be useful for the introduction of functional locks from password guessing and more intelligent redirect the user to a page of the site after login, depending on whether the user has a status of staff or not.

To work with the user authorization propose to use a separate application/module that will be called accounts .

Authorization Form is not required to write, because you can use the standard form AuthenticationForm , you will need to use in the login page template.

accounts module structure

accounts/
    templates/
        accounts/
            login.html
            login_widget.html
    __init__.py
    admin.py
    apps.py
    models.py
    special_func.py
    urls.py
    views.py

This module uses two templates:

  • login.html - a template for the login page
  • login_widget.html - a template for login widget that can be placed on any page of the site, the user can log in, not only from the login page, but also from any page with the article, for example.

special_func.py file contains some useful features, such as the receipt of the previous Url from request to redirect the user back to the page where the user is logged in.

Jan. 5, 2017, 12:47 p.m.

Django

Django, templatetags, Python, список популярных статей

The site already had an article about the withdrawal the list of popular articles in the last 7 days . But in the variant that is used in this article shows how to draw a conclusion on the Articles page. But there was a question as to quickly implement a list of popular articles on any page of the site.

I have solved this problem by using its own tag , which can be used in a Django template. That is, instead of each View on the site to register the same code to obtain a list articles or the use of the same function in this View, I just did a single template with a finished layout for a list of popular articles, which uses my custom tag, which I take a list of these articles. Thus, you only need to implement this pattern in the right place in the page template using the include tag.

Dec. 30, 2016, 5:30 a.m.

Django

referer, Django, IP, HTTP

Obtaining the user IP-addresses from the request on the Django can be useful for the organization of a functional site, such as the hosts lock, from which users are trying to make password brute force to the site or if you need to remember user IP, to provide access to the site for a particular user with only certain IP address.

The IP address can be either real or transmitted through a proxy server (in this case will be transferred HTTP_X_FORWARDED_FOR header which you can extract the real IP address).

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip
Nov. 13, 2016, 6:04 a.m.

Django

Django, статистика, популярные статьи

Many blogs and news sites to keep the audience's attention using such methods as ranking popular articles this week, related publications, and some major resources and more advice on user preferences.

First, it was decided to do - it displays a list of popular articles. The first version of the popular articles was based on a general counter views and eventually deduced the article with the most views. This is generally a bad option, since the TOP will result in articles just scored the highest number of views for all time.

Therefore it was necessary to change something. As a result, the output has been introduced popular articles in last 7 days in its simplest form. That is, the table has been added which introduced views of articles by day. Of course, the accuracy of counting under heavy load can vary greatly, but attendance is not reached the 5,000 - 10,000 unique visitors a day - it's not so important.

Now lets proceed with an example of how to make a list of popular articles Django .

Oct. 15, 2016, 1:50 p.m.

Django

контактная форма, Django, контакты

Continuing the development of the site, I would like to share an example of code for adding a contact form on the site to Django. There have already been articles with different shapes, for example, to add comments, but just talking about the entire process as a whole, and we will not get, and this theme party.

Especially that for a site on Wordpress for me it was a pain. Probably, all the fault was laziness, because I did not have any desire to begin to deal with PHP , to sketch out a contact form on their own (as a result of another plugin was used).

And when you consider that the development on the Django , quite often involves working with various forms of data, and thus there is a module for working with e-mail services, and the addition of such a form is not difficult.

Sept. 30, 2016, 4:42 p.m.

Django

Django, MaterializedPath, Python

When I worked with the implementation of comments on the site for Django, I was surprised to find that Django does not provide any modules for implementation comments. Rather it gave him before, it was a unit django.contrib.comments, but in version 1.7 it was announced as deprecated and offered either to cut yourself, or you can use something like Disqus. Well, it sort of code also supports syntax highlighting, but ... in the articles one light, the other in the comments - it will be ugly.

Therefore I decided to write my own comments on the site.

To implement the necessary comments:

  • Add a new model, call it Comment ;
  • Add an idea that will handle the addition of a comment;
  • Add a form to add a comment;
  • Use Materialized Path to organize tree structure;
Last comments
June 24, 2019, 10:23 a.m.
Евгений Легоцкой

Хорошо, ну будут проблемы помимо того, что касается статей, то не стесняйтесь задавать вопросы на форуме.
МБ
June 24, 2019, 10:21 a.m.
Михаил Булатов

Извиняюсь, все работает(из-за невнимательности).
June 24, 2019, 9:52 a.m.
Евгений Легоцкой

Придётся делать ещё сигнал в дочернем qml и пробрасывать через коннекты и обработчики. А вообще нужно смотреть конкретный код и что вы пытаетесь сделать. Так что лучше будет, если вы зад...
June 21, 2019, 8:31 a.m.
Ruslan Polupan

Вот моя строка по которой все отлично сработало %cqtdeployer% -bin c:/CentralMposKeys/CentalMposKeys.exe -qmake c:/Qt/5.12.2/mingw73_64/bin/qmake.exe
June 21, 2019, 8:24 a.m.
Андрей Янкович

Возможно кому то пригодится сqtdeployer для windows работает точно так же как и для Linux разница лишь в команде запуска Linux: cqtdeployer Windows: %cqtdeployer...
Now discuss on the forum
June 24, 2019, 2:36 p.m.
Михаиллл

Нашел проект подключения к вебсокету.Но по моему адресу не могу подключиться.Нужно ли для этого использовать библиотеки?Вы не знаете адрес вебсокета, на котором можно проверить с...
June 24, 2019, 2:07 p.m.
Евгений Легоцкой

Я пока даже не знаю, а какой код самого подключения? использовали ожидание на подключение? Так делали? socket->connectToServer("market");if (socket->waitForConnected(1000)) ...
June 24, 2019, 1:19 p.m.
IscanderChe

// widget.cpp#include "widget.h"#include <QTableView>#include <QVBoxLayout>#include "checkboxdelegate.h"#include "comboboxdelegate.h"#include "mytableview.h"#include <QSqlD...
June 24, 2019, 11:16 a.m.
BlinCT

Хорошо, с этим понятно. Вот есть такой набор каких то кнопок. Цифры отображают в каком порядке должен менятся фокус.1. Как правильнее сделать отображение активного обьекта...
e
June 24, 2019, 10:58 a.m.
evgenm27

Спасибо за ответ, буду пробовать
Looking for a Job?
10,000.00 руб. - 15,000.00 руб.
Нужен помощник для создания API.
Moscow, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

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

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB