Friday, April 24, 2015

form_invalid redirection with CBVs

Following a form_invalid I need to redirect to the CreateComment view below with the errors shown in the form. Is this possible please? Highlighted is where I need help.

Thank you for any assistance.


class Comments(View):
def get(self, request, *args, **kwargs):
view = CreateComment.as_view()
return view(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
view = CommentCreate.as_view()
return view(request, *args, **kwargs)

class CreateComment(ListView):
model = Comment
paginate_by = 2

def get_queryset(self):
comments = Comment.objects.filter(
object_id=self.kwargs['pk'], content_type_id=self.kwargs['ct']
).order_by('-created')
return comments

def get_context_data(self, **kwargs):
context = super(CreateComment, self).get_context_data(**kwargs)
context['form'] = CommentForm()
return context

class CommentCreate(SingleObjectMixin, FormView):
template_name = 'comment/comment_list.html'
form_class = CommentForm
model = Comment

def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

def get_success_url(self):
return reverse('comment:Comments', kwargs={'ct': self.kwargs['ct'], 'pk': self.kwargs['pk']})

def form_valid(self, form):
data = form.save(commit=False)
data.creator = self.request.user
data.object_id = self.kwargs['pk']
data.content_type_id = self.kwargs['ct']
data.save()
return super(CommentCreate, self).form_valid(form)

def form_invalid(self, form):
return super (CommentCreate, self).form_invalid(form)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/74848a77-5af5-4947-a541-f3812a285d99%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment