为什么Django抛出错误无法解决关键字slug

dxpyg8gm  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(111)

我一直在尝试建立一个学生学习平台,但我有一些真实的的问题,使用slug在Django创建可读的网址,但我遇到了这个错误

Cannot resolve keyword 'slug' into field. Choices are: Notes, Standard, Standard_id, created_at, created_by, created_by_id, id, lesson_id, name, position, ppt, slugs, subject, subject_id, video
Request Method: GET
Request URL:    http://127.0.0.1:8000/curriculumprimary-four/001/None/
Django Version: 3.2.12
Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'slug' into field. Choices are: Notes, Standard, Standard_id, created_at, created_by, created_by_id, id, lesson_id, name, position, ppt, slugs, subject, subject_id, video
Exception Location: /usr/lib/python3/dist-packages/django/db/models/sql/query.py, line 1569, in names_to_path
Python Executable:  /usr/bin/python3
Python Version: 3.10.6
Python Path:    
['/home/aiden/Projects/LMS/LMS',
 '/usr/lib/python310.zip',
 '/usr/lib/python3.10',
 '/usr/lib/python3.10/lib-dynload',
 '/home/aiden/.local/lib/python3.10/site-packages',
 '/usr/local/lib/python3.10/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Tue, 25 Jul 2023 09:27:05 +0000

字符串
这是我的models.py文件代码

from typing import Iterable, Optional
from django.db import models
import os
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django.urls import reverse

class Standard(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(null=True, blank = True)
    description = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        return super().save(*args, **kwargs)
    

def save_subject_img(instance, filename):
    upload_to = 'Images/'
    ext = filename.split('.')[-1]
    #get filename
    if instance.subject_id:
        filename = 'Subject_Pictures/{}.{}'.format(instance.subject_id, ext)
        return os.path.join(upload_to,filename)
   

class Subject (models.Model):
    subject_id = models.CharField(max_length=100, unique= True)
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(null=True, blank=True)
    standard = models.ForeignKey(Standard,on_delete=models.CASCADE,related_name="subjects")
    image = models.ImageField(upload_to=save_subject_img, blank=True,verbose_name='Subject Image')
    description = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        self.slug = slugify(self.subject_id)
        return super().save(*args, **kwargs)

def save_lesson_files(instance, filename):
    upload_to = 'Images/'
    ext = filename.split('.')[-1]
    #get filename
    if instance.lesson_id:
        filename = 'lesson_files/{}/{}.{}'.format(instance.lesson_id,instance.lesson_id, ext)
        if os.path.exists(filename):
            new_name =  str(instance.lesson.id)+ str('1')
            filename = 'lesson_files/{}/{}.{}'.format(instance.lesson_id,new_name, ext)

    return os.path.join(upload_to,filename)
   

class Lesson (models.Model):
    lesson_id = models.CharField(max_length=250, unique=True)
    Standard = models.ForeignKey(Standard, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name="lessons")
    name = models.CharField(max_length=250,unique = True)
    position = models.PositiveSmallIntegerField(verbose_name="Chapter no.")
    slugs = models.SlugField(null=True, blank=True)
    video = models.FileField(upload_to=save_lesson_files, verbose_name="Video", blank=True, null=True)
    ppt = models.FileField(upload_to=save_lesson_files, verbose_name="Presentations", blank=True)
    Notes = models.FileField(upload_to=save_lesson_files, verbose_name="Notes", blank=True, )

    class Meta:
        ordering = ['position']

    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        return super().save(*args, **kwargs)

    def get_absolute_url(self,queryset=None):
        return reverse('curriculum:lesson_list', kwargs={'slug':self.subject.slug, 'standard':self.Standard.slug})


然后我的views.py文件中有以下代码。

from django.shortcuts import render
from django.views.generic import (TemplateView,DetailView,ListView,FormView)
from .models import*

class StandardListView(ListView):
    context_object_name ='standards'
    model = Standard
    template_name = "curriculum/standard_list_view.html"

class SubjectListView(DetailView):
    context_object_name ='standards'
    model = Standard
    template_name = "curriculum/subject_list_view.html"

class LessonListView(DetailView):
    context_object_name ='subjects'
    model = Subject
    template_name = "curriculum/lesson_list_view.html"

class LessonDetailView(DetailView):
    context_object_name ='lessons'
    model = Lesson
    template_name = "curriculum/lesson_detail_view.html"


然后urls.py有以下代码

app_name = 'curriculum'
urlpatterns = [
    path('',views.StandardListView.as_view(),name='standard_list'),
    path('<slug:slug>', views.SubjectListView.as_view(), name='subject_list'),
    path ('<str:standard>/<slug:slug>/', views.LessonListView.as_view(),name='lesson_list'),
    path ('<str:standard>/<str:subject>/<slug:slug>/', views.LessonDetailView.as_view(),name='lesson_detail'),
]


Html文件如下

{% extends 'base.html' %}
{% block content %}
<p>Created on {{lessons.created_at}} by {{lessons.created_by}}</p>
{% endblock content %}


我试着弄清楚为什么它会抛出这个错误,但我没能通过任何人好心地帮助我,因为我卡住了。

kmpatx3s

kmpatx3s1#

Lesson模型中的变量是“slugs”,并且在调用它时传递了“slug”。

相关问题