Tuesday, June 4, 2013

properly passing form post data to get_context_data() in detailview

Hi,

I'm trying to process a form through a detailview that adds a comment to a blog post. Here's my view code:

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog_detail.html'
    queryset = Post.objects.filter(published=True)
    form_class = CommentForm
      
    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        post = self.get_object()
        context['comments'] = Comment.objects.filter(published=True).filter(post_id=post.id)
        context['form'] = CommentForm
        return context
    
    def post(self, request, *args, **kwargs):
        post = self.get_object()
        form = CommentForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.post_id = post.id
            f.ip_address = self.get_client_ip(self.request)
            f.save()
            form.send_email()
            messages.add_message(self.request, messages.SUCCESS, 'Comment submitted. Thanks!')
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', None))
        else:
            # this fails with attribute error: 'PostDetailView' object has no attribute 'object'
            return self.render_to_response(self.get_context_data(form=form))
    
    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip


And here's the relevant form code:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        exclude = ('post', 'published')
        
    def send_email(self):
        text = self.cleaned_data['text']
        name = self.cleaned_data['name']
        send_mail(
            'comment submission',
            name + ' wrote:\n' + text,
            [from_email_address],
            ([to_email_address])
        )

Form processing appears to work as expected when the form fields are actually filled and the form is valid but fails with an "Attribute Error: 'PostDetailView' object has no attribute 'object'" when the fields are blank (i.e. form is not valid). As a relative newbie to python and django I'm at a complete loss as to what I'm doing wrong here. 

Thanks in advance for any pointers.

--
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate