我刚开始在Django工作。我的问题,在解决与slug我得到一个错误时,发送一个请求到Slug。
这是我的错误:Articles matching query does not exist.
迁移时也会出现错误。
这是我的错误:django.db.utils.OperationalError:table "bloges_category" already exists
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
class Articles(models.Model):
Writer = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
Title = models.CharField(max_length=40, unique=True)
Body = models.TextField()
Image = models.ImageField(upload_to='articles')
Time = models.DateTimeField(editable=False, auto_now_add=True)
Update = models.DateTimeField(auto_now=True)
slug = models.SlugField(blank=True, unique=True)
def save(
self, force_insert=False, force_update=False, using=None, update_fields=None):
self.slug = slugify(self.Title)
super(Articles, self).save()
def get_absolute_url(self):
return reverse("bloges:articles_detail", args=[self.slug])
字符串
我的看法:
from django.shortcuts import render
from bloges.models import Articles
def post(request, slug):
articles = Articles.objects.get(slug=slug)
return render(request, 'bloges/post-details.html', {"postartic": articles})
型
我的网址:
from django.urls import path
from . import views
app_name = 'bloges'
urlpatterns = [
path("post/<slug:slug>", views.post, name="articles_detail")
]
型
发送请求后出错:Articles matching query does not exist.
个
1条答案
按热度按时间knsnq2tg1#
当我向Slug发送请求时,我得到一个错误,这是我的错误:与查询匹配的文章不存在。
这是因为您发布的名为
post
的视图没有一个名为slug
的URL参数与您的视图中的调用匹配:articles = Articles.objects.get(slug=slug)
。这会出错,因为你使用了
get()
,如果找不到搜索的对象,它会抛出一个错误。一个常见的解决方案是使用get_object_or_404(Articles, slug=slug)
,当找不到对象时,它会抛出一个HTTP 404
,或者使用filter
,即articles = Articles.objects.filter(slug=slug)
,在这种情况下,如果变量articles
不可用(即if not articles
,None
或Articles.objects.none()
,你做你想做的。注意你的URL参数:
字符串
这可能会调用一个URL,如:
http://localhost:8000/post/foo
其中
foo
不是Articles
中的slug
:Articles.objects.get(slug='foo')
我在迁移时得到一个错误这是我的错误:django.db.utils.OperationalError:table“bloges_category”already exists
我们需要查看您的迁移情况以及当前的数据库结构。总的来说,此错误说明您正在运行无法完成的迁移,因为它正在尝试创建一个已经存在的表。
我的第一个想法是你不小心删除了你的迁移文件,然后重新运行了
makemigrations
,或者你从数据库的迁移表中删除了你的数据。但是没有更多的信息,很难判断。