0

I'm trying to create a webapp in django 1.9 for task tracking and ordering. The different tasks are divided into spaces (like different projects). Now, I want to be able to choose what the task is assigned to in the CreateView.

The problem is, that I have a large number of users in my system, so I do not want to show a dropdown. Instead, I want to use a TextInput widget, to have the form check for the available options (this way I can also use typeahead on the client side).

This is the best I could come up with for the TaskCreate view:

class TaskCreate(LoginRequiredMixin, CreateView):
    """
    a view for creating new tasks
    """
    model = Task
    fields = ['space', 'name', 'description', 'assigned_to', 'due_date']
    template_name = "task_tracker/task_form.html"
    success_url = reverse_lazy('tracker:my_open_task_list')

    def get_context_data(self, **kwargs):
        context = super(TaskCreate, self).get_context_data(**kwargs)
        context['header_caption'] = 'Create'
        context['submit_caption'] = 'Create'
        context['all_usernames'] = [x.username for x in User.objects.all()]

        return context


    def get_form(self, form_class=None):
        form = super(TaskCreate, self).get_form(form_class)
        form.fields['assigned_to'].choices = [(x.username, x.id) for x in User.objects.all()]
        form.fields['assigned_to'].initial = self.request.user.username,
        form.fields['assigned_to'].widget = widgets.TextInput()

        try:
            form.fields['space'].initial = Space.objects.get(name=self.request.GET['space'])
        finally:
            return form

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.assigned_to = User.objects.get(username=form.cleaned_data['assigned_to'])
        return super(TaskCreate, self).form_valid(form)

But the thing is that this is not working - the form still considers my choice to be illegal, even when I type in a valid username.

I tried to switch places the x.username and x.id in the choice field but it didn't help me.

I'm stuck on this for a week now. Can anybody help me please?

  • What happens when you type in a valid `id`? –  Jan 31 '16 at 21:27
  • the user with that ID is added and submitted. but of course I don't want to write the `id` of the user, but its name. it seems the because the type of the `field` is `ModelChiceField` it just ignores the `choices` attribute I gave him. the only option I can think of right now is to delete this `assign_to` from the list of fields and add it myself in the `get_from` method. but it seems like a lousy way to do it. – Michael Rabinovich Feb 02 '16 at 20:22

0 Answers0