微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果字段名称与 slug 不同,则 Slugfield 不起作用

如何解决如果字段名称与 slug 不同,则 Slugfield 不起作用

晚上好,Django 对我来说是全新的,这是我在这里的第一个问题。 我正在尝试创建一个 Web 应用程序。我正在使用 Django、Python 和 MariaDB。 我创建了一个包含两个应用程序的项目,每个应用程序都有一个模型。在第一个中,我使用“slug”作为字段名称,一切正常。在第二个中,我想区分该字段,给出一个不同的名称(bk_slug),定义为 SlugField。我尝试使用相同类型的指令行并为似乎不起作用的字段名称修改它们。我无法拥有正确的 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",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,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 %} 

解决方法

在您的 DetailView 中,您需要将 slug_field [Django-doc] 指定为 'bk_slug'

class BookDetailView(DetailView):
    model = Book
    slug_field = 'bk_slug'
    
    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        return context

在模型中,您需要 slugify(…) [Django-doc] 名称,因此:

from django.utils.text import slugify

class Book(models.Model):
    # …

    def save(self,*args,**kwargs):
        if not self.bk_slug:
            self.bk_slug = slugify(self.title)
        return super().save(*args,**kwargs)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。