Django外键模型没有保存参考

时间:2013-06-28 21:00:33

标签: python django python-2.7 django-models

我遇到了一个问题,就是保存我的模型,我的UserProfile参考客户的外键,我已经确定我的表单在发送所需的信息和客户对象正在加载,但是当我保存我的模型,这失去了对客户的引用

我的代码是

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)

运行保存的功能

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')

1 个答案:

答案 0 :(得分:5)

下面

up.user = u
u.save()

您没有将up保存在任何地方。

因此u.save()应为up.save()

u.save()
up.user = u
up.save()