I am developing a server using Django and wanted when a user registered to run a function that would create a directory with the username. The folder with the new user name will be saved in Collections. My code is as follows:
Models.py
from django.db import models
from django.contrib.auth.models
import (BaseUserManager,AbstractBaseUser)
class UserManager(BaseUserManager):
def create_user(self, username, first_name, last_name, email, password=None):
"""
Creates and saves a user with the given variables and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, first_name, last_name, email, password=None, is_admin=True):
"""
Creates and saves a superuser with the given variables and password.
"""
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
is_admin = is_admin,
)
user.set_password(password)
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
username = models.CharField(max_length=255, unique=True)
first_name = models.CharField(max_length=100, unique=False)
last_name = models.CharField(max_length=100, unique=False)
is_active = models.BooleanField(default=True, unique=False)
is_admin = models.BooleanField(default=False, unique=False)
user_collection = models.CharField(max_length=500, default='NotCreated', unique=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name', 'email']
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
Directory images
Is there any way that I can accomplish what I need?
You can create a model method on the User
model and use python's os
module to create the respective directories per user.
import os
from django.db import models
class User(models.Model):
...
def add_to_collections(self):
path = f'collections/{self.username}'
if not os.path.exists(path):
os.makedirs(path)
# overriden save method
def save(self, *args, **kwargs):
if not self.pk:
self.add_to_collections()
super().save(*args, **kwargs)
Then, add_to_collections
model method can be hooked into an overriden save or a post_save signal with a check if the model instance is created and saved for the first time.
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.