如何访问Django模板中一对多关系的属性?

axzmvihb  于 2022-12-14  发布在  Go
关注(0)|答案(2)|浏览(144)

我是Python和Django的新手,我正在构建一个个人日记,它有非常简单的属性,比如月份和条目。

models.py
class Month(models.Model):
    id = models.AutoField(primary_key=True)
    month_name = models.CharField(verbose_name="Month", max_length=20, unique=True)
    year_number = models.IntegerField(verbose_name="Year")
    featured_img = models.ImageField(verbose_name="Featured", upload_to='diary/featured_img', default=False)

    class Meta:
        verbose_name = "Month"
        ordering = ['-year_number', 'month_name']

    def __str__(self):
        return '%s, %s' % (self.month_name, self.year_number)

class Entry(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200)
    content = models.TextField()
    month = models.ForeignKey('Month', on_delete=models.RESTRICT, null=True)
    img = models.ImageField(verbose_name="Image", upload_to='diary/entry_img', default=False)
    date_created = models.DateTimeField(verbose_name="Date", default=timezone.now)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = "Entries"
        ordering = ['-date_created']

我正在尝试建立一个简单的网页,以列表形式显示月份,当我点击月份时,我会在详细视图中看到条目。我完成了第一步,但我不知道如何访问Django模板中月份和条目模型之间的一对多关系。我想做的是显示一个页面,其中包含所有月份模型对象,当用户点击特定月份时说“December”,Django返回所有将month对象定义为December的条目。
这在我插入TabularInLine方法的管理站点中运行良好,我可以看到特定月份的所有条目,但我不知道如何在模板和视图中执行此操作。

admin.py
class EntryInLine(admin.TabularInline):
    model = Entry

class MonthAdmin(admin.ModelAdmin):
    inlines = [EntryInLine]

admin.site.register(Month, MonthAdmin)
views.py
class MonthListView(generic.ListView):
    model = Month
    context_object_name = 'month_list'
    template_name = 'diary/month.html'

class MonthDetailView(generic.DetailView):
    model = Entry
    context_object_name = 'entries_list'
    template_name = 'diary/entries.html'

def index(request):
    month = Month.objects.all()
    entry = Entry.objects.all()

    context = {
        'month': month,
        'entry': entry,
    }

    return render(request, 'index.html', context=context)
urls.py
urlpatterns = [
    path('', views.index, name='index'),
    path('month/', views.MonthListView.as_view(), name='month'),
    path('month/<int:pk>', views.MonthDetailView.as_view(), name='entries'),
]
月份. html
{% extends "base.html" %}

{% block title %}<title>Months</title>{% endblock %}

{% block content %}
<h1>Month</h1>
{% if month_list %}
    <ul>
        {% for month in month_list %}
        <li>
            <a href="month.get_absolute_url()">{{ month.month_name }}</a>
        </li>
        {% endfor %}
    </ul>
    {% else %}
    <p>There are no months to display</p>
    {% endif %}
{% endblock %}
条目. html
{% extends "base.html" %}

{% block title %}<title>Entries</title>{% endblock %}

{% block content %}
{% if entries_list %}
        {% for entry in entries_list %}
            <h3>{{ entry.title }}</h3>
            <p>{{ entry.date_created }}</p>
            <p>{{ entry.content }}</p>
        {% endfor %}
{% else %}
    <p>There are no entries in this month.</p>
{% endif %}
{% endblock %}

我知道问题可能是在DetailView中添加Entry模型和urlMap,但是我在网上找不到一个好的资源来解释到底是什么问题。

wnavrhmk

wnavrhmk1#

我找到了!在MonthDetailView中添加了get_context_data函数,现在它可以工作了!

class MonthDetailView(generic.DetailView):
    model = Entry
    context_object_name = 'entries_list'
    template_name = 'diary/entries.html'

    def get_context_data(self, **kwargs):
        context = super(MonthDetailView, self).get_context_data(**kwargs)
        context['entries_list'] = Entry.objects.filter(month=self.kwargs['pk'])
        return context
vxf3dgd4

vxf3dgd42#

class MonthDetailView(generic.DetailView):
    model = Entry
    context_object_name = 'entries_list'
    template_name = 'diary/entries.html'

    def get_context_data(self, **kwargs):
        pk = kwargs.get('pk') # this is the primary key from your URL
        context = super(MonthDetailView, self).get_context_data(**kwargs)
        context['entries_list'] = Entry.objects.filter(month=pk)
        return context

我想这可能会有帮助。

相关问题