Django~WSGIRequest,通过get_context_data方法添加表单

2024-10-04 05:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

当我访问我的页面时,我遇到了这个错误:

Caught AttributeError while rendering: 'WSGIRequest' object has no attribute 'get'

错误出现在我的html的第17行,也就是输出的行表格as\p在

html如下所示:

{% extends "base.htm" %}

{% block content %}
{% if story_list %}
    {% for story in story_list %}
        <div class="Story">
            <a href="#">{{  story.title }}</a>
        </div>
    {% endfor %}
{% else %}
    <p>No stories are present - enter one below</p>
{% endif %}
<h3>Create a new story</h3>
<form action="/addStory" method="post">
    {%  csrf_token %}
    {{  form.as_p }} ***THIS IS LINE 17***
    <input type="submit" value="Submit"/>
</form>
{% endblock %}

问题是我有一个视图做了两个事情,并且在django教程中重写了get_context_data方法,以便将第二个项目添加到django上下文中。因为,嗯,这就是我要做的,瑞光?在

^{pr2}$

其中,createNewStoryForm方法只执行以下操作:

def createNewStoryForm(request):
    return StoryForm(request)

故事形式是这样的:

class StoryForm(ModelForm):
    class Meta:
        model = Story
        ordering = ['create_date']

故事模型是一个普通的模型,这可能不是问题的一部分,但是,嘿,我是一个剪贴的人,所以就这样吧!在

class Story(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    title =  models.CharField(max_length=100)
    is_closed = models.BooleanField()
    is_random = models.BooleanField() # for uncategorised stories. Only one of these.
    result = models.CharField(max_length=20) #how did the relo work out?
    create_date = models.DateTimeField('date created')
    def __unicode__(self):
        return self.title

你知道我做错了什么吗?在

更新: 啊,是台词:

return StoryForm(request)

我想我可以通过一个“请求.POST“或者什么都没有,是吗?在


Tags: formgetdatereturntitlemodelsrequesthtml
2条回答

我能看到两个问题。最简单的方法是,您可以简单地替换这行代码:

context['form'] = createNewStoryForm(self.request)

^{pr2}$

最后不应该这样:

class StoryShowView(ListView):
    model = StoryForm

比利时:

class StoryShowView(ListView):
    model = Story

可能您是对的,您将request而不是request.POSTreqest.GET或{}传递给表单的构造函数。参见how to use forms上的文档:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

相关问题 更多 >