I am trying to implement a drop-down list in Django which contains the email addresses of those users whose domain matches to that of the currently logged in user.
I am using the following code but it still shows a list and not a drop down list. I tried changing the widget part from ChoiceField to MultipleChoiceField and now to CheckboxSelectMultiple just to see if checkbox is displayed or not but none of it seems to work.
Here is my forms.py
class AssignTask(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(widget=forms.Textarea)
assign_to = forms.MultipleChoiceField(choices=[], widget=forms.CheckboxSelectMultiple, required=False)
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.MultipleChoiceField(choices=[(i.email, i.email) for i in User.objects.filter(is_active=True, email__icontains=user_email)])
Here is my views.py
@login_required
def assigntask(request):
assign_form = AssignTask(user=request.user)
return render(request, 'todoapp/assign_task.html', context={'assign': assign_form})
Here is my html
{% extends 'todoapp/base.html' %}
{% block title %}Create a task{% endblock %}
{% block content %}
<h2>Create a task and assign it to a user</h2>
<form method="post">
{% csrf_token %}
{{ assign.as_p }}
<br/><input type="submit" value="Assign">
<button onclick="location.href='{%url 'dashboard' %}'" type="button">Go back</button>
</form>
{% endblock %}
Apparently this solution works for me
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)])