简体   繁体   中英

Cannot resolve keyword 'slug' into field

Im making comment and reply system in my blog using Django. Now im trying to get queryset of comments that dont have reply comments(if I dont do this, reply comments will be displayed on a page as regular comments). Here is error that i got:

FieldError at /post/fourh-news Cannot resolve keyword 'slug' into field. Choices are: 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 Request Method: GET Request URL: http://127.0.0.1:8000/post/fourh-news Django Version: 4.1.2 Exception Type: FieldError Exception Value:
Cannot resolve keyword 'slug' into field. Choices are: 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 Exception Location: D:\pythonProject28django_pet_project\venv\lib\site-packages\django\db\models\sql\query.py, line 1709, in names_to_path Raised during: blog.views.ShowSingleNews Python Version: 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']

View:

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)

Template:

{% 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 %}



Urls:

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']

You need to be a bit of change in passing URL in HTML like this...

<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>

NOTE:- If you want to pass url with key you can do like this

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM