how to create user in django code example

Example 1: how to require login for Django function views

To require login for Django function-based views
  
from django.contrib.auth.decorators import login_required

@login_required
def your_view():
    .....
        
      To require login for Django class-based views
      
from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
	.....

Example 2: create django user command line

user@hostname$ python3 -m django shell
>>> import django.contrib.auth
>>> User = django.contrib.auth.get_user_model()
>>> user = User.objects.create_user('username', password='userpassword')
>>> user.is_superuser = False
>>> user.is_staff = False
>>> user.save()

Example 3: django create user

from django.contrib.auth.models import User
user = User.objects.create_user(value['USERNAME'], value['EMAIL'], value['PASSWORD'])
user.first_name = value['NAME']
user.last_name = value['SURNAME']
user.save()

Example 4: django user permission check

# all your import goes here for Models.py
...

# Adding Permissions to a Model.
class BlogPost(models.Model):
  ... # model fields
  class Meta:
    permissions = [('can_write_blog', 'Can Write Blog')]
    

# Checking permissions in Views.py
if request.user.has_perm('app_name.can_write_blog'):
  # give access to blog post form
else:
  # restrict user from access the page.

Example 5: how to create staff account in django

user = User.objects.create_user('john', '[email protected]', 'johnpassword')  
user.is_staff=True 
user.save()

Example 6: create login user django command

py manage.py  createsuperuser 
1=enter your userName
2=enter your email
3=enter your password
4=enter your password again 
5=for create user enter y (yes)