mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-25 19:14:01 +03:00
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) ```
This commit is contained in:
parent
5bf338ea88
commit
c7acdd6006
|
@ -335,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
|
|||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_fields:
|
||||
if self.kwargs[field]: # Ignore empty fields.
|
||||
if self.kwargs.get(field): # Ignore empty fields.
|
||||
filter[field] = self.kwargs[field]
|
||||
obj = get_object_or_404(queryset, **filter) # Lookup the object
|
||||
self.check_object_permissions(self.request, obj)
|
||||
|
|
Loading…
Reference in New Issue
Block a user