2

我在 python 上只待了大约 2 周,我遇到了一个问题,过去 3 天我一直在试图解决这个问题。我已经阅读了官方文档以及几乎所有可用的教程和 youtube 视频。

我正在尝试构建一个简单的博客作为第一个项目,并希望有一个人们可以发表评论的部分。我已经建立了评论模型和一个模型表单来配合它。但是,我不知道如何让 django 在模板中为我创建表单,没有显示任何内容。

模型.py

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

    class posts(models.Model):
        author = models.CharField(max_length = 30)
        title = models.CharField(max_length = 100)
        bodytext = models.TextField()
        timestamp = models.DateTimeField(auto_now_add=True)

        def __unicode__(self):
            return self.title

    class comment(models.Model):
        timestamp = models.DateTimeField(auto_now_add=True)
        author = models.CharField(max_length = 30)
        body = models.TextField()
        post_id = models.ForeignKey('posts')

        def __unicode__(self):
            return self.body

    class commentform(ModelForm):
        class Meta:
            model = comment

视图.py

from django.shortcuts import render_to_response
from blog.models import posts, comment, commentform
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf


def home(request):
    entries = posts.objects.all()
    return render_to_response('index.html', {'posts' : entries})

def get_post(request, post_id):
    post = posts.objects.get(id = post_id)
    context = {'post': post}
    return render_to_response('post.html', context)

def add_comment(request, post_id):
    if request.method == 'POST':
        form = commentform(request.POST)
        if form.is_valid():
            new_comment = form.save(commit = false)
            new_comment.post_id = post_id
            new_comment.save()
    else:
        form = commentform()

    context = RequestContext(request, {
        'form': form})

    return render_to_response('post.html', context)

网址.py

    from django.conf.urls import patterns, include, url
    from django.conf import settings
    from django.contrib import admin
    admin.autodiscover()

    urlpatterns = patterns('',
        url(r'^$', 'blog.views.home', name='home'),
        url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
        url(r'^admin/', include(admin.site.urls)),
        url(r'^(?P<post_id>.*)/$', 'blog.views.get_post'),
        url(r'^post_comment/(\d+)/$','blog.view.add_comment'),

post.html

{% extends 'base.html' %}

{% block content %}
    <p><h3> {{ post }} </h3></p>
    <p> {{ post.bodytext }} </p>

<br><br><br><br>

<form action="/post_comment/{{ post.id }}/" method="POST"> {% csrf_token %}
    {{ form }}
    <input type="submit" value="Post">
</form>

{% endblock %}

我确实收到 403 错误 CSRF 验证失败,但我认为更紧迫的问题是 {{ form }} 在模板中没有做任何事情。

我相信 home 函数和 get_post 函数正在工作,并且所有 url 都正常工作。所以,我认为 add_comment 函数或 posts.html 中有问题。

谢谢

4

2 回答 2

1

Django 不是魔法。您的评论表单与显示博客文章的表单完全不同。那么 Django 应该如何知道渲染它呢?您需要以某种方式实际将表单对象传递给模板。

在旧的 contrib.comments 应用程序中执行此操作的方式是使用一个简单的模板标签,该标签仅负责显示对象的评论表单,您可以将其放置在任何模板上。表单本身像往常一样提交给它自己的视图。

于 2013-06-12T07:46:53.017 回答
0

One thing you might check is the syntax of the render_to_response call. I believe you'll want to define it like this. (Maybe your syntax will work too, and this isn't the issue, but I have mostly seen the call made like this). This could be the cause of the missing form in the context.

return render_to_response('post.html',
                      {'form': form},
                      context_instance=RequestContext(request))

Let me know if this works. Hope this helps, Joe

Reference: https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#django.shortcuts.render_to_response

于 2013-06-12T03:32:33.420 回答