Home > Software engineering >  How to show on template just a Model with Foreign Key Django?
How to show on template just a Model with Foreign Key Django?

Time:05-15

I'm getting on the template all the Router Model created. I mean if user A create a Router Model when I log in with user B I can see what user A create. how can I display only the user models created by user B? not the A or C. Just B.

I have this model:

class CustomUser(AbstractUser):
phone = models.IntegerField(null=True, blank=True)

class RouterModel(models.Model):
 ip = models.CharField(max_length=15)
 username = models.CharField(max_length=50)
 password = models.CharField(max_length=50)
 port = models.IntegerField()
 owner = models.ForeignKey('CustomUser', on_delete=models.CASCADE, )
 name = models.CharField(max_length=50)

 def __str__(self):
  return self.name

class Clients(models.Model):
 name = models.CharField(max_length=50)
 tcpIP = models.IntegerField()
 email = models.EmailField()
 phone = models.IntegerField()
 zone = models.CharField(max_length=50)
 owner = models.ForeignKey('RouterModel', on_delete=models.CASCADE, ) 

def __str__(self):
    return  self.name

class Tickets(models.Model):
 title = models.CharField(max_length=200)
 comment = models.TextField(max_length=500)
 owner = models.ForeignKey('Clients', on_delete=models.CASCADE) 

 def __str__(self):
    return self.title

and this view

class DashBoard(ListView):
 model = RouterModel
 template_name = 'templates/dashboard/dashboard.html'
 context_object_name = 'router_model'

template:

{% block content %}

{% if user.is_authenticated %}
    <h3>Hello {{ user.username }}</h3>

{% for router in object_list %}
    <h3>{{ router }}</h3>
    <h2>{{ router.ip }}</h2>
    <br>
{% endfor %}

{% endif %}

{% endblock content%}

CodePudding user response:

You can do it by writing this code in your template.

{% block content %}

{% if user.is_authenticated %}
    <h3>Hello {{ user.username }}</h3>

 {% for router in object_list %}
 {% if router.author == self.user %}
     <h3>{{ router }}</h3>
     <h2>{{ router.ip }}</h2>
    <br>
 {% endif %}
 {% endfor %}


 {% endif %}

{% endblock content%}

CodePudding user response:

You can also try this way

class DashBoard(ListView):
   model = RouterModel
   template_name = 'templates/dashboard/dashboard.html'
   context_object_name = 'router_model'    
   queryset = Publisher.objects.filter(owner=self.request.user)
               or 
   queryset = Publisher.objects.filter(owner=request.user)
  • Related