Reputation: 353
I want to get the chosen email-id from a drop down list made from ChoiceField. I have written a code but apparently it is not working. How do I do it ?
Here is my 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>')
Here is my 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)])
Error that I am getting is:
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
Upvotes: 1
Views: 969
Reputation: 88429
From the error traceback, We can understand, you are missing a .get()
function
so, try this,
assign_email = assign_now.cleaned_data.get('assign_to')
instead of
assign_email = assign_now.cleaned_data('assign_to')
complete view function
@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>')
Upvotes: 1