1

The below Django form works, but for the life of me I can't figure out how to make the ModelChoiceField for operator blank or set to None by default. I would like the user to have the option of just leaving this choices field set to None. This autopopulates with the first user in the user list.

Model

class Build(models.Model):
    PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    author =  models.ForeignKey(get_user_model(),related_name='+',on_delete=models.CASCADE,blank=True, null= True,)
    plannedAuthor =  models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE)
    status = models.CharField(max_length=100,blank=True,)
    operator = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE, default=None)

View

class queuedBuild_CreateView(LoginRequiredMixin,CreateView):
    model = Build
    form_class = queuedBuild_Creation_Form
    template_name = 'addQueuedBuild.html'
    login_url = 'login'
    success_url = reverse_lazy('equipmentdashboard')

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        customer = self.request.user.PSScustomer
        form.fields['operator'].choices = [(item.id, item.first_name) for item in CustomUser.objects.filter(isDevice=False, PSScustomer = customer)]
        return form

Form

class queuedBuild_Creation_Form(forms.ModelForm):
    buildDescrip = forms.ModelChoiceField(initial='Your name')
    def __init__(self, *args, **kwargs):
        super(queuedBuild_Creation_Form, self).__init__(*args, **kwargs)
        self.fields['status'].required = True

    class Meta:
        model = Build
        fields = ['status', 'operator',]
MattG
  • 1,682
  • 5
  • 25
  • 45

1 Answers1

6

As long as None is one of your choices you can do:

form.fields['operator'].initial = None

OR

choices = [(item.id, item.first_name) for item in CustomUser.objects.filter(isDevice=False, PSScustomer = customer)]

choices.insert(0, ('', 'None'))
form.fields['operator'].choices = choices

See here.

If not then you can use JavaScript to add a None choice and make it selected.

Dean Elliott
  • 1,245
  • 1
  • 8
  • 12
  • Thanks @Dean Elliot, I actually did try this, it does not change the default to None unfortunately...It doesn't seem to affect this field in any way – MattG Apr 01 '20 at 16:20
  • I've updated the answer, since `None` would now technically be a valid choice, you might want to create some custom validation to prevent the user submitting the form with `None` as a valid choice (if the field is not null), unless you want that. – Dean Elliott Apr 01 '20 at 16:27