[ Getting logged in User's Profile in Django without repeating request.user a lot? ]
The application I am writing in Django requires me to get a UserProfile model object (which has a one-to-one relationship with the standard Django User object) in a lot of the views. To get the user's profile, I end up repeating something like this quite a bit in all the different views:
user_profile = UserProfile.objects.get(user=request.user)
user_profile = UserProfile.objects.get(user=self.request.user)
I know good software engineering principles say don't repeat yourself (DRY), so I was wondering if there was a good way to encapsulate the code above in a separate method or if it's fine to keep it the way it is.
Thanks in advance for any help!
Add a related name to your UserProfile in
class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') about = models.TextField(default='')
Then in your
views.py, reference it with
request.user.profile.about = 'abc' request.user.profile.save()
Or make it shorter
p = request.user.profile p.about = 'abc' p.save()