如何使从CheckboxSelectMultiple保存的值在Django中填充我的编辑表单?

时间:2017-03-20 17:06:10

标签: python django django-forms

我正在尝试创建一个有效的编辑视图。创建用户配置文件非常有效。我可以在管理员中看到已保存的复选框值,但是当我去编辑表单时,除了复选框之外,所有内容都正确呈现。这些都是空的,好像没有保存任何值。如果我选择新值并提交编辑表单,则会正确保存新值,因此我的问题只是将保存的值显示为复选标记。

我的表格是:

  class ProfileUserForm(forms.ModelForm):

  class Meta:
        model = ProfileUser
        fields = ('field1', 'field2','field3','field4', 'chosencategories')


  chosencategories = forms.ModelMultipleChoiceField(
                                     widget=forms.CheckboxSelectMultiple,
                                     queryset=Category.objects.all(), to_field_name="name")

基于这些模型:

class ProfileUser(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)

    field1 = models.CharField(max_length=155, blank=True)
    field2 = models.CharField(max_length=155, blank=True)
    field3 = models.DateField(blank=True)
    field4 = models.CharField(max_length=255, blank=True)

    chosencategories=models.ManyToManyField(Category, blank=True, null=True, related_name='categorieschosen')

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

class Category(models.Model):
    name=models.CharField(max_length=100, choices=CATEGORIES)

    class Meta:
        verbose_name_plural = "categories"

    def __str__(self):
      return self.name

这是我目前的编辑视图:

@login_required
def edit_user_profile(request, username):
    user = request.user
    userprofile = ProfileUser.objects.get_or_create(user=user)[0]
    if request.method == 'POST':
        profile_form = ProfileUserForm(request.POST, instance=userprofile)
        if profile_form.is_valid():
            updated_user_profile=profile_form.save(commit=False)
            updated_user_profile.user = user
            updated_user_profile.save()
            profile_form.save_m2m()

            return HttpResponseRedirect(reverse('accounts:userprofile', kwargs={'username': user.username}))
            messages.success(request, ('Your profile was successfully updated!'))

        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        profile_form = ProfileUserForm(instance=userprofile)

    return render(request, 'accounts/edit_user_profile.html', 
                            {'profile_form': profile_form })

我看过:

我添加了用户的建议:

profile_form = ProfileUserForm(instance=ProfileUser.objects.get(user=request.user))

但这与我当前的行:

具有完全相同的效果
profile_form = ProfileUserForm(instance=userprofile)

所以我不确定我错过了什么。所有帮助赞赏。谢谢。

0 个答案:

没有答案