Django Forms.ModelMultipleChoiceField不保存任何内容

时间:2019-02-18 09:09:28

标签: django django-forms django-views

forms.ModelMultipleChoiceFieldwidget = forms.SelectMultiple遇到了很多问题,我希望有人能让我摆脱痛苦。

我正在使用JQuery Chosen多重选择框(类似于Select2)在字体末端的interest中渲染ProfileUpdateForm字段。example < / p>

起初request.POST根本没有执行,提交按钮不可单击,并且出现了错误An invalid form control with name='interest' is not focusable,现在我通过添加

进行了修补
def __init__(self, *args, **kwargs):
        super(ProfileUpdateForm, self,).__init__(*args, **kwargs)
        self.fields['interest'].required = False

到我的ProfileUpdateForm

尽管我现在可以单击“提交”按钮并查看

[2019/02/18 08:26:53] HTTP POST /profile 302

和所有其他表单信息更新... forms.ModelMultipleChoiceField interest字段没有任何反应。

如果选择interest,然后按submit,则页面刷新时SelectMultiple字段为空,并且不会存储/保存任何内容。我已经检查了管理员,但该部分没有任何更新。

进行问题诊断的最佳方法是什么?

forms.py

class ProfileUpdateForm(forms.ModelForm):

    interest = forms.ModelMultipleChoiceField(
        queryset=Interest.objects.all(),
        widget = forms.SelectMultiple(attrs={
        'name': "interest",
        'data-placeholder': "Choose your interests",
        'class': 'chosen-select',
        'multiple tabindex': '4',
    }))

    def __init__(self, *args, **kwargs):
         super(ProfileUpdateForm, self,).__init__(*args, **kwargs)
         self.fields['interest'].required = False

    class Meta:
         model = Profile
         fields = ['interest', 'age', 'bio']

views.py

def profile_view(request):
    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

    else:
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'p_form': p_form,
    }

    return render(request, 'users/profile.html', context)

profile.html

<form method="POST" enctype="multipart/form-data">
     {% csrf_token %}
     <!-- edit Profile model info -->
     {{ p_form|crispy }}
     <button type="submit" value="submit">Update Profile</button>
</form>

<script>
        $(".chosen-select").chosen();
        $('button').click(function() {
          $(".chosen-select").val('').trigger("chosen:updated");
        });
</script>

models.py

class Interest(models.Model):
    interest_name    = models.CharField(max_length=30)

    class Meta:
        ordering = ['interest_name']

    def __str__(self):
        return self.interest_name

class Profile(models.Model):
    user            = models.OneToOneField(User, on_delete=models.CASCADE)
    interest        = models.ManyToManyField(Interest)
    bio             = models.CharField(max_length=200)

0 个答案:

没有答案