简体   繁体   中英

How can I make two different login forms in Django?

How can I log in and redirect to his "Dashboard" and a login form for the admin site and redirect to his "Admin Panel"

I have been looking for and read that it can be done by creating a ModelBackend and found this as a reference but it does not make me clear how to do it. https://docs.djangoproject.com/en/1.8/topics/auth/customizing/

As I understand you need two login views. In your app views.py create 2 views, for example:

def loginDashboard(request):
  if request.user.is_authenticated():
    return HttpResponseRedirect('/')
  if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
      username = form.cleaned_data['username']
      password = form.cleaned_data['password']
      account = authenticate(username=username, password=password)
      if account is not None:
        login(request, account)
#here is redirecting to dashboard
          return HttpResponseRedirect('/dashboard/')
      else:
        return render(request, 'profiles/login.html', context)
    else:
      return render(request, 'profiles/login.html', context)
  else:
    form = LoginForm()
    context = {'form':form}
    return render(request, 'profiles/login.html', context)

def loginAdminPanel(request):
  if request.user.is_authenticated():
    return HttpResponseRedirect('/')
  if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
      username = form.cleaned_data['username']
      password = form.cleaned_data['password']
      account = authenticate(username=username, password=password)
      if account is not None:
        login(request, account)
#here is redirecting to admin panel
          return HttpResponseRedirect('/adminpanel/')
      else:
        return render(request, 'profiles/login.html', context)
    else:
      return render(request, 'profiles/login.html', context)
  else:
    form = LoginForm()
    context = {'form':form}
    return render(request, 'profiles/login.html', context)

And your urls.py:

url(r'^login-dash/$', views.loginDashboard),
url(r'^login-admin/$', views.loginAdminPanel),

In this case you have two login pages ( example.com/login-dash and example.com/login-admin )

your forms.py:

class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'))
password = forms.CharField(label=(u'Pasword'), widget=forms.PasswordInput(render_value=False))

Hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM