How to get the currently logged in user’s user id in Django?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting. The current user is in request object, you can get it by: def sample_view(request): current_user = request.user print current_user.id request.user will give you a User object representing the currently logged-in user. If a user isn’t currently logged in, request.user will be … Read more

How to use permission_required decorators on django class-based views

There are a few strategies listed in the CBV docs: Decorate the view when you instantiate it in your urls.py (docs) from django.contrib.auth.decorators import login_required urlpatterns = [ path(‘view/’,login_required(ViewSpaceIndex.as_view(..)), … ] The decorator is applied on a per-instance basis, so you can add it or remove it in different urls.py routes as needed. Decorate your … Read more

In Django, how do I check if a user is in a certain group?

Your User object is linked to the Group object through a ManyToMany relationship. You can thereby apply the filter method to user.groups. So, to check if a given User is in a certain group (“Member” for the example), just do this : def is_member(user): return user.groups.filter(name=”Member”).exists() If you want to check if a given user … Read more

Having Django serve downloadable files

For the “best of both worlds” you could combine S.Lott’s solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you’ve set up mod_xsendfile, integrating with your view takes a few lines of code: from django.utils.encoding import smart_str response … Read more

Extending the User model with custom fields in Django

The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property. Extending the existing User model … If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)