runnerpaul
runnerpaul

Reputation: 7196

Using data from one Django application in another

I have a Django blog site. It contains two applications: blog and pages.

The blog app lists all blog items as follows:

models.py:

class News(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )
    thumb = models.ImageField(blank=True, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('news_detail', args=[str(self.id)])

views.py

class NewsListView(ListView):
    model = News
    template_name = 'news_list.html'

news_list.html

{% extends 'base.html' %}

{% block title %}News{% endblock title %}

{% block content %}
  {% for news in object_list %}
    <div class="card" style="width: 300px; display: inline-block; margin: 5px; vertical-align: top;">
       <div class="card-header">
        <span class="font-weight-bold">
          <a href="{% url 'news_detail' news.pk %}" style="color:black">{{ news.title }}</a>
        </span> &middot;
        <span class="text-muted">by {{ news.author }} | {{ news.date }}</span>
      </div>
      <div class="card-body">
        {% if news.thumb %}
          <p align="center"><img src="{{ news.thumb.url }}" /></p>
        {% endif %}
        <p>{{ news.body | linebreaks | truncatewords:30 }}
          <a href="{% url 'news_detail' news.pk %}">Full story</a></p>
      </div>
      <div class="card-footer">
        {% if user.is_authenticated %}
          <a href="{% url 'news_edit' news.pk %}">Edit</a>
          <a href="{% url 'news_delete' news.pk %}">Delete</a>
        {% endif %}
      </div>
    </div>
  {% endfor %}
{% endblock content %}

My pages app has home.html:

{% extends 'base.html' %}

{% block title %}Home{% endblock title %}

{% block content %}
    <div class="jumbotron">
        <h1 class="display-4">Lakeland Cycle Club</h1>
        <p class="lead">The home of cycling in Fermanagh.</p>
        <p class="lead">
            <a class="btn btn-primary btn-lg" href="{% url 'news_list' %}" role="button">View All Club News</a>
        </p>
    </div>
{% endblock content %}

views.py:

class HomePageView(TemplateView):
    template_name = 'home.html'

I have no model in pages.

Is there any way I can use the NewsListView from my blog application to display the 3 most recent entries in my home page or must I create a similar model and view in my pages application in order to get the blog entries?

I tried this:

pages/views.py

from news.models import News

class HomePageView(TemplateView):
    model = News
    template_name = 'home.html'
    queryset = News.objects.order_by('-date')[:3]

home.html

{% extends 'base.html' %}

{% block title %}Home{% endblock title %}

{% block content %}
    <div class="jumbotron">
        <h1 class="display-4">Lakeland Cycle Club</h1>
        <p class="lead">The home of cycling in Fermanagh.</p>
        <p class="lead">
            <a class="btn btn-primary btn-lg" href="{% url 'news_list' %}" role="button">View All Club News</a>
        </p>
         <span class="font-weight-bold">
          <a href="{% url 'news_detail' news.pk %}" style="color:black">{{ news.title }}</a>
        </span>
    </div>
{% endblock content %}

However, whenI try to access the home page I get this:

File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/urls/resolvers.py", line 622, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'news_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['news/(?P<pk>[0-9]+)/$']

I think it comes from having this in my news/models.py:

    def get_absolute_url(self):
        return reverse('news_detail', args=[str(self.id)])

Upvotes: 0

Views: 98

Answers (1)

Walucas
Walucas

Reputation: 2568

You are almost there. Try this:

views.py

from news.models import News
from django.shortcuts import render

def HomePageView(request):
    context = {}
    news = News.objects.order_by('-date')[:3]  
    context['news']=news 
    return render(request,'home.html',context)

home.html

    {% extends 'base.html' %}

    {% block title %}Home{% endblock title %}

    {% block content %}
        <div class="jumbotron">
            <h1 class="display-4">Lakeland Cycle Club</h1>
            <p class="lead">The home of cycling in Fermanagh.</p>
            <p class="lead">
                <a class="btn btn-primary btn-lg" href="{% url 'news_list' %}" role="button">View All Club News</a>
            </p>
             <span class="font-weight-bold">
               {%for new in news%}
{{new.title}}
{%endfor%}
            </span>
        </div>
    {% endblock content %}

Upvotes: 1

Related Questions