Get Python logged in user ID

Asked

Viewed 661 times

1

I have a project in Python and Django. Where I have a REGISTRATION class, and in this table I would like to record in the column "Person" the ID of the user logged in the application, in the column "Events" record the event that he is registering, in which case I am using Slug, for access to this event.

class Inscricao(models.Model):
    pessoa = models.ForeignKey(User, verbose_name='usuario', on_delete=models.CASCADE)
    evento = models.ForeignKey(Evento, verbose_name='evento', on_delete=models.CASCADE)
    categoria = models.ForeignKey(Categoria, verbose_name='categoria', on_delete=models.CASCADE)
    numero = models.IntegerField(verbose_name='número', blank=True)
    data_inscricao = models.DateField(verbose_name='data de inscrição', blank=True)
    detalhe = models.TextField(max_length=100, verbose_name='observação', blank=True)
  • The view that receives this request is an instance Inscricao gets a request. In this request you take the necessary data (eg: request.user for logged in user) and instantiates your Model with the correct data.

2 answers

1

As already indicated, the request already contains the logged user. However, when you have to use for several objects, I use a class Abstract, and here I define the attributes that are always equal, that is, who created and when, who updated and when and reuse this as often as you want.

However, it involves installing a package, you can do so:

Pip install ai-Django-core

And defines the middleware so:

py Settings.

MIDDLEWARE = (
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'ai.middleware.current_user.CurrentUserMiddleware',
)

You start by adding a common.py file:

common py.

from django.conf import settings
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from ai.middleware.current_user import CurrentUserMiddleware
from django.contrib.contenttypes.fields import GenericRelation

class CommonInfo(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("Created By"), blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.SET_NULL, editable=False)
    created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True, editable=False)
    modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("Modified By"), blank=True, null=True, related_name="%(app_label)s_%(class)s_modified_on", on_delete=models.SET_NULL) 
    modified_on = models.DateTimeField(auto_now=True, blank=True, null=True)

    @staticmethod
    def get_current_user():
        """
        Get the currently logged in user over middleware.
        Can be overwritten to use e.g. other middleware or additional functionality.
        :return: user instance
        """
        return CurrentUserMiddleware.get_current_user()

    def set_user_fields(self, user):
        """
        Set user-related fields before saving the instance.
        If no user with primary key is given the fields are not set.
        :param user: user instance of current user
        """
        if user and user.pk:
            if not self.pk:
                self.created_by = user
            else:
                self.modified_by = user

    def save(self, *args, **kwargs):
        self.modified_on = now()
        current_user = self.get_current_user()
        self.set_user_fields(current_user)
        super(CommonInfo, self).save(*args, **kwargs)

    class Meta:
        abstract = True

py.models

from myapp.common import CommonInfo

class Inscricao(CommonInfo): # <= tens de adicionar aqui o CommonInfo ao invés do models.Model
    pessoa = models.ForeignKey(User, verbose_name='usuario', on_delete=models.CASCADE)
    evento = models.ForeignKey(Evento, verbose_name='evento', on_delete=models.CASCADE)
    categoria = models.ForeignKey(Categoria, verbose_name='categoria', on_delete=models.CASCADE)
    numero = models.IntegerField(verbose_name='número', blank=True)
    data_inscricao = models.DateField(verbose_name='data de inscrição', blank=True)
    detalhe = models.TextField(max_length=100, verbose_name='observação', blank=True)

0

The request object of the view, if it is only accessed with an authenticated user, contains the user instance in request.user.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.