Reputation: 2096
In my database I want to synchronize two tables. I use auth_user(Default table provided by Django) table for registration and there was another table user-profile that contain entities username, email, age etc. How to autometically upadate the columns username and email in user-profile according to updation in auth_user table.
from django.contrib.auth.models import User
class profile(models.Model):
username = models.CharField(max_length = 30)
email = models.EmailField()
age = models.PositiveIntegerField()
auth_user_id = models.ForeignKey(User)
Upvotes: 0
Views: 1573
Reputation: 4971
You can either modify the django registration code and include the code to save into your profile model on every new registration.
Or
You can set a signal on every save of User model. See the documentation.
def create_profile(sender, **kwargs):
if kwargs["created"]:
p = Profile(user=kwargs["instance"], ...)
p.save()
django.db.models.signals.post_save.connect(create_profile, sender=User)
create_profile() will be called every time any User object is saved. In this example, I create Profile object only if a new User instance has been created. You can modify it to change existing Profile objects on every change in User instance, also.
Upvotes: 2