[Answered ]-Class Based View, add data to the Form

2👍

You can get the value from the form’s cleaned_data.

def form_valid(self, form):
    if form.cleaned_data['right_provider']:
        ...
    else:
        ...
    return super().form_valid(form)

def form_valid(self, form):
    if form.cleaned_data['right_provider']:
        ...
    else:
        ...
    return super().form_valid(form)

Note I have removed the save() call – the form will be saved automatically when you call super().

If you do need to call save in your view, I would avoid calling super(). I think it’s clearer, and it avoids a potential problem of save_m2m not being called. See the docs for the save method form more information.

def form_valid(self, form):
    user = form.save(commit=False)
    ...
    user.save()  # save the user to the db
    form.save_m2m()  # required if the form has m2m fields
    return HttpResponseRedirect(self.get_success_url())

Another option is to call super() first without returning, then access self.object, and finally return the response.

def form_valid(self, form):
    response = super().form_valid(form)
    user = self.object
    if form.cleaned_data['right_provider']:
        ...
    else:
        ...
    return response

0👍

Model forms expect the form fields to match the model fields. So you could add it as a field to your model.

If you only want the field on the form, you want to add it in the innit method of the form.

class UserFrom(ModelForm)

    def __init__(self, **kwargs)
        super(UserForm, self).__init__(**kwargs)

        # probably some code here to work out the initial state of the checkbox, 
        self.fields['right_provider'] = forms.BooleanField(label='Right Provider', required=False)

Leave a comment