Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB
Nov. 27, 2017, 8:03 p.m.
Ambient

Здравствуйте!

Изучаю, как написать сайт на Django. Пытаюсь настроить CKEditor, чтобы стиль оформления контента редактора был такой же, как и стиль оформления сайта. Заметил, что у вас пользователи могут писать свои статьи и там используется CKEditor.  А в нём такое же оформление контента, как и на сайте.
Можете подсказать, как сделать также?
Nov. 10, 2017, 7:43 a.m.

Django

Django, ckeditor

In most of the site I use a self-written WYSIWYG editor, so it's not as advanced as I'd like. But for writing articles on the site, CKEditor is used, a very powerful and good editor. Nuance is that writing articles is available for all registered users of the site. But by default CKEditor allows you to upload images only to users with the status of staff.

For all other users, either an error page or the main page of the site will open instead of a file manager to search for images or the downloaded image.

A little polished the documentation, I managed to fix this problem. And to be honest, the solution looks rather strange, although it is proposed in the official documentation for the editor.

June 23, 2017, 8:12 a.m.

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
June 4, 2017, 8:52 a.m.

PostgreSQL

PostgreSQL, Django, LATIN1, UTF8

On the site there was one bug that manifested itself when trying to attach to files messages whose names were in Cyrillic. In this case, the site issued error 503. This occurred despite the fact that the database was encoded in UTF8, after correcting the encoding of the database itself in the previous article . While Django issued the following message:

'latin-1' codec can't encode characters in position 55-64: ordinal not in range(256)

The problem was that the server's coding was initially set to LATIN1. That is, the following commands gave the following conclusion:

postgres=# show server_encoding;
 server_encoding 
-----------------
 LATIN1
(1 row)

postgres=# show client_encoding;
 client_encoding 
-----------------
 LATIN1
(1 row)

postgres=# \encoding 
 LATIN1

Executing the command SET CLIENT_ENCODING TO 'utf 8'; did not work, after exiting psql, the encoding was returned to LATIN1 .

May 10, 2017, 4:38 p.m.

Django

AJAX, Django, Polling

Frequent surveys with AJAX allow you to establish a permanent connection between the browser and the server in order to update any data, for example, whether there are new notifications on the site for the user. For example, I organized a small system of notifications for registered users, which allows them to find out at the entrance to the site if there were answers in the articles and forum questions to which they are subscribed, and whether there were new articles and questions on the forum, to sections of which users were also signed.

The notifications are as follows:

April 30, 2017, 4:17 p.m.

Django

Like, Django, GenericRelation, Dislike, GenericForeignKey

In the article on creating a system of bookmarks on Django, an example was considered with the use of an abstract model for several types of bookmarks, namely for articles and comments on articles. Attention was also drawn to the fact that the model fields that had foreign keys to different models should have the same names to support the possibility of creating a single interface for adding bookmarks. This is made possible by the so-called "duck typing", which implies that objects that do not have a single inheritance hierarchy can be used in the same scenario if there are interfaces (methods) that have the same signature.

Literally the principle of duck typing sounds like this:

If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck.

That is, having methods with the same signature, we can use objects that are not associated with an inheritance hierarchy, in the same context.

In the same article, let's consider the variant when using the Like Dislike system, not two different tables for articles and comments are used, and not even one that will contain a foreign key for an article or comment (that is, two columns, One of the columns, depending on what type of content the user activity is related to), and one table that will contain:

  • content_type - The content type to which the record belongs
  • object_id - Record ID
    • content_object - The generated foreign key to write, in fact the content object
  • Other additional fields
April 8, 2017, 11:52 a.m.

Django

bookmark, AJAX, favorite, Django, jQuery

The site has the ability to mark articles, comments, topics and answers on the forum as favorites. However, marking as favorites does not provide a reload of the page, because for these actions the mechanism of AJAX-requests is used.

In order to implement the bookmark system, you need:

  • Add a table that implements the Many-to-Many relationship between the user and the article or comment.
  • Add a view that will handle this request.
  • Add url to handle the request to add or exclude an object from the favorites.
  • Write the html-code, which will be responsible for displaying the counter added to the bookmark.
  • Add a javascript handler that will call the AJAX request.

On this site, the icon of the star from Bootstrap is used as a counter icon.

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.

ГК
March 20, 2019, 9:01 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:0points,
  • Rating points-10
ГК
March 20, 2019, 8:46 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
MU
March 20, 2019, 3:43 p.m.
Maciej Urmański

It's possible to simply add vote option for non logged users?
March 20, 2019, 9:45 a.m.
Евгений Легоцкой

Добрый день. Поппробуйте домен localhost, а url соответственно http://localhost Возможно, потребуется указать порт. Например, так http://localhost:8000
March 19, 2019, 12:57 p.m.
AlexanderBardin

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)
March 16, 2019, 1:55 p.m.
Дмитрий

Спасибо за статью. Давно итересует следующий вопрос: с помощью переменных QMAKE_TARGET_COMPANYQMAKE_TARGET_PRODUCTQMAKE_TARGET_DESCRIPTIONможно задать свойства компилируемой программы, о...
JS
March 12, 2019, 10:19 a.m.
Jean Stefanovich

Большое спасибо за разъяснения!
Now discuss on the forum
March 20, 2019, 12:26 p.m.
Евгений Легоцкой

Лучше стараться избегать этого. Нормального механизма нет. Я просто выдёргиваю из бэкенда перевёденные куски шаблона, если нужно что-то задействовать в JS.
March 17, 2019, 10:47 p.m.
Евгений Легоцкой

Добрый день. Вот, нашлось у меня немного времени. Делается это через шаблон проектирования наблюдатель. GraphKS_mfvSlup.zip
ЧГ
March 15, 2019, 9:52 p.m.
Чарльз Грин

спасибо, попробую, отпишусь
m
March 15, 2019, 7:41 p.m.
mihamuz

Сори догадался)
n
March 12, 2019, 4:57 p.m.
newbie.works.with.QT

Большооооое спасибо!!!!!Не передать как я вам благодарен, спасибо что всегда отзываетесь.Теперь я смогу продолжить работу в QT!!! (пробую писать бота (Я как вы могли догадаться немного не пр...
Join us in social networks

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