Reputation: 4637
I am having an issue on saving my model, my UserProfile reference on a foreign key to a Customer, and I have gotten sure that my form in sending the needed info and the customer object is being loaded, however when I save my model, this lost the reference to customer
My code is
models.py
from django.db import models
from customers.models import Customer
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from anfitrion.models import ModelBase
from django.db.models.signals import post_save
class UserProfile(ModelBase):
user = models.OneToOneField(User)
customer = models.ForeignKey(Customer)
address = models.CharField(max_length = 255)
phone_home = models.CharField(max_length = 16)
phone_office = models.CharField(max_length = 16)
expiration = models.DateTimeField(null=True, blank=True)
picture = models.ImageField(upload_to='profiles/%Y/%m/%d')
observations = models.TextField(null=True, blank=True)
status = models.BooleanField()
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
class SiteProfile(ModelBase):
site = models.OneToOneField(Site)
def __str__(self):
return "%s's profile" % self.user
def create_site_profile(sender, instance, created, **kwargs):
if created:
profile, created = SiteProfile.objects.get_or_create(site=instance)
post_save.connect(create_site_profile, sender=Site)
function running the saveing
def users_save (request):
#try:
if request.is_ajax() and request.POST:
user_id = request.POST['user_id']
s = get_current_site(request)
u = User (
username = request.POST['username'],
first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
email = request.POST['email']
)
u.set_password(request.POST['password'])
c = None
if int( request.POST['customer_id'] ) > 0:
c = Customer.objects.get(id=request.POST['customer_id'])
up = UserProfile(
customer = c,
address = request.POST['address'],
phone_home = request.POST['phone_home'],
phone_office = request.POST['phone_office']
)
up.user = u
u.save()
if int( request.POST['group_id'] ) > 0:
g = Group.objects.get( id = request.POST['group_id'] )
g.user_set.add(u)
return HttpResponse(1, mimetype='application/json')
Upvotes: 3
Views: 4823
Reputation: 99680
Here
up.user = u
u.save()
You are not saving the up
anywhere.
So u.save()
should be up.save()
u.save()
up.user = u
up.save()
Upvotes: 7