Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between add_form and form

I'm currently reading a book on Django and reached the point where the author is creating a custom user model using the following code:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser

class CustomUserAdmin(UserAdmin): 
    add_form = CustomUserCreationForm 
    form = CustomUserChangeForm 
    model = CustomUser

admin.site.register(CustomUser, CustomUserAdmin)

could someone possibly explain to me what is the difference between add_form and form?

(if anyone could also tell me why we include both CustomUser and CustomUserAdminin admin.site.register(CustomUser, CustomUserAdmin) that would be great)

thank you very much for your help!

like image 713
Nazim Kerimbekov Avatar asked Jan 18 '19 22:01

Nazim Kerimbekov


People also ask

What is a form in django?

Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way.

How does django form work?

Django's form handling uses all of the same techniques that we learned about in previous tutorials (for displaying information about our models): the view gets a request, performs any actions required including reading data from the models, then generates and returns an HTML page (from a template, into which we pass a ...

How can I get form data in django?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is get and post method in django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.


1 Answers

In short: the add_form is used when you construct a new CustomUser, whereas the simple form is used to change data for an existing CustomerUser object.

The UserAdmin class overrides the get_form(..) method, as we can see in the source code [GitHub]:

def get_form(self, request, obj=None, **kwargs):
    """
    Use special form during user creation
    """
    defaults = {}
    if obj is None:
        defaults['form'] = self.add_form
    defaults.update(kwargs)
    return super().get_form(request, obj, **defaults)

Now the get_form itself of the ModelAdmin class (the superclass of UserAdmin) invokes the modelform_factory(..) with a dictionary of attributes, as we can see in the source code [GitHub]:

def get_form(self, request, obj=None, change=False, **kwargs):
    # ...

    defaults = {
        'form': form,
        'fields': fields,
        'exclude': exclude,
        'formfield_callback': partial(self.formfield_for_dbfield, request=request),
        **kwargs,
    }

    if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
        defaults['fields'] = forms.ALL_FIELDS

    try:
        return modelform_factory(self.model, **defaults)
    except FieldError as e:
        raise FieldError(
            '%s. Check fields/fieldsets/exclude attributes of class %s.'
            % (e, self.__class__.__name__)
        )

That dictionary is updated with parameters that are passed as named arguments. So with form=self.add_form. This thus results in using a different form: the add_form.

This can be useful if we, for example, only want to be able to update specific fields when we update a CustomUser.

Note that only the UserAdmin has such get_form override, a ModelAdmin itself has no add_form to the best of my knowledge, and thus specifying such attribute will not make a difference.

like image 137
Willem Van Onsem Avatar answered Sep 30 '22 04:09

Willem Van Onsem