mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 00:19:53 +03:00
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:
parent
df584350b4
commit
54b3139e04
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue
Block a user