8000 Use .get() to find correct kwargs field and avoid KeyError (#8607) · encode/django-rest-framework@c7acdd6 · GitHub
[go: up one dir, main page]

Skip to content

Commit c7acdd6

Browse files
authored
Use .get() to find correct kwargs field and avoid KeyError (#8607)
In the "Creating custom mixins" documentation, the code example recommends using ```python if self.kwargs[field] ``` However, if the correct field is not present in kwargs, a KeyError arises. A more secure option is tu use .get() to validate that the field is contained in the kwargs dictionary: ```python if self.kwargs.get(field) ```
1 parent 5bf338e commit c7acdd6

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

docs/api-guide/generic-views.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
335335
queryset = self.filter_queryset(queryset) # Apply any filter backends
336336
filter = {}
337337
for field in self.lookup_fields:
338-
if self.kwargs[field]: # Ignore empty fields.
338+
if self.kwargs.get(field): # Ignore empty fields.
339339
filter[field] = self.kwargs[field]
340340
obj = get_object_or_404(queryset, **filter) # Lookup the object
341341
self.check_object_permissions(self.request, obj)

0 commit comments

Comments
 (0)
0