Django Creating Custom User models - python

I am making a website through Django and I want to create a similar model for the Users model (default user model came with Django)
I have tried everything I have found from google django docs and I couldn't.
Can anyone help?
Or help me to make a login system for my normal model
For an instance,
I have created a normal model called accounts and there is a field in it called loggedin.
Whenever I try to login system set it to True means logged in. And if i logged out by the logout button i set it to false now lets take in consideration if i have closed the web browser Immediately i want to set it to False
Any help?

There are two common ways to deal with is extending django's AbstractUser:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# Some other fields to go along with the default fields
info = models.TextField(max_length=500, blank=True)
phone_number = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
After this, just change the default user model on your settings.py adding AUTH_USER_MODEL = my_app.models.user

Related

how to make models for user auth(use abstract user) for login and signup using django?

how to make models for user auth(use abstract user) for login and signup using Django?
I want to make login OTP based for ecommerse website.
from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
mobile = models.CharField(max_length=10)
address = models.CharField(max_length=200)
emailId = models.CharField(max_length=50)
password = models.CharField(max_length=200)
I tr above code.
What should I have to add above?
You should use AbstractUser if you want to inherit permissions settings and all functions that Django uses.
In settings, you should also add AUTH_USER_MODEL = "your_module_name.User"
In Django, making a user model by yourself is not recommended because other 3rd party packages depend on the user models Django provided.
There are two ways you can follow.
Extending the existing User model
Using a custom user model when starting a project

Can I change to a CustomUser model after the initial migration? Or I should've done it at the start of the project?

I'm trying to add custom user model mid project, and I might remember reading somewhere that you can't do that or that it isn't easy to do so, is that true? What can I do now?
The best way to proceed with this is to make another model which uses an OneToOneField to the user model. For example I am making this model to add fields like profile_pic, Your_website.
models.py
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
Your_website = models.URLField(blank = True)
profile_pic = models.ImageField(upload_to="profile_pics", blank = True)
def __str__(self):
return self.user.username
On your next migration it will ask you to provide a default for the user field so remember to do so.
By this method you can create a custom user model with the existing user model.

Django Auth User and Custom User

So far, I have been creating a user class in Django without inheriting AbstractBaseUser or AbstractUser classes. For example,
class User(models.Model):
realname = models.CharField(max_length=50)
username = models.CharField(max_length=50, unique=True)
birthday = models.DateField()
phone = models.CharField(max_length=50, unique=True)
password = models.CharField(max_length=2000)
...
Now I am thinking about creating a user model that actually inherits AbstractBaseUser class.
My question is, in what ways does inheriting AbstractBaseUser increase efficiency and productivity, if any?
I guess set_password() function may relieve the burden of manually encrypting input password with bcrypt; however, additional work is needed to create a UserManager class, refer to my custom User model with auth.get_user_model() function (django documentation says this way is recommended to return the currently active user model) instead of simply referring to it as 'User', and etc.
Your help will be greatly appreciated!!
Based on the documentation of User model in Django, the advantages of using AbstractUser to create your own user model are:
It comes with the integration with Group and Permission models which would help you build your authentication system and authorisation system in your apps.
The UserManager is quite powerful as it also provide util functions such as "set_password", "has_perm" and "is_authenticated" etc.
Based on the above, you can just inherit the AbstractUser to build your own User model, so you don't need to reinventing the wheel. It provides both flexibilities and functionalities. You could also customise lots of things in your own User model by overriding its own methods.
In your case, you could just use the following code and specify your AUTH_USER_MODEL = 'myapp.User' in your settings:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
realname = models.CharField(max_length=50)
birthday = models.DateField()
phone = models.CharField(max_length=50, unique=True)

In Django, is it possible for superusers to have different required fields than non-superusers?

I know that superusers and regular users are both just django's User objects, but how can I write a custom user class that requires some fields for plain users and doesn't require those fields for superusers?
No structure in the database is tricky. JSONFields for example may prove to be extremely hard to tame when the app grows.
I would go and try to make it "simple" - more maintainable (I imagine if you need to do stuff like that you may want to extend the model in the future). If this is a new project you can easily change the default user model. But that may or may not help you with your case.
You can always make two models:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class Mortal(AbstractBaseUser):
is_superuser = False
username = models.CharField(max_length=256)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
class Admin(AbstractBaseUser):
is_superuser = True
username = models.CharField(max_length=256)
and then make your own authentication backend:
class MyBackend(object):
"""
Danger! A backend to authenticate only via username
"""
def authenticate(self, username=None):
try:
return Mortal.objects.get(username=username)
except Mortal.DoesNotExist:
try:
return Admin.objects.get(username=username)
except Admin.DoesNotExist:
return None
You can have a profile class (say UserProfile) with foreign key to the user that is to be created only when user signs up using the website's registration form. That way, superuser which is created on admin site or through command line wouldn't need an extra profile instance attached to it.

Multiple User Types In Django

I am new to Django and trying to create an App with two User Types (Freelancers and Customers). I understand how to create a User profile Class and it works well for me:
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100, default='')
country = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
This works well for me on a one user type user. But now I am building an app with 2 types of users (freelancers and customers), what is the best approach to get this done. Both users will have different view and info. Should I:
Create 2 different apps, and repeat the normal registeration and login for each.
If I do the above, hope the freelancers when logged in won't access customers view.
How do I add user type to the user profile if I decide to use one app and model for it.
Please I need a step by step beginner approach, or a link to relevant source.
Thanks.
You could try this:
class UserProfile(models.Model):
user = models.ForeignKey(User)
#define general fields
class Freelancer(models.Model):
profile = models.ForeignKey(UserProfile)
#freelancer specific fields
class Meta:
db_table = 'freelancer'
class Customers(models.Model):
profile = models.ForeignKey(UserProfile)
#customer specific fields
class Meta:
db_table = 'customer'
You can then have as many Users as you want from the UserProfile.
You should need just use Groups Django mechanism - you need to create two groups freelancer and let say common and check whether user is in first or second group - then show him appropriate view
To check whether user is in group you can use
User.objects.filter(pk=userId, groups__name='freelancer').exists()
You Could Try extending the Default Django Auth User like this
Create an App with Account or Whatever name you like , then in models.py write like below
class User(AbstractUser):
is_head = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
Add Auth Extended Model in Settings.py
AUTH_USER_MODEL = 'accounts.User'
Migrate your Account app and you are all set with Your User Extended Model.

Categories