Use .get() to find correct kwargs field and avoid KeyError

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-15 14:51:57 -04:00 committed by GitHub
parent df584350b4
commit 54b3139e04
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
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)
@ -395,4 +395,4 @@ The following third party packages provide additional generic view implementatio
[UpdateModelMixin]: #updatemodelmixin
[DestroyModelMixin]: #destroymodelmixin
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related