gpt4 book ai didi

python - Django 外键模型不保存引用

转载 作者:行者123 更新时间:2023-11-28 21:58:56 24 4
gpt4 key购买 nike

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

我的代码是

模型.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')

最佳答案

这里

up.user = u
u.save()

您没有在任何地方保存up

所以u.save()应该是up.save()

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

关于python - Django 外键模型不保存引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com