Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

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

Feed, RSS, Python

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.

<link rel="home" type="application/rss+xml" href="" />

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.

from django.contrib.syndication.views import Feed
from knowledge.models import *

class ArticlesFeed(Feed):
    title = "EVILEG - Practical programming"
    description = "Recent Articles EVILEG site about programming and information technology"
    link = "/"

    def items(self):
        return Article.objects.exclude(article_status=False).order_by('-article_date')[:10]

    def item_title(self, item):
        return item.article_title

    def item_description(self, item):
        return item.article_content[0:400] + "<p>The article first appeared on <a href="\"\"">EVILEG " \
                                "- 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

def get_absolute_url(self):
    return reverse('knowledge:article', kwargs={'section': self.article_section.section_url,

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:

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.

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^feed/$', views.ArticlesFeed()),

For Django I recommend VDS-server of Timeweb hoster .

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

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

from <application_name> import <module_name>

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

from . import <module_name>


from <application_name> import *

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

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

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

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

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

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

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

from .<module_name> import <filename>


Only authorized users can post comments.
Please, Log in or Sign up
Jan. 17, 2019, 11:51 a.m.

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

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

C++ - Test 002. Constants

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

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

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

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

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

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

Сделал вот так. В 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.

Для 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.

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

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