python - 向文章 django createviewforeignkey 添加评论

标签 python django comments django-class-based-views

我想使用 django createview 在我的文章中添加评论。目前,我可以毫无问题地添加文章。我可以添加评论。但我无法将评论添加到正确的文章中。

我已经在这两天了。我真的很想用 CBV 来做这件事,因为我正在努力学习。任何帮助解释我做错了什么以及如何纠正它的帮助将不胜感激。

模型.py

class Article(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, null=True, blank=True)
    content = models.TextField(default='')
    author = models.ForeignKey(User)
    featured_image = models.ImageField(upload_to='articles/featured_image', default='')
    created = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(blank=True, null=True)
    update_author = models.ForeignKey(User, null=True, blank=True,
                                    related_name="+")

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural = 'Articles'
        ordering = ['-created',]


    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('articles:article-detail', kwargs={'slug': self.slug})


class ArticleComment(models.Model):
    article = models.ForeignKey(Article, 
                                related_name='comments',
                                null=True)
    author = models.ForeignKey(User,
                                null=True)
    text = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Article Comment'
        verbose_name_plural = 'Article Comments'


    def __str__(self):
        return self.text 

View .py

class ArticleDetailView(DetailView):
    model = Article
    context_object_name = 'article'

    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)
        article = Article.objects.all()
        context['sidebar_articles'] = article.order_by('-created')[:15]
        return context


class CreateArticleView(LoginRequiredMixin, CreateView):
    model = Article
    fields = ['title', 'content']

    def form_valid(self, form):
        article = form.save(commit=False)
        #featured_image = form.cleaned_data['featured_image']
        form.instance.author = self.request.user
        form.save()
        return super(CreateArticleView, self).form_valid(form)


class UpdateArticleView(UpdateView):
    model = Article 


class DeleteArticleView(DeleteView):
    model = Article 


class CreateArticleComment(CreateView):
    model = ArticleComment 
    fields = ('text',)

    def post_valid(self, form):
        post = get_object_or_404(Post, 
                                    slug=article.slug)
        article = Article.objects.all()
        articlecomment = form.save(commit=False)
        articlecomment.author = self.request.user
        articlecomment.article = article
        articlecomment.save()
        return redirect('articles:article-detail', slug=article.slug)

    def get_success_url(self):
        return reverse_lazy('articles:article-list')

url.py

urlpatterns = [
    url(r'^$',
        ArticleListView.as_view(),
        name = 'article-list'),


    url(r'^add-article/$',
        CreateArticleView.as_view(),
        name = 'create-article'),



    url(r'^(?P<slug>[-\w]+)/$',
        ArticleDetailView.as_view(),
        name = 'article-detail'),


    url(r'^(?P<slug>[/w-]+)/update/$',
        UpdateArticleView.as_view(),
        name = 'update-article'),


    url(r'^(?P<slug>[/w-]+)/delete/$',
        DeleteArticleView.as_view(),
        name = 'delete-article'),


    url(r'^(?P<slug>[-\w]+)/comment/$',
        CreateArticleComment.as_view(),
        name = 'add-article-comment'),


]

模板.html

{% extends 'articles/base.html' %}
{% load static %}
{% load cloudinary %}


{% block page_title %}{{ object.title | title }} | Dad Support{% endblock %}

{% block page_css %}
    <style>
        body {background: rgba(233, 235, 238, 1); color: 50,50,50,1);}
        .header {background: white; overflow: hidden; padding: 10px 0;}
        .navigation {text-align: center;}
        h1 {text-transform: uppercase; font-size: 1.25rem; font-weight: 900; font-family: "Cabin"; padding: 1rem 0.5rem 0.5rem;}
        a {color: rgba(0,0,51,1); font-weight: 900;}
        a:hover {color: rgba(0,0,51,0.8);}
        .fa {display: block;}

        .main {margin: 2rem 0; overflow:hidden;}

        .article-container {background: rgba(255,255,255,1); border-radius: 5px;}
        .article-container p {padding: 0rem 1rem;}
        .first-sidebar {height: 694px;}

        .trending-stories,
        .entrance-wrapper,
        .article-sidebarad {background: white; overflow:auto; border-radius: 5px;}

        .trending-stories,
        .entrance-wrapper, 
        .article-sidebarad {font-size: 0.9rem; padding: 1rem; text-align: center;}

        .entrance-wrapper span {display: block; margin-top: 0.375rem;}

        .spacer {margin: 10px 0;}

        .article-sidebarad img {width: 300px; height: 300px;}

        .trending-stories a {text-transform: capitalize;}

        .trending-stories {text-align: left;}

        .trending-stories-wrapper,
        .article-sidebarad-wrapper {margin: 0 10px;}

        .trending-stories h2,
        .article-sidebarad h2 {font-size: 0.8rem; font-weight: 900; text-transform: uppercase; text-align: left;}
        .trending-stories h3 {font-size: 0.9rem; margin: 0; padding: 0; font-weight: 600;}

    </style>
{% endblock %}

