Answer the question
In order to leave comments, you need to log in
How to pass the value of the User model to the signals?
Hi all.
In this situation, in the create_profile_database () function,
I want to pass the value of the User model that has username to this function, which should, upon post_save, create a database with the name username where username in the Student object is linked one to one.
How to be?
My Model:
from django.db import models
from django.conf import settings
from django.db.models.signals import post_save
from django.db import connection
class Student(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True)
first_name = models.CharField(max_length=80, blank=True)
last_name = models.CharField(max_length=80, blank=True)
slug = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField('Datetime created')
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
# Dev
def create_profile_database(sender, **kwargs):
if kwargs['created']:
with connection.cursor() as cursor:
cursor.execute("CREATE DATABASE username")
row = cursor.fetchone()
return row
post_save.connect(create_profile_database, sender=Student)
class Work(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
name = models.CharField(max_length=80, blank=True)
description = models.CharField(max_length=255, blank=True)
points = models.PositiveSmallIntegerField(blank=True)
created_at = models.DateTimeField('Datetime created')
def __str__(self):
return '%s %s' % (self.name, self.points)
Answer the question
In order to leave comments, you need to log in
In my project, I use the following scheme for creating a profile when creating a user:
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
...
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
def __str__(self):
return self.user
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question