Search code examples
pythondjangodjango-modelsdjango-formsdjango-users

Django get username of logged in user and pass it to models


I am creating a project in django in which I have two diff users i.e. Customers and restaurants. I am creating a model for Menu in which I want add to add user name of logged in user to restaurant name in models. Is there anyway to do this. I have searched through the net got answers like foreign key but not able to implement. Also I need username in views to search from database according to username. Models.py

class menu_details(models.Model):
    restaurant_name = models.CharField(blank=True, max_length=20)
    dish_name = models.CharField(blank=True, max_length=20)
    dish_type = models.CharField(max_length=10, choices=food_type, default='veg')
    price = models.CharField(blank=True, max_length=20)
    description = models.TextField(blank=True, max_length=5000)
    image = models.ImageField0(blank=True)

    class Meta:
        db_table = "menu_details"

Solution

  • If you want to have username of already logged in user in a view you can use user object from request:

    from .models import menu_details
    
    
    def my_view(request):
        if request.user.is_authenticated:
            user = request.user # user object from the person who is visiting
            username = user.username # username of logged in user
            menu_details.objects.filter(restaurant_name=username) # getting the menu using restaurant