0

New in Django. I'm trying to show form, but have instead it:
messag.views.CommentAdd object at 0x037860D0

forms.py:

from django.http import JsonResponse


class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return JsonResponse(data)
        else:
            return response

views.py:

class CommentAdd(AjaxableResponseMixin, CreateView):
    model = Comment
    fields = ['author_name', 'text', 'root']


class ShowTree(ListView):
    model = Comment
    template_name = 'comment_tree.html'

    def get_context_data(self, **kwargs):
        context = super(ShowTree, self).get_context_data(**kwargs)
        context['comment_form'] = CommentAdd()
        return context
1
  • When I use simply class CommentAdd in urls.py url(r'^add/$', CommentAdd.as_view(), name='add'), - all works correctly Commented Jun 30, 2015 at 22:21

1 Answer 1

1

It doesn't work because you need to pass an form instance and you are passing a class based view. CreateView is a class based view, not a ModelForm.

It could be easier to create a CreateView like in the example and get the data to build the list in get_context_data()

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer! But I can't understand how to pass form instance in my ShowTree.get_context_data function
If you make a CreateView you won't need to pass the form instance in the get_context_data function.
The Django example doesn't use get_context_data to pass the form instance, I suggest that you use get_context_data to get the queryset of Comments to create the list
Yes, and I need comments and form in one page. How to add this form CommentAdd(AjaxableResponseMixin, CreateView) to one page with comments, may be with templatetag?
With templatetag I have the same <messag.templatetags.forma.CommentAdd object at 0x036D5390> :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.