Django表单文本字段不显示

时间:2019-06-16 13:01:10

标签: python html django

我已经使用django的模型和表单在博客应用程序中添加了注释部分,但是当在浏览器中加载表单时,表单的文本字段将不会显示。只有提交按钮加载,没有文本字段可供提交。

models.py

from django.db import models
from datetime import datetime
from django import forms

class Post(models.Model):
    title = models.CharField(max_length=140)
    body = models.TextField()
    date = models.DateTimeField("date published", default=datetime.now())

    def _str_(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=100)
    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:
        models = Comment
        exclude = ['post']

form = CommentForm

post.html

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

        <form method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <br>
            <button class="btn" style="background-color:lightblue" type="submit">Submit Comment</button>
        </form>
    </div>
</div>

views.py

from django.shortcuts import render
from django.views import generic
from .forms import CommentForm
from .models import Comment

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})
    form = CommentForm(request.POST)

form = CommentForm()

在django的管理员中,我可以添加新评论,并且表单可以按预期加载,但不适用于博客文章本身。管理员通过管理面板提交的评论也可以保存并显示正常。

1 个答案:

答案 0 :(得分:1)

您在 forms.py

中有错字

models更改为model

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 # changed from models
       exclude = ['post']

views.py

您缺少进口商品

from django.shortcuts import get_object_or_404,redirect
from .models import Post

其他变化
在您的 models.py
中 类的 to字符串方法是__str__而不是_str_

通过此更改,我能够使用您的片段(用于发布评论)重现this django project