How to catch the current user in the Django model?

Asked

Viewed 958 times

2

Hello,

I’m creating a Django application and I have a model with the Newdemand class in which I need that when the user creates a demand, the name of the guy is saved in a field.
Here my class:

class NewDemand(models.Model):

    name = models.CharField(max_length=150)
    date_created = models.DateTimeField(auto_now_add=True, blank=True)
    date_max = models.DateField(db_index=True)
    requester_user = models.ForeignKey(User)
    demand_desc = models.TextField()

    def __str__(self):
        return str(self.name)

I tried to put a models.ForeugnKey(User) but on the admin page appears a field with a menu that contains all users. I want the user name to go straight to the bank without having to appear on the admin page when inputar the data.

  • the way you’re going to make it work the way you want it to, it depends on a few points, among them: are you going to be using admin for this new demand creation operation? If yes, you will have to use the logic that Marcelo Lino spoke in the answer below, along with some modifications in admin. Then you can take a look at doc to see which override method will best suit your problem

  • This new Demand can be created by any user, just be logged in. I’m using the Class-Based View scheme, so I’m saving

1 answer

2


You apply this logic in the view:

def new_demand(request):
    user = request.user.id
    demand = NewDemand(name, date_created, date_max, user, demand_desc)

So you take the ID of the logged in user and pass as parameter to your demand.

Browser other questions tagged

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