Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AttributeError "object has no attribute 'pk'" if "request.user" is not a Django model #80

Closed
mlegner opened this issue Jun 24, 2022 · 5 comments · Fixed by #107
Closed
Assignees

Comments

@mlegner
Copy link

mlegner commented Jun 24, 2022

In my Django application, users are not (always) associated with a model. In this case, I get an AttributeError in django_structlog/middlewares/request.py#L108 because the request.user does not have an attribute pk.

A possible solution would be to use the pk attribute if it exists and otherwise just take the str of the user:

-            user_id = request.user.pk
+            user_id = getattr(request.user, "pk", str(request.user))
@jrobichaud
Copy link
Owner

I'd probably have to do it this way:

-            user_id = request.user.pk
+            if hasattr(request.user, "pk"):
+                user_id = request.user.pk          
+            else:
+                user_id = str(request.user)

There is a subtle difference getattr requires str(request.user) to be evaluated at every request, and it will serialize the user even though it has a pk.

@jrobichaud
Copy link
Owner

I might just have to prevent the crash and let the developers bind what they need using the signals.

@jrobichaud
Copy link
Owner

jrobichaud commented Aug 2, 2022

Not everyone in the same situation as you will want to bind the user like you suggested.

@mlegner
Copy link
Author

mlegner commented Aug 2, 2022

I might just have to prevent the crash and let the developers bind what they need using the signals.

Not everyone in the same situation as you will want to bind the user like you suggested.

Fully agree. My suggestion was just the simplest fix that I could think of. Just keeping the user_id empty and letting the developers assign it would work also.

@jrobichaud
Copy link
Owner

fixed in 3.0.1
See the doc for the signals: to bind your custom user_id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants