Manuel Santi
Manuel Santi

Reputation: 1132

Django manage different forms in a same page in view.py

In my project i have to manage 3 different forms in my login html file, one for classic login, one for user registration and one for company registration (all in a single login.html file) I create in my forms.py three different Modelforms class for manage the different models but now i have just an url and in my views.py i dont know how to say for witch form the data come from and how make the binding and the elaboration:

def user_login(request, log_err=None):
    context = RequestContext(request)

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        return HttpResponseRedirect('/login/log_error')

    else:
        return render(request, 'login.html', {'l_err': log_err})

How can i discriminate the saving data into correct model if come from form1,2 or 3?

So many thanks in advance

Upvotes: 0

Views: 178

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

You can set a different name for each submit button and then check which one is clicked and then pass the data to the corresponding form:

<form method="POST">
    { fields ... }
    <button type="submit" name="company">Rgister Company</button>
</form>

<form method="POST">
    { fields ... }
    <button type="submit" name="register">Rgister</button>
</form>

<form method="POST">
    { fields ... }
    <button type="submit" name="login">Login</button>
</form>

And then check the data in view:

if request.method=='POST':
    if 'login' in request.POST:
        # Login form
    elif 'register' in request.POST:
        # Register form
    elif 'company' in request.POST:
        # Company registration form

Upvotes: 1

Related Questions