Handling form from different view and passing form validation through session in django

Posted by Mo J. Mughrabi on Stack Overflow See other posts from Stack Overflow or by Mo J. Mughrabi
Published on 2012-12-08T11:15:44Z Indexed on 2012/12/10 5:04 UTC
Read the original article Hit count: 260

Filed under:

I have a requirement here to build a comment-like app in my django project, the app has a view to receive a submitted form process it and return the errors to where ever it came from. I finally managed to get it to work, but I have doubt for the way am using it might be wrong since am passing the entire validated form in the session.

below is the code

comment/templatetags/comment.py

@register.inclusion_tag('comment/form.html', takes_context=True)
def comment_form(context, model, object_id, next):
    """
    comment_form()
        is responsible for rendering the comment form
    """
    # clear sessions from variable incase it was found

    content_type = ContentType.objects.get_for_model(model)

    try:
        request = context['request']
        if request.session.get('comment_form', False):
            form = CommentForm(request.session['comment_form'])


            form.fields['content_type'].initial = 15
            form.fields['object_id'].initial = 2
            form.fields['next'].initial = next
        else:
            form = CommentForm(initial={
                'content_type'  : content_type.id,
                'object_id'     : object_id,
                'next'          : next
            })

    except Exception as e:
        logging.error(str(e))
        form = None

    return {
        'form' : form
    }

comment/view.py

def save_comment(request):
    """
    save_comment:

    """

    if request.method == 'POST':

        # clear sessions from variable incase it was found
        if request.session.get('comment_form', False):
            del request.session['comment_form']


        form = CommentForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            if request.user.is_authenticated():
                obj.created_by = request.user
            obj.save()
            messages.info(request, _('Your comment has been posted.'))
            return redirect(form.data.get('next'))
        else:

            request.session['comment_form'] = request.POST
            return redirect(form.data.get('next'))

    else:
        raise Http404

the usage is by loading the template tag and firing

{% comment_form article article.id article.get_absolute_url %}

my doubt is if am doing the correct approach or not by passing the validated form to the session. Would that be a problem? security risk? performance issues?

Please advise

Update

In response to Pol question. The reason why I went with this approach is because comment form is handled in a separate app. In my scenario, I render objects such as article and all I do is invoke the templatetag to render the form. What would be an alternative approach for my case?

You also shared with me the django comment app, which am aware of but the client am working with requires a lot of complex work to be done in the comment app thats why am working on a new one.

© Stack Overflow or respective owner

Related posts about django