当我访问我的页面时出现此错误:
渲染时捕获到AttributeError:' WSGIRequest'对象没有属性' get'
错误开始在线" 17"我的html,这是输出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']
而故事模型是一个普通模型,可能不是问题的一部分,但是,嘿,我是一个切割和粘贴,所以这里去了!
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)
我认为我可以通过&#34; request.POST&#34;或者没有,是吗?
答案 0 :(得分:1)
可能你是对的,你正在将request
而不是request.POST
,reqest.GET
或request.REQUEST
传递给表单的构造函数。请参阅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,
})
答案 1 :(得分:1)
我可以看到两个问题。很简单,你可以简单地替换这一行:
context['form'] = createNewStoryForm(self.request)
与
context['form'] = StoryForm(request.POST, request.FILES)
最后不应该这样:
class StoryShowView(ListView):
model = StoryForm
是:
class StoryShowView(ListView):
model = Story