Search code examples
pythondjangodjango-modelsdjango-formsdjango-authentication

Add username or any user authentication related field like first name, last name etc in model forms


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 restaurant name in models directly(user name in this case) instead of taking input thorough forms every time.Also if possible if can take name from another field like this which is part of login system?

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 I understand well what you want, I think you need a Foreign Key Field pointing to the User infromation.

    field_name= models.ForeignKey(User, help_text="", blank=True, null=True, on_delete=models.CASCADE)
    

    Then you can access all the data from a user instance in views, for example:

    this_menu = menu_details.objects.get(pk=1)
    
    restaurant_name = this_menu.field_name.first_name
    restaurant_email = this_menu.field_name.email
    

    Or in templates:

    {{ this_menu.field_name.first_name }}
    {{ this_menu.field_name.email}}