[Answer]-Django forms "pattern" for this situation?

1👍

✅

You can do something like this:

Create a dictionary of the forms,

FORMS = {
    0: CreateWomanProfileForm,
    1: CreateManProfileForm
}

And in the views:

def create_profile(request, template):
    is_man = 1 if request.session.get('user_type_cd') == 'man' else 0

    if request.method == "POST":
        form = FORMS.get(is_man)(request.POST)
        if form.is_valid():
            # Do stuff
            return HttpResponseRedirect(reverse('do-next-thing'))
    else:
        form = FORMS.get(is_man)()

    return render_to_response(template, locals(), context_instance=RequestContext(request))

Or even this should work

def create_profile(request, template):
    is_man = 1 if request.session['user_type_cd'] == 'man' else 0

    form = FORMS.get(is_man)(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            # Do stuff
            return HttpResponseRedirect(reverse('do-next-thing'))

    return render_to_response(template, locals(), context_instance=RequestContext(request))
👤karthikr

Leave a comment