提交表单后,两个字段无法保存。 Django的

时间:2016-03-19 14:21:24

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

我有两个模型字段(爱好和语言),当用户提交表单时,它们不会被保存。它们是连接到不同模型的许多领域。但我不确定如何将它们保存在模型中。

这是模型:

# this is model for user
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

    hobbies = models.ManyToManyField(Hobby)
    languages = models.ManyToManyField(Language)

    profilepic = models.ImageField(upload_to='static/images/Profile Pictures', blank=True)
    city = models.ForeignKey(City)
    slug = models.SlugField(unique=True)

    average_rating = models.IntegerField(default=0)
    ratings_count = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        # Uncomment if you don't want the slug to change every time the name changes
        self.slug = slugify(self.user.username)
        super(UserProfile, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.user.username

这是爱好和语言模型:

# this is the model for hobbies - one to many relationship with User
class Hobby(models.Model):
    hobby = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        # if self.id is None:
        # self.slug = slugify(self.name)
        self.slug = slugify(self.hobby)
        super(Hobby, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.hobby

# this is the model for languages - one to many relationship with User
class Language(models.Model):
    language = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        # if self.id is None:
        # self.slug = slugify(self.name)
        self.slug = slugify(self.language)
        super(Language, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.language

这是将表单数据保存到数据库中的视图:

def createprofile(request):

    registered = False
    if request.method == 'POST':
        user = User.objects.get(username = request.user.username)
        user_form = UserForm(data=request.POST, instance = user)

        profile_form = UserProfileForm(data=request.POST)



        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user



            if 'profilepic' in request.FILES:
                profile.profilepic = request.FILES['profilepic']

            profile.save()

            registered = True

            if 'next' in request.GET:
                return redirect(request.GET['next'])

        else:
            print user_form.errors, profile_form.errors



    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(request,
            'createprofile.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )

1 个答案:

答案 0 :(得分:1)

在save方法中使用commit = False时,Django提供了一个save_m2m方法来创建关系。

https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method

正如Django docs在上面的链接所述:

  

当您的模型与另一个模型具有多对多关系时,可以看到使用commit = False的另一个副作用。如果模型具有多对多关系,并且在保存表单时指定commit = False,则Django无法立即保存多对多关系的表单数据。这是因为在实例存在于数据库中之前,无法为实例保存多对多数据。