函数is.valid()返回false,尽管它不应该这样做

时间:2019-07-22 15:12:33

标签: django

我的一个模型中有一个表单,无论我选择什么,它都会返回false。

我不知道它的确切来源,除了target_group queryset可以正常工作外,其他形式与此类似,POST请求中的html似乎有问题。

    class ActivitiesForm(forms.Form):
        activity = forms.ModelChoiceField(label='Select your activities', queryset=Activity.objects.all())
        target_group = forms.ModelChoiceField(label='Who is the report destined to?', queryset=OutputOutcomeImpact.objects.order_by().values_list('target_group', flat=True).distinct())


    class Activities(TemplateView):
        template_name = 'blog/activities.html'
        context = {'title': 'Activities selection page'}
        def get(self, request):
            form_act = ActivitiesForm()
            form_act.fields['activity'].queryset = Activity.objects.filter(categories__sectors__name=request.session['sector']['name'])
            self.context['form_act']=form_act
            return render(request,self.template_name, self.context)
        def post(self,request):
            form_act = ActivitiesForm(request.POST)
            print(form_act.is_valid(),form_act)
            if form_act.is_valid():
                request.session['activity'] = model_to_dict(form_act.cleaned_data['activity'])
                request.session['target_group'] = model_to_dict(form_act.cleaned_data['target_group'])
                return redirect('/about', self.context)


Console print:    


      False <tr><th><label for="id_activity">Select your activities:</label></th><td><select name="activity" required id="id_activity">
          <option value="">---------</option>

          <option value="Municipal waste incineration" selected>Municipal waste incineration</option>

          <option value="Plastic upcycling">Plastic upcycling</option>

        </select></td></tr>
        <tr><th><label for="id_target_group">Who is the report destined to?</label></th><td><ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul><select name="target_group" required id="id_target_group">
          <option value="">---------</option>

          <option value="Standard" selected>Standard</option>

          <option value="Investors">Investors</option>

        </select></td></tr>

以下是在表格中使用的模型的详细信息:

    class OutputOutcomeImpact(models.Model):
        output_outcome_impact_name = models.CharField(max_length=255, primary_key=True)
        TYPECHOICE = (
        ('Output', 'Output'),
        ('Outcome', 'Outcome'),
        ('Impact', 'Impact'),
        )
        type = models.CharField(max_length=255, choices=TYPECHOICE)
        description = models.TextField()
        TARGETGROUP = (
        ('Standard', 'Standard'),
        ('Investors', 'Investors'),
        ('Local authorities and NGOs', 'Local authorities and NGOs'),
        )
        target_group = models.CharField(max_length=255,choices=TARGETGROUP)
        question = models.TextField()
        models.ForeignKey('self', on_delete=models.PROTECT)
        def __str__(self):
            return self.output_outcome_impact_name , self.target_group



    class Activity(NameDescModel):
        product_service = models.TextField()
        output_outcome = models.TextField()
        outcome_impact = models.TextField()
        categories = models.ManyToManyField('Category')
        output_outcome_impacts = models.ManyToManyField('OutputOutcomeImpact')
        countries = models.ManyToManyField('Country')

2 个答案:

答案 0 :(得分:0)

尝试一下:

target_group = forms.ChoiceField(label='Who is the report destined to?', choices=OutputOutcomeImpact.TYPECHOICE)

Django文档中的更多信息:https://docs.djangoproject.com/en/2.2/ref/forms/fields/#choicefield

答案 1 :(得分:0)

问题似乎是由于以下原因中的queryset

 target_group = forms.ModelChoiceField(label='Who is the report destined to?', queryset=OutputOutcomeImpact.objects.order_by().values_list('target_group', flat=True).distinct())

这导致将不正确的值添加到表单HTML。例如:

<option value="Municipal waste incineration" selected>

这里的value应该是模型的主键(因为您正在使用ModelChoiceField)解决方案是使用:

target_group = forms.MyModelChoiceField(label='Who is the report destined to?', queryset=OutputOutcomeImpact.objects.all().distinct())

请注意您需要的自定义MyModelChoiceField,以便在下拉菜单中显示正确的文本。

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

docs提供了更多信息