我已经创建了ListView和FormView的组合。如果我调用表格有效的方法一切正常,但如果表格无效,我尝试初始化form_invalid方法并重定向到MainView以显示表单错误,我得到错误。
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>
答案 0 :(得分:1)
问题是ListView
和FormMixin
不能在一起开箱即用,所以你需要稍微改变一下你的观点。试试这个示例基本视图:
class CreateListView(CreateView, ListView):
def form_invalid(self, request, *args, **kwargs):
return self.get(self, request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = CreateView.get_context_data(self, **kwargs)
context.update(
super(FormListView, self).get_context_data(**kwargs)
)
return context
class MainView(CreateListView):
template_name = 'post/main.html'
model = Post
paginate_by = 5
form_class = PostForm
success_url = reverse_lazy('this-view-name')
def get_context_data(self, **kwargs):
context = super(MainView, self).get_context_data(**kwargs)
context['trends'] = Tag.objects.all().order_by('posts')
return context