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:
Daian Gan 2022-08-31 05:18:17 -04:00 committed by GitHub
parent 5bf338ea88
commit c7acdd6006
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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 queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {} filter = {}
for field in self.lookup_fields: 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] filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter) # Lookup the object obj = get_object_or_404(queryset, **filter) # Lookup the object
self.check_object_permissions(self.request, obj) self.check_object_permissions(self.request, obj)