【问题标题】:I don't work comments and forms are not displayed我不工作评论和表格不显示
【发布时间】:2019-11-10 15:28:27
【问题描述】:

我正在尝试在网站上制作 cmets,但是当我启动服务器时,我看不到表单。我创建了一个简单的博客,人们可以在其中发表喜欢和评论,但问题是当我添加评论表单时,它们根本不会出现。

附言

请原谅我的英语,我来自另一个国家,我不太懂英语

post.html 主模板

{% extends "ShapeHtml/wrapper.html" %}


{% block content %}

    <div class="panel panel-default">
      <div class="panel-heading">
        <h1 class=" text-info">{{object.title}}</h1>
      </div>
      <div class="panel-body">
        <p> {{object.post|safe|linebreaks}}  </p>
        <h3 align="right" class=" text-info"> Опубликованно: {{articles.date|date:"d-m-Y в H:i"}}</h3>
    </div>

        <h4>Comments</h4>


    <form action="{% url '' %}" method="post">
      {% csrf_token %}

      {% if CommentModel %}
        {% for CommentModel in comments %}
          {{ CommentModel.WhoAreYou }} <br>
        {% endfor %}
      {% endif %}

      {{ form }}
      <input type="submit" value="Submit">
    </form>

{% endblock %}

views.py

from .forms import CommentForm



class ArticlesList(ListView):
    model = Articles
    template_name = 'news/posts.html'



class ArticleDetail(DetailView):
    model = Articles
    template_name = 'news/post.html'





def GetComments(request):

    if request.method == 'POST':

        form = CommentForm(request.POST)

        if form.is_valid():
            form.save()

            return HttpResponseRedirect(request.path_info)

    else:

        form = CommentForm()

        comments = CommentModel.objects.all()

    return render(request, 'news/post.html', {'form': form, 'comments': comments})

urls.py

urlpatterns=[
    path('', ArticlesList.as_view(), name='articles_list'),
    path('<int:pk>/', ArticleDetail.as_view(), name='article_detail'),
    path('aboutUs', views.aboutUs, name='aboutUs'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py 是帖子和 cmets 的模型

from django.db import models

class Articles(models.Model):
    title = models.CharField(max_length= 200)
    post = models.TextField()
    date = models.DateTimeField()
    img = models.ImageField(upload_to='', default="default_value")

    def __str__(self):
        return self.title


class CommentModel(models.Model):
    WhoAreYou = models.CharField(max_length=100)

forms.py 字段表单

类 CommentForm(ModelForm):

class Meta:
    model = CommentModel
    fields = ('WhoAreYou',)

【问题讨论】:

    标签: python html django


    【解决方案1】:

    你在 forms.py 中写了class CommentForm(forms.ModelForm)

    class CommentForm(forms.ModelForm):
    
        comment = forms.CharField()
    
        class Meta:
          model = CommentModel
          fields = ('WhoAreYou',)

    我想它会起作用的。

    【讨论】:

    • 需要导入什么样的库?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2015-10-11
    相关资源
    最近更新 更多