What is context_object_name=None in django class CreateView?

Viewed 33

Get the name to use for the object. For context_object_name=None

Doc:For example Article will be article Why we use context_object_name in createview.We don't have a object,we just have a simple form to show users.

def get_context_object_name(self, obj):
    """Get the name to use for the object."""
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

Please somebody help me???

1 Answers

In any class based view, the default object name, in case of a single object is object and in case of multiple objects is object_list. These are the context variables you use in your template that renders the view.

For example, in case of a single object, you will use them as

{{object}}
...
{{object.pk}} 

and in case of multiple items:

{% for i in object_list %}
...do something...
{% endfor %}

When you supply a context_object_name in your view, the variable named object will be replaced by that.

For example: If you set context_object_name='place', then in your template, you can use the instance as {{place}} instead of {{object}}

Source: https://docs.djangoproject.com/en/4.1/topics/class-based-views/generic-display/#making-friendly-template-contexts

Related