Elcid
Elcid

Reputation: 70

what is the difference between extra_context and get_context_data(**kwargs) in django CBVs

I'm using Django CBVs and confused about differences between extra_context Class attribute and get_context_data(**kwargs) method. Although according to docs you can use both but which one is better to use?

can anyone help me to clear the problem ???

I use this class attribute in a DetailView subclass and it worked .

Django 2.2 version .

Thanks.

Upvotes: 1

Views: 439

Answers (2)

Roderich25
Roderich25

Reputation: 76

I don't know if you still has this doubt, but I recently had an issue by using extract_context in a production environment, specifically on a AWS EC2 instance using Django 2.2 and Python 3.6, I thought that using a QuerySet on extra_context will update automatically in production as it did on dev environment but in case you need a QuerySet update in your context you better use get_context_data.

Bottom line if you need a fixed value use extra_context otherwise use get_context_data.

Upvotes: 1

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3038

They both do the same functionality, except that in get_context_data to get prev data you should call super and update that dict; cause you don't want to lose prev data in context.

But extra_context will do the same but no need to call super and you can call it in url like TemplateView.as_view(extra_context={'title': 'Custom Title'}).

So to sum up, extra_context is just a faster with less code to update your context data in CBV.
Also to note, extra_context will be used as an attribute, but get_context_data is the method for CBVs.

Upvotes: 0

Related Questions