为什么Form不会保存多对多的字段值

时间:2015-12-20 12:56:09

标签: django django-models django-forms python-3.5

代码的问题在于表单已成功通过,但模型未保存Profile模型中的多对多字段。 除食物和类型外,所有值都会被保存。 请帮我解释一下代码。 模型

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)

1 个答案:

答案 0 :(得分:2)

由于您使用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上的文档。