0
我已經創建了組合ListView和FormView。如果我調用窗體有效的方法一切正常,但如果窗體無效,我嘗試初始化form_invalid方法,並重定向到MainView顯示窗體錯誤,我得到錯誤。在Django結合視圖中顯示錶單錯誤
views.py
class MainView(ListView, FormMixin):
"""
Main which display all posts
"""
# Setting template name
template_name = 'post/main.html'
# Setting view model
model = Post
# Setting pagination
paginate_by = 5
# Setting form class
form_class = PostForm
# Overriding get_context_data method
def get_context_data(self, **kwargs):
context = super(MainView, self).get_context_data(**kwargs)
context['form'] = self.form_class()
context['trends'] = Tag.objects.all().order_by('posts')
return context
# Handling post sending
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
self.form_valid(form)
return redirect('main')
else:
self.form_invalid(form)
return redirect('main')
def form_valid(self, form):
# Getting body text from form
text = form.cleaned_data['body']
# Getting actual logged in user
author = self.request.user
# Getting image file
image_file = form.cleaned_data['image_file']
# Getting image_url
image_url = form.cleaned_data['image_url']
# Creating post instance and saving
post = Post(text=text, author=author, image_file=image_file, image_url=image_url)
post.save()
錯誤
AttributeError at /main/
'MainView' object has no attribute 'object_list'
交/ main.html中
<!--Post column-->
<section class="col-sm-7">
<!--Iterating through posts-->
{% for post in object_list %}
{{ post.text}}
{% endfor %}
</section>
交換父母的名字有幫助嗎? '類MainView(FormMixin,ListView):'。 –
好像你正在嘗試從你的視圖中訪問'object_list'屬性,而不是使用它作爲模板變量。你可以顯示模板「'post/main.html'」..? – mariodev
@mariodev好的,我添加了它。 –