2023-07-04 14:24:55 +02:00

59 lines
2.0 KiB
Plaintext

This rule suggests avoiding the use of the built-in Python function "locals()" when passing context to a Django "render()" function.
== Why is this an issue?
Using the "locals()" function to pass context to a Django "render()" function can lead to security vulnerabilities and unexpected behavior. "locals()" returns a dictionary of the current local scope, including any sensitive information that may be present in the function's local namespace. This means that if "locals()" is used to pass context to "render()", sensitive data such as passwords, keys, and other secrets could be leaked.
Additionally, using "locals()" to pass context can make code more difficult to read and understand. It can also make it harder to maintain code over time.
== How to fix it
Instead of passing "locals()" to the "render()" function, explicitly define the context dictionary with only the variables that are required. This way, sensitive data is not accidentally included in the context, and the code is easier to read and maintain.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
def my_view(request):
username = "alice"
password = "p@ssw0rd"
context = locals()
return render(request, "my_template.html", context)
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def my_view(request):
username = "alice"
context = {"username": username}
return render(request, "my_template.html", context)
----
== Resources
=== Documentation
https://docs.djangoproject.com/en/4.1/topics/http/shortcuts/#render[Django render() function]
https://docs.python.org/3/library/functions.html#locals[Python locals() function]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use an explicit context instead of passing "locals()" to this Django "render" call.
Secondary location message (if locals() is assigned to a variable):
locals() is assigned to "{variable_name}" here
'''
endif::env-github,rspecator-view[]