【问题标题】:How to return single object in a Django model and view如何在 Django 模型和视图中返回单个对象
【发布时间】:2020-07-22 21:33:37
【问题描述】:

我想从模型中返回一个非常基本的单个段落,但我不知道如何或哪个是最好的方法。这是一个简单的描述文本字段(maindescription),我希望将来能够更改,而不是对其进行硬编码。它必须是简单的方法,但我只能找到一个很好的例子。对于如何正确编写视图并在模板中检索它的任何帮助,我们将不胜感激。

model.py

from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel
from time import strftime, gmtime
# Receive the pre_delete signal and delete the file associated with the model instance.
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

class Song(models.Model):
    author = models.CharField("Author", max_length=255) 
    song_name = models.CharField("Song Name", max_length=255)
    slug = AutoSlugField("Soundtrack", unique=True, always_update=False, populate_from="song_name")
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    audio_file = models.FileField(upload_to='mp3s/', blank=True)

    def __str__(self):
        return self.song_name

class MainDescription(models.Model):    
    main_description = models.TextField()
    slug = AutoSlugField("Main Description", unique=True, always_update=False, populate_from="main_description")
    
    def __str__(self):
        return self.main_description

view.py

from django.views.generic import ListView, DetailView
from .models import Song, MainDescription

class SongListView(ListView):
    model = Song

# Overwrite the default get_context_data function
def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    # Add extra information here, like the first MainDescription Object
    context['main_description'] = MainDescription.objects.first()
    return context

admin.py

from django.contrib import admin
from .models import Song, MainDescription

admin.site.register(Song)
admin.site.register(MainDescription)

urls.py

from django.urls import path
from . import views

app_name = "music"
urlpatterns = [
    path(
        route='',
        view=views.SongListView.as_view(),
        name='list'
    ),
]

song_list.html

{% extends 'base.html' %}

{% block content %}
<div class="container">
<p>{{ main_description.main_description }}</p>
</div>
<ul class="playlist show" id="playlist">
{% for song in song_list %}
    <li audioURL="{{ song.audio_file.url }}" artist="{{ song.author }}"> {{ song.song_name }}</li>  
{% endfor %}
</ul> 
{% endblock content %}
</div>

【问题讨论】:

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


    【解决方案1】:

    您似乎正在尝试向 SongListView 添加额外的上下文

    class SongListView(ListView):
    
       model = Song
    
       # Overwrite the default get_context_data function
       def get_context_data(self, **kwargs):
           # Call the base implementation first to get a context
           context = super().get_context_data(**kwargs)
           # Add extra information here, like the first MainDescription Object
           context['main_description'] = MainDescription.objects.first()
           return context
    

    然后在你的模板中你可以做这样的事情

    <p>{{ main_description.main_description }}</p>
    

    有关文档的更多信息,您可以找到它here

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 2013-03-27
      相关资源
      最近更新 更多