0
votes

I'm Building an application where the auth process has three fields.

  1. subdomain
  2. username
  3. password

Each subdomain defines an isolated space and the username is unique only inside its subdomain

For example:

  • the subdomain foo.bar.com has the user jhon_doe with the password secret. It may exists another jhon_doe but in other subdomain.

So ... I've created a custom backend authentication and it works well. The problem is that the login Django Admin form have username and password fields by default.

I would like to implement a custom Django Admin login form with subdomain username and password fields.

1

1 Answers

1
votes

I had a similar requirement and I did that in the following way. See if it can help you or not.

First I extended my existing user model and added email and phone in models.py.

from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
   email = models.EmailField(verbose_name='email',
                          max_length=255, unique=True)
   phone = models.CharField(null=True, max_length=255)
   REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
   USERNAME_FIELD = 'email'

   def get_username(self):
       return self.email

I have created an authapp and added this following lines in form.py which I create in authapp folder.

from django.views.generic import CreateView
from django.forms import CharField,  ModelForm
from django.utils.translation import gettext_lazy as _
from authapp.models import User

class LoginForm(ModelForm):
class Meta:
    model = User
    fields = ('email', 'phone', 'password')

Finally in my .html file in template I added this code. Form name in request payload was login_form.

<form method="POST" action="/login/">
    <div class="modal-body">{% csrf_token %} {{ login_form|crispy}}</div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">
        Close
      </button>
      <button type="submit" class="btn btn-primary">Login</button>
    </div>
  </form>

and the result of my login form was

enter image description here

I would like to clearify here that if you want to change existing login screen which is Django's default so you have to search arround but in my suggestion you should implement you your own custome way.

Thank you and happy coding...