form object has no attribute 'has_header'
18,866
From a view you need to return a response
object , but you are returning the form object. Hence the error.
You can use render
instead
Change
return form
to
return render(request, template_name, {'form': form})
Author by
Leval
Updated on June 05, 2022Comments
-
Leval almost 2 years
I'm new to django. I have news app with view, which renders a page for each news:
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})
And I've created comment app: 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',)
I'l try realize comments.view function add_comment which news_page view (above) use:
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
But I've got error 'AddCommentForm' object has no attribute 'has_header' . I think that's happen because add_comment view don't have HttpResponse. How should I rewrite code so that the idea become working. Error traceback
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'
Thank's!