如何从Django中的表单获取ChoiceField值?

时间:2019-03-04 06:55:12

标签: python django

我想从ChoiceField的下拉列表中获取所选的电子邮件ID。我已经编写了代码,但显然无法正常工作。 我该怎么办?

这是我的 views.py

@login_required
def assign(request):
    if request.method == 'POST':
        assign_now = AssignTask(data=request.POST, user=request.user)
        if assign_now.is_valid():
            task_title = assign_now.cleaned_data.get('title')
            task_description = assign_now.cleaned_data.get('desc')
            assign_email = assign_now.cleaned_data('assign_to')
            assign_email = dict(AssignTask.fields['assign_to'].choices)[assign_email]
            user_details = User.objects.get(email=assign_email)
            t = Task(title=task_title, description=task_description, assigned_to=user_details)
            t.save()
            return HttpResponse('<h2>Successfully assigned task</h2>')
        else:
            return HttpResponse('<h2><Task assignment failed/h2>')
    else:
        return HttpResponse('<h2>Request method error</h2>')

这是我的 forms.py

class AssignTask(forms.Form):
    title = forms.CharField(max_length=200)
    description = forms.CharField(widget=forms.Textarea)
    assign_to = forms.ChoiceField(widget=forms.Select(choices=[]))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        user_email = self.user.email.split('@')[1]
        super(AssignTask, self).__init__(*args, **kwargs)
        self.fields['assign_to'] = forms.ChoiceField(choices=[(i.email, i.email) for i in User.objects.filter(is_active=True, email__icontains=user_email)])

我遇到的错误是:

File "/home/gblp250/PycharmProjects/assignment/todoapp/views.py" in assign
  118.             assign_email = assign_now.cleaned_data('assign_to')

Exception Type: TypeError at /assign
Exception Value: 'dict' object is not callable

1 个答案:

答案 0 :(得分:1)

从错误追溯中我们可以理解,您缺少 .get() 函数

所以,尝试一下,  

assign_email = assign_now.cleaned_data.get('assign_to')
代替

 assign_email = assign_now.cleaned_data('assign_to')

完整的查看功能

@login_required
def assign(request):
    if request.method == 'POST':
        assign_now = AssignTask(data=request.POST, user=request.user)
        if assign_now.is_valid():
            task_title = assign_now.cleaned_data.get('title')
            task_description = assign_now.cleaned_data.get('desc','Sample Description')
            assign_email = assign_now.cleaned_data.get('assign_to')
            user_details = User.objects.get(email=assign_email)
            t = Task(title=task_title, description=task_description, assigned_to=user_details)
            t.save()
            return HttpResponse('<h2>Successfully assigned task</h2>')
        else:
            return HttpResponse('<h2><Task assignment failed/h2>')
    else:
        return HttpResponse('<h2>Request method error</h2>')