Search code examples
pythondjangomodelchoicefield

Django ModelChoiceField with empty_label as valid input


I'm using the following form to generate a dropdown list with my registered users:

class TaskAssignUserForm(forms.Form):
    user = forms.ModelChoiceField(queryset=User.objects.all().order_by('username'))

Inside my template I render the above form together with a submit button. The application user can choose from the registered users to select one and assign him/her to a task. This is working, if a user and not the empty label (--------) was selected.

But, I want the empty label as a valid option too, to cancel the assignment between the task and the user. I'm working with the following views.py and looking for an option to check if the empty label or an empty choice was made.

if form_TaskAssignUserForm.is_valid():
    task.user_assigned = form_TaskAssignUserForm.cleaned_data['user']
    task.save()
else:
   if  # check if emtpy label is set
       task.user_assigned = None
       task.save()

I found out that checking if form_TaskAssignUserForm.cleaned_data['user'] exists could be an option but I feel not comfortable with that. There should be a way that works together with the .is_valid() check.

Is there a djangonian way solving that problem?

Bye, aronadaal


Solution

  • You should just need to set required=False on the field.

    user = forms.ModelChoiceField(required=False, queryset=User.objects.all().order_by('username'))
    

    This means that no selection is required for the form to be valid.