Django表单字段更新

时间:2017-11-05 15:51:10

标签: python django database django-forms

我有一个Django表单,允许用户从多个标签选项中选择一个标签。我面临的问题是,即使标签列表更新,模型表单也不会从数据库中获取更新的标签列表。因此,新标签不会出现在选项中。

这是我在forms.py中的代码:

class EnglishTagForm(forms.Form):
    tag_choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter(
                     agentId=Agent.objects.get(name='English Chowdhury'))]
    tag = forms.CharField(widget=forms.Select(choices=tag_choices, 
                     attrs={'class':'form-control'}))

def __init__(self, *args, **kwargs):
    super(EnglishTagForm, self).__init__(*args, **kwargs)
    self.fields['tag'].choices = [(x.tagName, 
                           x.tagName.upper()) for x in ClassTag.objects.filter(
                           agentId=Agent.objects.get(name='English Chowdhury'))]

此表单正在视图中实例化。我的问题是我应该做哪些更改,以便在每个实例化时从数据库更新tag_choices。

如何在views.py中使用上述表单:

```

def complaintDetail(request, complaint_id):

    complaint = Complaints.objects.filter(pk=complaint_id).first()
    context = {}

    if request.method == 'POST':
        agent = Agent.objects.get(name="English Chowdhury")

        if "SubmitTag" in request.POST:
            englishForm = EnglishTagForm(request.POST)

            if englishForm.is_valid:
                // Complaint Delete Logic
                return redirect('chatbot:modComplaints')
            else:
                englishForm = EnglishTagForm()
                context['eForm'] = englishForm
        elif "SubmitBundle" in request.POST:
            newTagForm = NewTagForm(request.POST)

            if newTagForm.is_valid():
               // Complaint Delete Logic

                complaint.delete()
                return redirect('chatbot:modComplaints')
            else:
               newTagForm = NewTagForm()
               context['newForm'] = newTagForm
    else:
        englishForm = EnglishTagForm()
        context['eForm'] = englishForm
        newTagForm = NewTagForm()
        context['newForm'] = newTagForm
    context['complaint'] = complaint
    return render(request, 'chatbot/complaintDetail.html', context) 

```

编辑:(供将来参考) 我决定修改代码属性并将CharField转换为ModelChoiceField,这似乎解决了这个问题。

更新课程:

class EnglishTagForm(forms.Form):
    tag = forms.ModelChoiceField(queryset=ClassTag.objects.filter(
        agentId=Agent.objects.get(name='English Chowdhury')), 
        empty_label=None, widget=forms.Select(
        attrs={'class':'form-control'}))

1 个答案:

答案 0 :(得分:0)

请从第2行中删除列表理解。这样,

tag_choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter(
                 agentId=Agent.objects.get(name='English Chowdhury'))]

成为

tag_choices = []