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(self) 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.
没有评论:
发表评论