表单对象没有属性'has_header'

时间:2013-07-10 15:17:13

标签: django comments

我是django的新手。我有一个带有视图的新闻应用程序,它为每个新闻呈现一个页面:

def news_page(request, news_id):
    news = News.objects.get(pk=news_id)
    tags = news.tags.all()
    category = news.category
    comments = news.comment_set.all()
    form = add_comment(request, news.id)
    return render(request, 'news/news_page.html', {'form': form, 'news': news, 'tags': tags, 'category': category, 'user': request.user, 'comments': comments})

我已经创建了评论应用: models.py:

class Comment(models.Model):
    author = models.ForeignKey(User)
    comment_body = models.CharField(max_length=500)
    news = models.ForeignKey(News)
        pub_date = models.DateTineField(default = datetime.datetime.now())

forms.py:

class AddCommentForm(ModelForm):
    comment_body = forms.CharField(widget=forms.Textarea)

    class Meta():
        model = Comment
        exclude = ('author', 'news','pub_date',)

我试着实现comments.view function add_comment news_page view(上面)使用:

def add_comment(request, news_id):
    news = News.objects.get(pk=news_id)
    if request.method == 'POST':
        form = AddCommentForm(request.POST)
        if form.is_valid:
            comment = form.save(commit=False)
            comment.author = request.user
            comment.news = news
            comment.save()
    else:
        form = AddCommentForm()
    return form

但我有错误'AddCommentForm'对象没有属性'has_header'。我认为这是因为add_comment视图没有HttpResponse。我应该如何重写代码以使这个想法变得有效。  错误追溯

Internal Server Error: /news/15/comment/
Traceback (most recent call last):
  File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\core\handlers\base.py"
, line 187, in get_response
    response = middleware_method(request, response)
  File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\contrib\sessions\middl
eware.py", line 26, in process_response
    patch_vary_headers(response, ('Cookie',))
  File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\utils\cache.py", line
142, in patch_vary_headers
    if response.has_header('Vary'):
AttributeError: 'AddCommentForm' object has no attribute 'has_header'

感谢的!

2 个答案:

答案 0 :(得分:8)

从视图中你需要返回一个response对象,但是你要返回表单对象。因此错误。

您可以使用render代替

更改

return form

return render(request, template_name, {'form': form})

答案 1 :(得分:0)

karthikr是对的

您也可以使用

return render_to_response('template_name',{'form':form})