【问题标题】:I am not getting the value from the database我没有从数据库中获取值
【发布时间】:2022-01-27 15:15:43
【问题描述】:

我在 django 中使用 MVT。我正在使用通用 CBV(列表视图、详细视图)。这是我的代码

这是model.py

from django.db import models


class Singers(models.Model):
    name= models.CharField(max_length=256)
    age= models.IntegerField()
    gender= models.CharField(max_length=10)


class Albums(models.Model):
    name= models.CharField(max_length=256)
    singer=models.ForeignKey(Singers, on_delete=models.CASCADE)

view.py

from django.views import generic
from core.models import Albums, Singers

#in generic view instead of functions, we use classes

class AlbumView(generic.ListView):
    model = Albums
    template_name = 'index.html'
    paginate_by = 10
    def get_queryset(self):
        return Albums.objects.all()

class DetailView(generic.DetailView):
    model = Albums
    template_name = 'detailview.html'

这里是 urls.py

from django.urls import path
from core.views import AlbumView, DetailView
urlpatterns = [
    path('album/', AlbumView.as_view()),
    path('album/detail/<pk>/', DetailView.as_view())
]

这里是 index.html


{% block content %}
    <h2>Albums</h2>
    <ul>
        {% for albums in object_list %}
            <li>{{ albums.name }}</li>
        {% endfor %}
    </ul>
{% endblock %}


这里是 detailview.html

{% block content %}
  <h1>name: {{Albums.name}}</h1>
  <p><strong>Singer: {{Albums.Singer}}</strong></p>
{% endblock %}

详细视图无法正常工作。它没有获取专辑的名称和歌手的详细信息。

建议我该怎么做?

【问题讨论】:

  • detailview.html 中,将Album 更改为object,例如,使用{{Albums.name}} 代替{{Albums.name}}
  • 然后它显示一个空白页面。我该怎么办?

标签: html django django-models django-views django-templates


【解决方案1】:

试试这个

{% block content %}
  <h1>name: {{object.name}}</h1>
  <p><strong>Singer: {{object.singer.name}}</strong></p>
{% endblock %}

【讨论】:

    【解决方案2】:
    class DetailView(generic.DetailView):
        model = Albums
        template_name = 'detailview.html'
    

    这是行不通的,你必须得到这样的第一个上下文

    def get_context_data(self, **kwargs):
            // Call the base implementation first to get a context
            context = super().get_context_data(**kwargs)
            // Add in a QuerySet of all the books
            context['Album_list'] = Albums.objects.all()
            return context
    

    你也可以这样做

    context_object_name = 'publisher'
    queryset = Publisher.objects.all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 2011-04-08
      • 2021-08-31
      • 1970-01-01
      • 2017-01-02
      • 2016-09-14
      • 2014-12-26
      • 1970-01-01
      相关资源
      最近更新 更多