[英]Cannot resolve keyword 'slug' into field
我正在使用 Django 在我的博客中创建评论和回复系统。现在我正在尝试获取没有回复评论的评论查询集(如果我不这样做,回复评论将作为常规评论显示在页面上)。 这是我得到的错误:
/post/fourh-news 处的 FieldError 无法将关键字“slug”解析为字段。 选择是:comm_to_repl,comm_to_repl_id,comment_content,创建,id,post,post_of_comment,post_of_comment_id,reversies,user_created_comment,user_created_comment_id request request:获取请求URL: 886602088:88255541222222274/122274 // .2 异常类型:FieldError 异常值:
无法将关键字“slug”解析为字段。 选项有:comm_to_repl、comm_to_repl_id、comment_content、created、id、post、post_of_comment、post_of_comment_id、replies、user_created_comment、user_created_comment_id 异常位置:D:\pythonProject28django_pet_project\venv\lib\site-packages\django\db\models\sql\query。 py,第 1709 行,在 names_to_path 期间引发:blog.views.ShowSingleNews Python 版本:3.10.4
Model:
class Post(models.Model):
title = models.CharField(max_length=150, verbose_name='Название')
slug = models.CharField(max_length=100, unique=True, verbose_name='Url slug')
content = models.TextField(verbose_name='Контент')
created_at = models.DateTimeField(auto_now=True, verbose_name='Дата добавления')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата обновления')
posted_by = models.CharField(max_length=100, verbose_name='Кем добавлено')
photo = models.ImageField(upload_to='photos/%Y/%m/%d', verbose_name='Фото', blank=True)
views = models.IntegerField(default=0)
category = models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name='Категория')
tag = models.ManyToManyField('Tags', verbose_name='Тэг', blank=True)
comment = models.ForeignKey('Comment', verbose_name='Комментарий', on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('single_news', kwargs={'slug': self.slug})
class Meta:
ordering = ['-created_at']
class Category(models.Model):
title = models.CharField(max_length=150, verbose_name='Название')
slug = models.CharField(max_length=100, unique=True, verbose_name='category_url_slug')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category', kwargs={'slug': self.slug})
class Meta:
ordering = ['title']
class Tags(models.Model):
title = models.CharField(max_length=150, verbose_name='Название')
slug = models.CharField(max_length=100, unique=True, verbose_name='tag_url_slug')
def get_absolute_url(self):
return reverse('news_by_tag', kwargs={'slug': self.slug})
def __str__(self):
return self.title
class Meta:
ordering = ['title']
class Comment(models.Model):
user_created_comment = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, null=True)
post_of_comment = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True)
comment_content = models.TextField(verbose_name='Текст комментария')
created = models.DateTimeField(auto_now=True)
comm_to_repl = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
def get_absolute_url(self):
return reverse('single_news', kwargs={'slug': self.post_of_comment.slug})
class Meta:
ordering = ['-created']
看法:
class ShowSingleNews(DetailView):
model = Post
template_name = 'blog/single_news.html'
context_object_name = 'post'
raise_exception = True
form = CommentForm
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
post = self.get_object()
form.instance.user_created_comment = request.user
form.instance.post_of_comment = post
commrepl = request.POST.get("commentID")
form.instance.comm_to_repl_id = int(commrepl)
form.save()
else:
print("some error with form happened")
print(form.errors.as_data())
return redirect(reverse("single_news", kwargs={
"slug": self.get_object().slug
}))
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = Post.objects.get(slug=self.kwargs['slug'])
context['form'] = self.form
self.object.views = F('views') + 1
self.object.save()
self.object.refresh_from_db()
return context
def get_queryset(self):
return Comment.objects.filter(replies=None)
模板:
{% extends 'base.html' %}
{% load static %}
{% load sidebar %}
{% block title %}
{{ title }}
{% endblock %}
{% block header %}
{% include 'inc/_header.html'%}
{% endblock %}
{% block content %}
<section class="single-blog-area">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="border-top">
<div class="col-md-8">
<div class="blog-area">
<div class="blog-area-part">
<h2>{{ post.title}}</h2>
<h5> {{ post.created_at }}</h5>
<img src="{{ post.photo.url }}">
<div>
<span>Category: {{ post.category }}</span> <br>
<span>Posted by: {{ post.posted_by }}</span> <br>
</div>
<h5>Views: {{ post.views }}</h5>
<p>{{ post.content|safe }}</p>
<div class="commententries">
<h3>Comments</h3>
{% if user.is_authenticated %}
<form method="POST" action="{% url 'single_news' slug=post.slug %}">
{% csrf_token %}
<input type="hidden" id="commentID">
<div class="comment">
<input type="text" name="comment_content" placeholder="Comment" class="comment">
</div>
<div class="post">
<input type="submit" value="Post">
</div>
</form>
{% else %}
<h5><a href="{% url 'login' %}">Login</a> in order to leave a comment</h5>
{% endif %}
<ul class="commentlist">
{% if not post.comments.all %} </br>
<h5>No comments yet...</h5>
{% else %}
{% for comment in post.comments.all %}
<li>
<article class="comment">
<header class="comment-author">
<img src="{{ user.image.url }}" alt="">
</header>
<section class="comment-details">
<div class="author-name">
<h5><a href="#">{{ comment.user_created_comment.username }}</a></h5>
<p>{{ comment.created }}</p>
</div>
<div class="comment-body">
<p>{{ comment.comment_content }} </p>
</div>
<div class="reply">
<p><span><a href="#"><i class="fa fa-thumbs-up" aria-hidden="true"></i></a>12</span><span><button class="fa fa-reply" aria-hidden="true"></button>7</span></p>
<form method="POST" action="{% url 'single_news' slug=post.slug %}">
{% csrf_token %}
<input type="hidden" name="commentID" value="{{ comment.id }}">
<div class="comment">
<input type="text" name="comment_content" placeholder="Comment" class="replyComment">
</div>
<div class="post">
<input type="submit" value="Reply">
</div>
</form>
</div>
</section>
{% if comment.replies.all %}
{% for reply in comment.replies.all %}
<ul class="children">
<li>
<article class="comment">
<header class="comment-author">
<img src="{% static 'img/author-2.jpg' %}" alt="">
</header>
<section class="comment-details">
<div class="author-name">
<h5><a href="#">{{ reply.user_created_comment.username }}</a></h5>
<p>Reply to - {{ reply.comm_to_repl.user_created_comment }}</p>
<p>{{ reply.created }}</p>
</div>
<div class="comment-body">
<p>{{ reply.comment_content}}</p>
</div>
<div class="reply">
<p><span><a href="#"><i class="fa fa-thumbs-up" aria-hidden="true"></i></a>12</span><span><a href="#"><i class="fa fa-reply" aria-hidden="true"></i></a>7</span></p>
<form method="POST" action="{% url 'single_news' slug=post.slug %}">
{% csrf_token %}
<input type="hidden" name="commentID" value="{{ reply.id }}">
<div class="comment">
<input type="text" name="comment_content" placeholder="Comment" class="replyComment">
</div>
<div class="post">
<input type="submit" value="Reply">
</div>
</form>
</div>
</section>
</article>
</li>
</ul>
{% endfor %}
{% endif %}
</article>
{% endfor %}
{% endif %}
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="newsletter">
<h2 class="sidebar-title">Search for the news</h2>
<form action="{% url 'search' %}" method="get">
<input type="text" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
</div>
{% get_popular_posts 5 %}
<div class="tags" style="">
<h2 class="sidebar-title">Tags</h2>
{% for ta in post.tag.all %}
<p><a href="{{ ta.get_absolute_url }}">{{ ta.title }}</a></p>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
{% block footer %}
{% include 'inc/_footer.html' %}
{% endblock %}
网址:
urlpatterns = [
path('', HomePage.as_view(), name='home'),
path('category/<str:slug>/', GetCategory.as_view(), name='category'),
path('post/<str:slug>', ShowSingleNews.as_view(), name='single_news'),
path('tag/<str:slug>', GetNewsByTag.as_view(), name='news_by_tag'),
path('search/', Search.as_view(), name='search'),
path('registration/', registration, name='registration'),
path('login/', loginn, name='login'),
path('logout/', logoutt, name='logout'),
forms:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment_content']
你需要像这样在 HTML 中传递URL
...
<form method="POST" action="{% url 'single_news' post.slug %}">
{% csrf_token %}
<input type="hidden" id="commentID">
<div class="comment">
<input type="text" name="comment_content" placeholder="Comment" class="comment">
</div>
<div class="post">
<input type="submit" value="Post">
</div>
</form>
注意:- 如果您想使用密钥传递 url,您可以这样做
<form method="POST" action="{% url 'single_news'?slug=post.slug %}">
{% csrf_token %}
<input type="hidden" id="commentID">
<div class="comment">
<input type="text" name="comment_content" placeholder="Comment" class="comment">
</div>
<div class="post">
<input type="submit" value="Post">
</div>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.