Django:模板中的Modelform自动创建表单

时间:2023-02-11 09:28:52

I've only been at python for about 2 weeks now and I've run into an issue which I've been trying to figure out for the past 3 days. I've read through the official documentation and pretty much every tutorial and youtube video available.

到目前为止,我只在python工作了大约两周,我遇到了一个问题,在过去的三天里,我一直在试图解决这个问题。我已经通读了官方文档和几乎所有的教程和youtube视频。

I'm trying to build a simple blog as a first project and would like to have a section where people can post comments. I have set up the comments model and a modelform to go along with it. However, I can't figure out how to get django to create the form for me in the template, nothing is displayed.

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

models.py

models.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

views.py

views.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)

Urls.py

urls . 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

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 %}

I do get a 403 error CSRF verification failed but, the more pressing issue I think is that the {{ form }} doesn't do anything in the template.

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

I believe home function and get_post function are working and all the urls are working properly. So, I assume there's something wrong with the add_comment function or in posts.html.

我相信home函数和get_post函数都可以工作,所有的url都可以正常工作。我假设add_comment函数或post .html有问题。

Thanks

谢谢

2 个解决方案

#1


1  

Django isn't magic. Your comment form is in a completely different view from the one that displays the blog post. So how is Django supposed to know to render it? You need to actually pass the form object to the template somehow.

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

The way that this was done in the old contrib.comments app was to have a simple template tag which was responsible for just displaying the comment form for an object, which you could place on any template. The form itself submitted to its own view as usual.

在旧的懊悔。comments应用程序中实现这一点的方法是有一个简单的模板标记,它只负责显示对象的注释表单,您可以将其放置在任何模板上。表单本身像往常一样提交给自己的视图。

#2


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.

您可以检查render_to_response调用的语法。我相信你们会这样定义它。(也许您的语法也可以,但这不是问题所在,但我看到的大多数调用都是这样的)。这可能是上下文中缺少表单的原因。

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

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

#1


1  

Django isn't magic. Your comment form is in a completely different view from the one that displays the blog post. So how is Django supposed to know to render it? You need to actually pass the form object to the template somehow.

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

The way that this was done in the old contrib.comments app was to have a simple template tag which was responsible for just displaying the comment form for an object, which you could place on any template. The form itself submitted to its own view as usual.

在旧的懊悔。comments应用程序中实现这一点的方法是有一个简单的模板标记,它只负责显示对象的注释表单,您可以将其放置在任何模板上。表单本身像往常一样提交给自己的视图。

#2


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.

您可以检查render_to_response调用的语法。我相信你们会这样定义它。(也许您的语法也可以,但这不是问题所在,但我看到的大多数调用都是这样的)。这可能是上下文中缺少表单的原因。

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

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