dearly
dearly

Reputation: 1

How can I add a new database entry upon user registration with Django?

I'm starting to learn Django and have a class called Customer in my models.

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,
        primary_key=True)
    cart = models.ManyToManyField(Product)
    orders = models.ManyToManyField(Order)

    def __init__(self, user):
        self.user = user

I'm importing django.contrib.auth to register users to the database, but I would like to also initialize a Customer object upon registration.

I first attempted to override the save() method from the UserCreationForm and initialize a Customer object there:

class UserCreationForm(forms.ModelForm):
    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        customer = Customer(user)
        customer.save()
        if commit:
            user.save()
        return user

But it did not seem to create a Customer object.

Alternatively, is it better to extend the User class to have the Customer class fields? I initially thought I should keep authentication separate, which is why I created the Customer class.

Upvotes: 0

Views: 748

Answers (1)

Moha369
Moha369

Reputation: 834

Might be better if you created a signal instead!

from django.db.models import signals
from django.dispatch import receiver
from django.contrib.auth.models import User
from path.to.models import Customer

@receiver(signals.post_save, sender = User)
def create_customer(sender, instance, created, *args, **kwargs):
    if created:
        c = Customer(...) #create your customer object
        c.save()

and in apps.py, import signals to run it.

Upvotes: 1

Related Questions