{% block page_content %}
    <div class="row">
        <div class="main">
            <div class="medium-11 small-centered">
                <div class="small-8 medium-8 large-8 columns">
                    <div class="article-container">
                        <h1>{{ article.title }}</h1>
                        {% cloudinary article.featured_image height="469" width="703" crop="scale" %}
                        <p class="text-body">{{ article.content |linebreaks}}</p>
                    </div>
                    <div class="comment-container">
                        <a class="btn btn-default" href="{% url 'articles:add-article-comment' slug=article.slug %}">Add comment</a>
                        {% for comment in article.comments.all %}
                            <div class="comment">
                                <div class="date">{{ comment.created }}</div>
                                <strong>{{ comment.author }}</strong>
                                <p>{{ comment.text|linebreaks }}</p>
                            </div>
                        {% empty %}
                            <p>No comments here yet :(</p>
                        {% endfor %}
                    </div>
                </div>
                <div class="small-4 medium-4 large-4 columns">
                    <div class="article-sidebar">
                        <div class="entrance-wrapper">
                            {% if not user.is_authenticated %}
                            <div class="row">
                                <div class="medium-3 columns">
                                    <p>
                                        <a href="{% url 'articles:create-article' %}">
                                            <i class="fa fa-pencil fa-2x" aria-hidden="true">
                                                <span>Publish</span>
                                            </i>
                                        </a>
                                    </p>
                                </div>
                                <div class="medium-3 columns">
                                    <p>
                                        <a href="{% url 'contact:contact-list' %}">
                                            <i class="fa fa-phone fa-2x" aria-hidden="true">
                                                <span>Contact</span>
                                            </i>
                                        </a>
                                    </p>
                                </div>
                                <div class="medium-3 columns">
                                    <p>
                                        <a href="{% url 'profiles:register' %}">
                                            <i class="fa fa-user-plus fa-2x" aria-hidden="true">
                                                <span>Register</span>
                                            </i>
                                        </a>
                                    </p>
                                </div>
                                <div class="medium-3 columns">
                                    <p>
                                        <a href="{% url 'profiles:login' %}">
                                            <i class="fa fa-sign-in fa-2x" aria-hidden="true">
                                                <span>Sign In</span>
                                            </i>
                                        </a>
                                    </p>
                                </div>
                                {% endif %}
                                {% if user.is_authenticated %}
                                    <div class="row">
                                        <div class="medium-3 columns">
                                            <p>
                                                <a href="{% url 'articles:create-article' %}">
                                                    <i class="fa fa-pencil" aria-hidden="true">
                                                        <span>Publish</span>
                                                    </i>
                                                </a>
                                            </p>
                                        </div>
                                        <div class="medium-3 columns">
                                            <p>
                                                <a href="{% url 'contact:contact-list' %}">
                                                    <i class="fa fa-phone" aria-hidden="true">
                                                        <span>Contact</span>
                                                    </i>
                                                </a>
                                            </p>
                                        </div>
                                        <div class="medium-3 columns">
                                            <p>
                                                <a href="{% url 'profiles:profile-detail' user.username %}">
                                                    <i class="fa fa-user-circle" aria-hidden="true">
                                                        <span>Profile</span>
                                                    </i>
                                                </a>
                                            </p>
                                        </div>
                                        <div class="medium-3 columns">
                                            <p>
                                                <a href="{% url 'profiles:logout' %}">
                                                    <i class="fa fa-sign-out" aria-hidden="true">
                                                        <span>Sign Out</span>
                                                    </i>
                                                </a>
                                            </p>
                                        </div>
                                    </div>
                                    <p>Welcome {{ user.username }} !!!</p>       
                                {% endif %}
                            </div>                          
                        </div>
                        <div class="spacer"></div>
                        <div class="article-sidebarad">
                            <h2>sponsored</h2>
                            <img src="file:///home/absinthe62/Downloads/milkyway.jpg" height="280" width="336">
                        </div>
                        <div class="spacer"></div>
                        <div class="trending-stories">
                            <div class="row">
                                <div class="medium-12">
                                    <div class="trending-stories-wrapper">
                                        <h2>Article Vault</h2>
                                        {% for article in sidebar_articles %}
                                            <h3>
                                                <a href="{% url 'articles:article-detail' article.slug %}">{{ article.title }}</a>
                                            </h3>
                                            <p class="sidebar-body">{{ article.body| truncatewords:13 }}</p>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

最佳答案

我想这就是你想要的

class CreateArticleComment(CreateView):
    model = ArticleComment 
    fields = ('text',)

    def post_valid(self, form):
        article = get_object_or_404(Article, 
                                    slug=article.slug) # Replaced 'Post' with 'Article'
        articlecomment = form.save(commit=False)
        articlecomment.author = self.request.user
        articlecomment.article = article
        articlecomment.save()
        return redirect('articles:article-detail', slug=article.slug)

    def get_success_url(self):
        return reverse_lazy('articles:article-list')

关于python - 向文章 django createviewforeignkey 添加评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45048125/

相关文章:

python - 如何沿数组维度映射克罗内克乘积?

python - 将包含元组的列表转换为字符串

c# - 在 C# 中,连续 3 个 '/' 是做什么的?

python - 如何保存从 Python Selenium ChromeDriver 在 Chrome 中打开的嵌入式 PDF

python - 在 Django 中将 Postgres 与 Oscar 同步时出现编程错误

Django 与 Graphite 烯 : How to handle bidirectional relationship with polmorphic models?

jquery - Django 延迟加载分页

android-studio - Android Studio 中可用的所有评论标签是什么?

Android 示例评论 BEGIN_INCLUDE END_INCLUDE

python - ValueError : the bucket does not exist,或被禁止访问'调用CreateMultipartUpload时发生错误(AccessDenied)