Raf Rasenberg
Raf Rasenberg

Reputation: 684

How to query only the fields of the logged in user in Django?

So I use a model which is linked to my custom user (AbstractUser) in Django. I want to loop over all the objects of the current logged in user that belong to him.

So these are the models:

class CustomUser(AbstractUser):
    # Define all the fields
    company             = models.CharField(blank=True, null=True, max_length=150, unique=True)
    email               = models.EmailField(blank=True, null=True)
    username            = models.CharField(blank=True, null=True, max_length=150)
    first_name          = models.CharField(blank=True, null=True, max_length=150)
    last_name           = models.CharField(blank=True, null=True, max_length=150)
    phone_number        = models.CharField(max_length=15, blank=True, null=True)
    kvk_number          = models.IntegerField(blank=True, null=True)
    vat_number          = models.CharField(blank=True, null=True, max_length=150)
    customer_type       = models.CharField(max_length=1, choices=CUSTOMER_CHOICES, null=True, blank=True) # Choices are defined before the model

    # Username is required here otherwise createsuperuser will throw a error. We define the usernamefield here as the email
    REQUIRED_FIELDS = ['username', 'email']
    USERNAME_FIELD = 'company'

    def __str__(self):
        return self.company

class UserLinks(models.Model):
    # Define all the fields
    user                = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
    name                = models.CharField(max_length=2, choices=LINK_CHOICES, null=True, blank=True)
    link                = models.URLField(blank=True, null=True)
    login_name          = models.CharField(blank=True, null=True, max_length=150)
    password            = models.CharField(blank=True, null=True, max_length=150)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "User link"
        verbose_name_plural = "User links"

And this is my view:

def get(self, request):
        user = CustomUser.objects.all()
        return render(request, self.template_name ,{'user': user})

Then when I want to loop through the objects through the foreingkey I use:

{% for entry in user %}
{{ entry.company  }}
{{ entry.first_name }}

{% for a in entry.userlinks_set.all %}
{{ a.name }}
{{ a.link }}
{% endfor %}

{% endfor %}

However now I am displaying all the objects, but I only want to display the objects of the current logged in user, how to do this?

Upvotes: 0

Views: 270

Answers (2)

Dimitris Kougioumtzis
Dimitris Kougioumtzis

Reputation: 2439

You can access your logged in user via request in template

{% if not request.user.is_anonymous %}
   {{request.user.company}}
   {{request.user.first_name}}
   {% for link in request.user.userlinks_set.all %}
      {{link.name}}
      {{link.link}}
   {% endfor %}
{% endif %}

Upvotes: 0

ivissani
ivissani

Reputation: 2664

You can access the currently logged-in user at

request.user

although you should consider that if a user is not logged in this will return AnonymousUser. You can prevent this by wrapping your view with a login_required decorator.

You can change your view code in the following way:

def get(self, request):
    return render(request, self.template_name ,{'user': request.user})

and your template code should look like

{{ user.company  }}
{{ user.first_name }}

{% for a in user.userlinks_set.all %}
    {{ a.name }}
    {{ a.link }}
{% endfor %}

Upvotes: 1

Related Questions