【发布时间】:2021-10-01 08:11:54
【问题描述】:
晚上好,Django 对我来说是全新的,这是我在这里的第一个问题。 我正在尝试创建一个 Webapp。我正在使用 Django、Python 和 MariaDB。 我创建了一个包含两个应用程序的项目,并且每个应用程序都有一个模型。在第一个中,我使用“slug”作为字段名称,一切正常。在第二个中,我想区分该字段,该字段给出定义为 SlugField 的不同名称 (bk_slug)。我尝试使用相同类型的指令行并将它们修改为似乎不起作用的字段名称。我无法拥有正确的 URL(基于类的 ListView),也无法访问基于类的 DetailView.... 提前感谢您的支持。
models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.urls import reverse
# book masterdata
class Book(models.Model):
bk_title = models.CharField("Book Title", max_length=100,
primary_key=True)
bk_originaltitle = models.CharField("Book original Title",
max_length=100, blank=True)
bk_author = models.CharField("Author", max_length=50)
bk_editor = models.CharField("Editor", max_length=50)
bk_editiondate = models.CharField("Book Edition date",
max_length=30)
bk_recblocked = models.BooleanField("Book record blocked")
bk_creator = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='+', verbose_name="Created by")
bk_creationdate = models.DateTimeField("Creation date",
auto_now=True)
bk_modifier = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name='+', verbose_name="Last modification by")
bk_modified = models.DateTimeField("Last modification date",
auto_now=True)
bk_slug = models.SlugField(max_length=100, allow_unicode=True,
blank=True)
def __str__(self):
return self.bk_title
def get_absolute_url(self):
return reverse('book_detail', kwargs={'slug': self.bk_slug})
urls.py
from django.urls import path
from dimlibrary.views import BookListView
from dimlibrary.views import BookDetailView
urlpatterns = [
path('', BookListView.as_view(), name='book_list'),
path('<slug:bk_slug>/', BookDetailView.as_view(),
name='book_detail'),
]
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.utils import timezone
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from dimlibrary.models import Book
# book views :
# List view
class BookListView(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
# Details View
class BookDetailView(DetailView):
model = Book
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
```html
{% extends 'base/base.html' %}
{% load static %}
{% block content %}
<h1>Books List</h1>
<ul>
{% for book in object_list %}
<li><a href="{{ dimlibrary.book.get_absolute_url }}">{{
book.bk_title }}</a> - {{ book.bk_author }} -
{{ book.bk_editor }}</li>
{% empty %}
<li>No book registred yet.</li>
{% endfor %}
</ul>
{% endblock content %}
【问题讨论】:
-
您能分享您的第二个应用的模型、视图、网址等吗?
-
嗨,Willem,我按要求插入了我的代码,提前感谢您的反馈