How to have empty fields using ClassBased Views?

Hello,

I want to have empty fields when using ClassBased Views.

Right now my fields gets filled with the default values of my model, I do not want this to happen.

Is there a way to overwrite this inside the view/form class?

View:

class WegingenInvoegenView(LoginRequiredMixin, CreateView):
    template_name = 'webapp/wegingen/wegingeninvoegen.html'
    form_class = WegingenInvoegenForm

    def form_valid(self, form):
        f = form.save(commit=False)
        f.gebruiker = self.request.user
        f.save()

        return redirect('wegingenbeheer')

Form:

class WegingenInvoegenForm(forms.ModelForm):
    class Meta:
        model = Wegingen
        fields = ['aantalTonICT', 'aantalTonServers', 'aantalTonElektro', 'aantalTonGSMIncl',
                    'aantalTonGSMExcl', 'aantalTonGrootWitgoed', 'aantalTonKoelVries',
                    'aantalTonRestafval', 'gebruiker', 'levering', 'ophaling']

Yes, you have a couple of different options, the first two coming to mind are:

  • Remove the default values in your model (You’re explicitly defining them as the default values for those fields, so it would make sense to apply them to the form so that when the form is submitted, those values are applied if nothing is changed.)

  • Override the get_form method in your class and remove those values from the form after it has been initialized.

I’ve fixed it by doing setting Initial to None in the Form Class:

class WegingenInvoegenForm(forms.ModelForm):
    class Meta:
        model = Wegingen
        fields = ['aantalTonICT', 'aantalTonServers', 'aantalTonElektro', 'aantalTonGSMIncl',
                    'aantalTonGSMExcl', 'aantalTonGrootWitgoed', 'aantalTonKoelVries',
                    'aantalTonRestafval', 'gebruiker', 'levering', 'ophaling']

    aantalTonICT = forms.FloatField(
        initial = None,
    )

    aantalTonServers = forms.FloatField(
        initial = None,
    )

    aantalTonElektro = forms.FloatField(
        initial = None,
    )

    aantalTonGSMIncl = forms.FloatField(
        initial = None,
    )

    aantalTonGSMExcl = forms.FloatField(
        initial = None,
    )

    aantalTonGrootWitgoed = forms.FloatField(
        initial = None
    )

    aantalTonKoelVries = forms.FloatField(
        initial = None,
    )

    aantalTonRestafval = forms.FloatField(
        initial = None,
    )



class UpdateWegingenForm(forms.ModelForm):
    class Meta:
        model = Wegingen
        fields = ['aantalTonICT', 'aantalTonServers', 'aantalTonElektro', 'aantalTonGSMIncl',
                    'aantalTonGSMExcl', 'aantalTonGrootWitgoed', 'aantalTonKoelVries',
                    'aantalTonRestafval', 'gebruiker', 'levering', 'ophaling']

Be aware that you are overriding the default fields being created by the model form.

See the green “Note” section in the docs on Overriding the default fields.