Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
q_sent = False
sent_failed = False

if request.method == 'POST':
    form = FaqForm(request.POST)
    if form.is_valid():
        form.save()
        q_sent = True  
    else:
        sent_failed = True   
else:
    form = FaqForm()

return render_to_response('faq_ask_question.html', RequestContext(request, {
                         'form' : form,
                         'q_sent' : q_sent,
                         'sent_failed' : sent_failed,
                         'request' : request, })) 
share|improve this question

3 Answers 3

form = FaqForm(request.POST or None)
context = {
    'q_sent': False, 
    'sent_failed': False, 
    'form' : form,
    'request' : request 
}

if form.is_valid():
    form.save()
    context['q_sent'] = True 
else:
    context['sent_failed'] = True
return render_to_response('faq_ask_question.html', RequestContext(request, context))

But anyway even my example is not good.

q_sent and sent_failed - they are not needed. You give form instance to the template. And at the template you should display validation errors. If data is correct you usually set success message by message framework and redirect user to some other page.

request in the context... you can just add 'django.core.context_processors.request' to context processors, if you really need request instance in your templates.

share|improve this answer
if request.method == 'POST':
    form = FaqForm(request.POST)
    if form.is_valid():
        form.save()  
else:
    form = FaqForm()

return render_to_response('faq_ask_question.html', RequestContext(request, {
                         'form' : form,
                         'q_sent' : not form.errors and form.is_bound,
                         'sent_failed' : form.errors,
                         'request' : request, })) 

Hope it's help you. Main idea - remove q_sent and sent_failed.

PS. code could contain an exception

share|improve this answer

Try to add 'is_sent' parameter to your form object (with default to False). And in save() method set it to True. So no need to pass 'q_sent' and 'sent_failed' variable in context, you can use form.is_sent. Which is much clearer and places this logic where it shuld be — in form itself.

Some more optimizations:

form = FaqForm(request.POST or None)
if form.is_valid():
    form.save()
return direct_to_template(request, 'faq_ask_question.html',
                          {'form' : form, 'request': request})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.