Django表单文本输入字段未在浏览器中显示

时间:2019-07-16 11:36:20

标签: python html django

我在博客文章下有一个Django模型和一个用于提交评论的表单。但是,该表单未显示在我的浏览器中,并且我认为未加载。我是编码的新手,很长一段时间都在寻找解决方案,但无济于事。

models.py

from django.db import models
from datetime import datetime
from django import forms
from django.contrib.auth.models import User
from django.conf import settings

class Comment(models.Model):
    post = models.ForeignKey('blog.post', on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    text = models.TextField(max_length=200)
    created_date = models.DateTimeField(default=datetime.now())

    def __str__ (self):
        return self.text

forms.py

from django import forms
from django.forms import ModelForm
from .models import Comment
from django.db import models

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['post' 'author']
        fields = ['text']

views.py

from django.shortcuts import render,get_object_or_404,redirect
from django.views import generic
from .forms import CommentForm
from .models import Comment, Post


def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('/blog/<int:pk>', pk=post.pk)
    else:
        form = CommentForm()
        return render(request, 'blog/post.html', {"form":form, "post": post})

urls.py

from django.urls import path, include, re_path
from django.views.generic import ListView, DetailView
from .models import Post
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
                path('', ListView.as_view(
                    queryset=Post.objects.all().order_by("-date")[:25],
                    template_name="blog/blog.html")),
                re_path("(?P<pk>\d+)", DetailView.as_view(model = Post,
                    template_name = "blog/post.html")),
                re_path('blog/<int:pk>', views.add_comment_to_post, name='post_comment'),
]

post.html

<div class="container">
    <h5>New comment</h5>

    <form method="POST" action="{% url 'post_comment' post.pk %}">
        {% csrf_token %}
        {{ form.as_p }}
        <br>
        <button type="submit" class="save btn btn-default">Post Comment</button>
    </form>

    {% for comment in post.comments.all %}
        <div class="card" style="margin: 20px 0px 20px 5px">
            <div class="date">{{ comment.created_date }}</div>
            <strong>{{ comment.author|capfirst }}</strong>
            <p>{{ comment.text|linebreaks }}</p>
        </div>
    {% empty %}
        <p>No comments yet. Be the the first to reply</p>
    {% endfor %}

</div>

我可以通过管理面板汇总评论,因此我相信实际模型可以正常工作。我认为问题很可能出在我的urls.py中,因为该模型正在运行,而这是我目前最不了解的文件。

很抱歉也发布了太多代码,但是我对编码太陌生了,无法再将它缩小到适合您的好伙伴。

1 个答案:

答案 0 :(得分:0)

您应该在表单中明确说出您想要的字段。您可以在docs

中阅读更多详细信息

forms.py

from django import forms
from .models import Comment


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['post', 'author']
        fields = ['text', ....]

views.py

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('/blog/<int:pk>', pk=post.pk)
    else:
        form = CommentForm()
        return render(request, 'blog/post.html', {"form":form, "post": post})

urls.py

from django.urls import path, include, re_path
from django.views.generic import ListView, DetailView
from .models import Post
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html")),
    re_path("(?P<pk>\d+)", DetailView.as_view(model=Post, template_name="blog/post.html")),
    # you were using re_path here instead of path
    path('blog/<int:pk>', views.add_comment_to_post, name='post_comment'),
]

post.html

<div class="container">
    <h5>New comment</h5>

    <form method="POST" action="{% url 'post_comment' post.pk %}">
        {% csrf_token %}
        {{ form.as_p }}
        <br>
        <button type="submit" class="save btn btn-default">Post Comment</button>
    </form>

    {% for comment in post.comments.all %}
        <div class="card" style="margin: 20px 0px 20px 5px">
            <div class="date">{{ comment.created_date }}</div>
            <strong>{{ comment.author|capfirst }}</strong>
            <p>{{ comment.text|linebreaks }}</p>
        </div>
    {% empty %}
        <p>No comments yet. Be the the first to reply</p>
    {% endfor %}

</div>

此外,您无需在表单中调用CommentForm,因为您将其导入了views.py。另一件事是,views.py的最后一行将永远不会执行,因为您已经在if / else条件内返回了。不过,您绝对不需要。