Evgenii Legotckoi
Evgenii LegotckoiSept. 20, 2016, 1: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.

<head>
...
<link rel="home" type="application/rss+xml" href="http://example.com/feed" />
...
</head>

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="\"https://evileg.com/en\"">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,
                                                '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:

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
.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

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

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

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

from <application_name> import <module_name>

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

from . import <module_name>

или

from <application_name> import *

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

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

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

Evgenii Legotckoi
  • Dec. 11, 2018, 10:06 a.m.

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

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

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

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

from .<module_name> import <filename>

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 8:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 4:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 6:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks