簡體   English   中英

無法將關鍵字“slug”解析為字段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM