1

当我访问我的页面时出现此错误:

渲染时捕获 AttributeError:“WSGIRequest”对象没有属性“get”

错误出现在我的 html 的“17”行,这是输出 form.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 上下文中。因为,嗯,这就是我的意思,riiiiiiiiight?

#for showing of the stories!
class StoryShowView(ListView):
    model = StoryForm

    def get_queryset(self):
        return getStoryItemsForUser(self.request)

    def get_context_data(self, **kwargs):
        context = super(StoryShowView,self).get_context_data(**kwargs)
        context['form'] = createNewStoryForm(self.request)
        return context

好吧,createNewStoryForm 方法就是这样做的:

def createNewStoryForm(request):
    return StoryForm(request)

StoryForm 就是这样:

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

Story 模型是一个普通模型,这可能不是问题的一部分,但是,嘿,我是一个剪切和粘贴,所以来了!

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)

我认为我可以传入“request.POST”或什么都不传入,是这样吗?

4

2 回答 2

1

我可以看到两个问题。最简单的是您可以简单地替换这一行:

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

context['form'] = StoryForm(request.POST, request.FILES)

最后不应该这样:

class StoryShowView(ListView):
    model = StoryForm

是:

class StoryShowView(ListView):
    model = Story
于 2012-05-21T12:06:04.297 回答
1

可能你是对的,你传递request而不是request.POSTreqest.GET或者传递request.REQUEST给你的表单的构造函数。请参阅有关如何使用表单的文档:

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,
    })
于 2012-05-21T07:50:10.090 回答