gpt4 book ai didi

django - 为什么表单不保存多对多字段值

转载 作者:行者123 更新时间:2023-12-02 02:24:55 24 4
gpt4 key购买 nike

代码的问题是表单已成功通过,但模型未在配置文件模型中保存多对多字段。除了食物和类型之外,所有值都被保存。请帮我编写代码。型号

class Relationship(models.Model):
status = models.CharField(max_length =30)

def __str__(self):
return self.status

class Food(models.Model):
food_name = models.CharField(max_length = 80)

def __str__(self):
return self.food_name

class City(models.Model):
city = models.CharField(max_length = 80)

def __str__(self):
return self.city

class Type(models.Model):
types = models.CharField(max_length =80)

def __str__(self):
return self.types

class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
avatar = models.ImageField(upload_to = image_upload_to)
city = models.OneToOneField(City)
fav_food = models.ManyToManyField(Food)
relationship = models.OneToOneField(Relationship)
preferrs = models.ManyToManyField(Type)

def get_absolute_url(self):
return reverse('chatbot')

def __str__(self):
return self.user.get_username()
`

我的模型表格如下

class ProfileForm(ModelForm):
class Meta:
model=Profile
fields = ['avatar','city','fav_food','relationship','preferrs']

我的观点如下

def ProfileCreate(request):
template="profile.html"
context={}
if request.user.get_username()=='':
return redirect('account_login')
if Profile.objects.all().filter(user__username=request.user.get_username()).count()>0:
return redirect('chatbot')
else:

form = ProfileForm(request.POST ,request.FILES or None)

if form.is_valid():

new_profile = form.save(commit=False)

user = User.objects.all().filter(username=request.user.get_username())[0]
new_profile.user=user
new_profile.save()
return redirect('chatbot')

context['form']=form


return render(request,template,context)

最佳答案

由于您使用 commit=False 保存表单,因此在保存实例后必须调用表单的 save_m2m 方法。

new_profile = form.save(commit=False)
# no need to fetch the user here, just use request.user
new_profile.user = request.user
new_profile.save()
form.save_m2m()

请参阅 model form save method 上的文档了解更多信息。

关于django - 为什么表单不保存多对多字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381206/

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