ModelMultipleChoiceField django 和调试模式

我正在尝试在我的应用程序中实现 ModelMultipleChoiceField,如下所示:链接

model.py


class Services(models.Model):


    id = models.AutoField(primary_key=True)

    type = models.CharField(max_length=300)


class Professionals_Services(models.Model):

    professional = models.ForeignKey(User, on_delete=models.CASCADE)

    service = models.ForeignKey(Services, on_delete=models.CASCADE)

form.py


class ProfileServicesUpdateForm(forms.ModelForm):

    service = forms.ModelMultipleChoiceField(required=False, queryset=Services.objects.all())


    class Meta:

        model = Professionals_Services

        fields = ['service']


    def clean(self):

        # this condition only if the POST data is cleaned, right?

        cleaned_data = super(ProfileServicesUpdateForm, self).clean()

        print(cleaned_data.get('service'))

view.py


class EditProfileServicesView(CreateView):

    model = Professionals_Services

    form_class = ProfileServicesUpdateForm

    context_object_name = 'services'

    template_name = 'accounts/edit-profile.html'


    @method_decorator(login_required(login_url=reverse_lazy('professionals:login')))

    def dispatch(self, request, *args, **kwargs):

        return super().dispatch(self.request, *args, **kwargs)


    def post(self, request, *args, **kwargs):

        form = self.form_class(data=request.POST)

        if form.is_valid():

            services = form.save(commit=False)

            services.save()

html


<select class="ui search fluid dropdown" multiple="" name="service" id="id_service">

  {% for service in services_list %}

    <option value="{{ service.id }}">{{ service.type }}</option>

  {% endfor %}

</select>

对于开发,我使用 Pycham Professionals(最新版本)和 docker,当我运行应用程序并尝试发布 POST 时,答案是:


Cannot assign "<QuerySet [<Services: Services object (2)>, <Services: Services object (5)>, <Services: Services object (6)>, <Services: Services object (7)>]>": "Professionals_Services.service" must be a "Services" instance.

但是,如果我在调试模式下运行应用程序并在应用程序上设置断点,则if form.is_valid(): 应用程序可以正常工作


那是因为 validate 等于 Unknown not in debug


你知道如何修复吗?


梵蒂冈之花
浏览 89回答 1
1回答

Helenr

你的service是ForeignKey:    service = models.ForeignKey(Services, on_delete=models.CASCADE)AForeignKey表示您选择单个元素,而不是多个元素。您使用ManyToManyField[Django-doc]选择多个元素:class Professionals_Services(models.Model):    professional = models.ForeignKey(User, on_delete=models.CASCADE)    service = models.ManyToManyField(Service)您也不应该重写该post方法,并且可以使用LoginRequiredMixin[Django-doc]来确保用户已登录:from django.contrib.auth.mixins import LoginRequiredMixinclass EditProfileServicesView(LoginRequiredMixin, CreateView):    login_url = reverse_lazy('professionals:login')    model = Professionals_Services    form_class = ProfileServicesUpdateForm    context_object_name = 'services'    template_name = 'accounts/edit-profile.html'    def form_valid(self, form):        form.instance.user = self.request.user        return super().form_valid(form)在您中,Form您还应该返回清理后的数据:class ProfileServicesUpdateForm(forms.ModelForm):    service = forms.ModelMultipleChoiceField(required=False, queryset=Services.objects.all())    class Meta:        model = Professionals_Services        fields = ['service']    def clean(self):        # this condition only if the POST data is cleaned, right?        cleaned_data = super(ProfileServicesUpdateForm, self).clean()        print(cleaned_data.get('service'))        return cleaned_data注意:通常使用settings.AUTH_USER_MODEL[Django-doc]来引用用户模型比直接使用User模型 [Django-doc]更好。注意:Django 中的模型是用PerlCase编写的,而不是Snake_case,因此您可能需要将模型从 重命名Professionals_Services为ProfessionalService。注意:通常 Django 模型有一个单一的名称,所以Services而不是Service.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python