views:

64

answers:

0

I'm rolling a custom comment app that can take any object and allow the user to post comments (much like the one that comes with django.contrib).

My first thought, since none of the form is specific to any particular view, was to put it in a template tag:

@register.inclusion_tag('comments/add.html', takes_context=True)
def add_comment(context, obj):
    request = context['request']
    if request.method == 'POST':
        form = CommentForm(request.POST)
        comment = form.save(commit=False)
        comment.poster = request.user
        comment.content_type = ContentType.objects.get_for_model(obj)
        comment.object_id = obj.pk
        if form.is_valid():
            comment.save()
    else:
        form = CommentForm()
    return locals()

This works great except for two things: 1) You can't redirect from a template tag 2) As many devs have pointed out to me today, template tags shouldn't be doing this kind of work

Most people have suggested using a view specifically for processing the form, but I can't figure out how that would work. The view would need variables from the original view for form defaults, it would need to know where the user came from to properly redisplay on errors and redirect on success. I want this to be clean, but I don't know how to set up a view in any way that's near as clean as the template tag.

How can I turn this template tag into a generic piece of code that could apply to many pages (even multiple times in a page, really)?