【问题标题】:Using data from one Django application in another在另一个 Django 应用程序中使用数据
【发布时间】:2023-03-31 05:56:01
【问题描述】:

我有一个 Django 博客站点。它包含两个应用程序:blogpages

博客应用列出所有博客项目如下:

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 %}

我的页面应用有 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'

我的页面中没有模型。

有什么方法可以使用我的博客应用程序中的NewsListView 在我的主页中显示最近的 3 个条目,或者我必须在我的页面应用程序中创建一个类似的模型和视图才能获取博客条目?

我试过了:

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 %}

但是,当我尝试访问主页时,我得到了这个:

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]+)/$']

我认为这来自于我的 news/models.py:

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

【问题讨论】:

    标签: python django


    【解决方案1】:

    你快到了。试试这个:

    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 %}
    

    【讨论】:

    • 谢谢@Walucas。当我尝试时,我得到这个错误:File "/Users/paulcarron/git/lakelandcc/pages/urls.py", line 6, in &lt;module&gt; path('', HomePageView.as_view(), name='home'),。这是我的页面/urls.py from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ]
    • 您需要将您的网址从:HomePageView.as_view() 更新为HomePageView
    • 感谢您的帮助。这正是我正在寻找的。​​span>
    猜你喜欢
    • 2023-03-20
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2021-11-16
    • 1970-01-01
    • 2010-09-24
    相关资源
    最近更新 更多