I have an overrided User model and a Cart model. I expect that a Cart model instance is created automatically once a User model instance is created. I am trying to pass the newly registered user into the get_queryset
method, but no idea how to do it. Are there any other better ways of doing this? It's because I may need to do the same thing for other models unlike the User model which has a form that can pass values to the get_queryset
method.
account/models.py:
class Cart(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.user.email + '_cart'
account/views.py:
class RegisterView(generic.CreateView):
template_name = 'account/register.html'
form_class = RegisterForm
success_url = reverse_lazy('book:home')
def get_queryset(self):
sign_up = self.request.POST.get('register')
if sign_up:
c = Cart.objects.create(user=???)
c.save()
account/templates/account/register.html:
<form name="register" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Sign Up">
</form>
To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.
__init__ method "__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.
Method-1: Use Django's post_save
signal (as @AKX said)
from django.contrib.auth import get_user_model
@receiver(post_save, sender=get_user_model())
def create_user_cart(sender, instance, created, **kwargs):
if created:
Cart.objects.create(user=instance)
Method-2: Override the save()
method of your User model or extended Usermodel
class MyUserModel(....):
# your code
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
Cart.objects.create(user=self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With