【问题标题】:ModelForm object has no attribute 'fields'ModelForm 对象没有属性“字段”
【发布时间】:2020-03-10 15:28:56
【问题描述】:

我正在为表单使用 django (3.0) ModelMultipleChoice 字段。我正在尝试修改查询集以对其进行一些限制。

这里是观点:

def nouvelle_tache(request,id_livrable):
    livrable=Livrable.objects.get(pk=id_livrable)
    projet = livrable.projet
    if request.method == "POST":
        form = NouvelleTache(request.POST,projet=projet)
        tache = form.save(commit=False)
        tache.livrable = livrable
        tache.id_tache = livrable.id_derniere_tache() + Decimal(0.01)
        tache.save()
        form.save_m2m()
        etat = Temps_etat_tache(etat=form.cleaned_data['etat_initial'],tache=tache)
        etat.save()
        return redirect('tache',tache.pk)
    else:
        form = NouvelleTache(projet=projet)
    return render(request, 'application_gestion_projets_AMVALOR/nouvelle_tache.html', locals())

还有表格:

class NouvelleTache(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        projet = kwargs.pop('projet', None)
        queryset = Utilisateur.objects.all()
        for utilisateur in projet.utilisateurs:
            queryset = queryset.exclude(pk=utilisateur.pk)
        self.fields['ressources'].queryset = queryset
        super(NouvelleTache, self).__init__(*args, **kwargs)
        
    ressources= forms.ModelMultipleChoiceField(queryset=Utilisateur.objects.all() ,widget =forms.CheckboxSelectMultiple )
    etat_initial = forms.ModelChoiceField(queryset=Etat_tache.objects.none())
    class Meta:
        model = Tache
        fields  = ['libelle']

我有以下错误:“NouvelleTache”对象没有属性“字段”

我不明白为什么,因为许多其他用户似乎有类似的代码并且它可以工作。

任何帮助将不胜感激。

【问题讨论】:

    标签: django django-forms


    【解决方案1】:
    super(NouvelleTache, self).__init__(*args, **kwargs)
    

    需要先执行,因为fields是在超类中设置的:

    def __init__(self, *args, **kwargs):
        projet = kwargs.pop('projet', None)
        queryset = Utilisateur.objects.all()
        for utilisateur in projet.utilisateurs:
            queryset = queryset.exclude(pk=utilisateur.pk)
        super(NouvelleTache, self).__init__(*args, **kwargs)
        self.fields['ressources'].queryset = queryset
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2018-05-10
      • 2017-03-07
      • 2021-05-28
      • 2012-08-21
      • 2016-01-31
      • 2019-04-15
      • 1970-01-01
      • 2015-06-07
      相关资源
      最近更新 更多