0

My "view" code has an obvious repetition in its code. Is there any way of refactoring the "return" code?

def form_contractor_view(request):
    if request.method == 'POST':
        form = ContractorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index_view')
        else:
            return render_to_response(
                'form_contractor.html',
                {'form': form},
                context_instance=RequestContext(request),
            )
    else:
        form = ContractorForm()
        return render_to_response(
           'form_contractor.html',
           {'form': form},
           context_instance=RequestContext(request),
        )
1
  • I would very much recommend you to consider class-based views. Commented Nov 8, 2015 at 9:43

2 Answers 2

2

There is no need for the first else at all. Move the final render back an indent, and that will catch the else case. Note that this is the pattern explicitly described in the documentation.

Also, use render instead of render_to_response.

def form_contractor_view(request):
    if request.method == 'POST':
        form = ContractorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index_view')
    else:
        form = ContractorForm()
    return render(
       request,
       'form_contractor.html',
       {'form': form},
    )
Sign up to request clarification or add additional context in comments.

2 Comments

When the form is not valid, Django keeps producing the error saying that HttpResponse object is none. Therefore, to circumvent that error, I included the first "else". With your suggestion, invalid forms will not be redirected. Is there any way around that?
No, that won't happen as long as you follow this pattern precisely: as I mentioned, the final return line must not be indented.
0

I will give my try:

def form_contractor_view(request):
    form = ContractorForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect(reverse('index_view')) # <-- you forgot reverse() here
    return render(
        request,
        'form_contractor.html',
        {'form': form}
    )

I replaced render_to_response with render which does the same thing - you just type less... try to be lazy ;)

I think, this works. not tested though. If request is not done in POST, then is_valid() returns False returning the form as None back again which makes sense. and for the case where the request is done in POST and invalid values in it, then else kicks in and returns the form with error messages... I think, this works.. please test

3 Comments

Re: 'you forgot reverse()' - you don't need to call reverse first when using the redirect shortcut, it will reverse the URL for you!
@Alasdair you mean redirect('index_view') will do the same thing?
@Alasdair you are right: github.com/django/django/blob/master/django/… thanks for the trick

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.