Evgenii Legotckoi
Sept. 20, 2016, 11:20 p.m.

Django - Tutorial 005. Adding RSS feeds to the site on Django

While still not a lot of articles on the new site, I add RSS-feed, the benefit of that Django has a built-in functionality for organizing RSS-feeds, as in the usual format, and the Atom format. But first, usually confine adding news feeds, which can be connected to the service by FeedBurner, and also found on the site some RSS-reader. For example, I use QuiteRSS , which, incidentally, is written in Qt5.


What is needed for organizing RSS-feeds in the minimum version:

  1. Add a reference to the feed in the body of the page head-tag;
  2. Write view, which will be responsible for the preparation of the feed;
  3. Modify a model for the projects which will be based newswire.

Adding links to RSS-feed

First, add a link to the RSS-feed is in the page header. Why do it? - It is necessary to ensure that RSS-readers can easily find the feed when parse your site. If you do not provide a link, the user will have to manually search your RSS-feed.

  1. <head>
  2. ...
  3. <link rel="home" type="application/rss+xml" href="http://example.com/feed" />
  4. ...
  5. </head>
  6.  

In this case, RSS-feed contains at feed.

Implementation of view

To implement the presentation we need a Feed class, and import that model, the objects which will be based newswire. Naturally chosen the Article model, about which I have already told in the article on the models, templates and views that are used on this site.

  1. from django.contrib.syndication.views import Feed
  2. from knowledge.models import *
  3.  
  4.  
  5. class ArticlesFeed(Feed):
  6. title = "EVILEG - Practical programming"
  7. description = "Recent Articles EVILEG site about programming and information technology"
  8. link = "/"
  9.  
  10. def items(self):
  11. return Article.objects.exclude(article_status=False).order_by('-article_date')[:10]
  12.  
  13. def item_title(self, item):
  14. return item.article_title
  15.  
  16. def item_description(self, item):
  17. return item.article_content[0:400] + "<p>The article first appeared on <a href="\"https://evileg.com/en\"">EVILEG " \
  18. "- Practical programming</a></p>"

So, in order to take advantage of the RSS-feed, you must inherit from the class Feed. Override the title field, which will be the name of your RSS-channel to override the description field, which is a description of your RSS-channel, as well as specify the channel address, but since I have this channel is the main page of the site, the link is specified as a slash.

NOTE: If you do not specify the link even so, will crumble errors and nothing will not work.

items method returns the 10 most recent articles, excluding those that have the status of a draft.

item_title method respectively substitutes the name of the article.

item_description method substitutes the description of articles in the field article_content model. In the description enter the first 400 characters in the article and additional signature with a link back to the site. Contact link to the site is made to news aggregators, which will feed on your website leave back links to the website at.

Modification Article Model

  1. def get_absolute_url(self):
  2. return reverse('knowledge:article', kwargs={'section': self.article_section.section_url,
  3. 'article_id': self.id})

Articles are in knowledge module and divided into sections. Therefore, to form a complete address is used two variables:

  1. address of section
  2. id of article

URL pattern is as follows:

  1. url(r'^(?P[\w]+)/(?P<article_id>[0-9]+)/$', views.EArticleView.as_view(),

Adding a URL pattern for RSS

And to make it work, it is necessary to add a URL pattern for RSS. I have this template is in the home module, as well as all news feed, in addition to the model articles. And this pattern looks as follows.

  1. from django.conf.urls import url
  2.  
  3. from . import views
  4.  
  5. urlpatterns = [
  6. url(r'^feed/$', views.ArticlesFeed()),
  7. ]

For Django I recommend VDS-server of Timeweb hoster
.

Илья Чичак
  • Dec. 11, 2018, 8:52 p.m.

Тут мне тоже есть что сказать=)

Сами разрабы советуют импортировать следующим образом:

  1. from <application_name> import <module_name>

Стоит избегать

  1. from . import <module_name>

или

  1. from <application_name> import *

в первом случае некоторым IDE срывает крышу=) (а вообще это несколько опасно, особенно в случае с джангой - можно импортнуть не то и не оттуда)

а во втором может случиться коллизия, например в двух модулях есть классы с одним и тем же именем (ну мало ли). и вот не угадаешь, какой будет в итоге=)

Явное лучше неявного=)

Evgenii Legotckoi
  • Dec. 11, 2018, 9:06 p.m.

Что интересно, если написать так

  1. from <application_name>.<module_name> import <filename>

,то PyCharm сносит крышу, если разрабатываешь в рамках проекта приложение, которое подготавливается в качестве самостоятельного приложения, которое в дальнейшем можно будет устанавливать через pip . То есть если оно имеет структуру гит репозитория, как, например, evileg_core

PyCharm вообще не понимает, что происходит.
приходится писать так

  1. from .<module_name> import <filename>

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html