Skip to content
Advertisement

Django: how to check a guest or a page owner entered the page

I am doing a social network, I have one profile template for all users, how to check a guest or a page owner entered the page, {% if profile.user.username == None%} tried to write like this in html but it works strangely.For users, I use the Profile model

  class Profile(models.Model):
    first_name = models.CharField(max_length=200, blank=True)
    last_name  = models.CharField(max_length=200, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.EmailField(max_length=150, blank=True)
    country = models.CharField(max_length=100, blank=True)
    avatar = models.ImageField(default = 'avatar.svg', upload_to = 'avatars/%Y/%m/%d', blank=True)
    friends = models.ManyToManyField(User, blank=True, related_name='friends')
    update = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user}-{self.created}"
    
    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
        instance.profile.save()

Advertisement

Answer

try this

{% if profile.user == request.user %}
   # i am user
{% else %}
   # i am guest
{% endif %}

or

{% if profile.user.username == request.user.username %}
   # i am user
{% else %}
   # i am guest
{% endif %}

https://docs.djangoproject.com/en/3.1/topics/templates/

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement