Evgenij LegotskojSept. 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.

<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.
Support the author Donate

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

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

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>

Comments

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

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
V

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

  • Result:50points,
  • Rating points-4
DK

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

  • Result:20points,
  • Rating points-10
s
  • storm
  • Jan. 20, 2023, 10:30 p.m.

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

  • Result:0points,
  • Rating points-10
Popular publications in the last 90 Days
Last comments
S

Qt WinAPI - Lesson 004. QtIFW - Automation WinDeployQt and build installers with Qt Installer Framework

Hello Evgenij, regarding the online installer, I've tried many times to use web host for the created repo after repogen step. I tried using github but I found people talking it is not …
  • juvf
  • Jan. 17, 2023, 9:18 a.m.

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

PS. Почти дописал плеер на QML. Уперся в ограничения QML. Переписываю плеер на с++/qt, а графика останится в qml. Нашел то, что мне надо, а именно индикатор звука. Qt может перехватывать аудиопо…

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

В этом случае вижу только какой-нибудь костыль в стиле перебора по всем индексам в заголовке с помощью методу headerData . То есть пройтись в for цикле пока не будет совпадения н…
a
  • avt
  • Dec. 12, 2022, 8:06 p.m.

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо за ответ. Нет, дело не в читаемости кода, в разных таблицах у меня есть столбцы с одинаковым именем, но с разными индексами. Хотел сделать решение по имени столбца для всех таблиц сразу.…
  • juvf
  • Dec. 12, 2022, 3:06 p.m.

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Спасибо.
Now discuss on the forum

Как создать уникальное значение поля на основе существующих значений

В принципе это можно сделать так: def unique_field(self): return '{0}_{1}'.format(self.title, self.price)class Tovar(models.Model): title=models.CharField('Наименование',max_length=…
W
  • Wayne
  • Jan. 27, 2023, 12:47 p.m.

Здравствуйте помогите с qml

как сделать так, чтобы зеленая фигура при движения за пределы круга пропадала на qml
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

QSqlRelatipnalTabelModel Qt 4.8.1 как получить id внешней связи?

Наконец-то готовы представить полноценное развитие Qt QSqlTableModel и QTableView. Посмотреть можно у нас на сайте здесь На github здесь здесь Радостная новос…
P
  • Pisych
  • Jan. 25, 2023, 10:01 p.m.

Ввод бухгалтерского документа в одной форме

вопрос снят. спасибо за ответы. сообразил, как сделать:)
About
Services
© EVILEG 2015-2022
Recommend hosting TIMEWEB