I want to filter the clients of every agent individually. Django

188
May 31, 2021, at 2:40 PM

I'm creating a view where I can show all the clients of specific agents via there PK.

I am not having error when I use Client.objects.all() as the queryset and it gets to show all of the clients. however I don't know how to filter clients via select pk for Url.

Please help.

Here's my Views.py

class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
    template_name = "agents/agent_client_list.html"
    context_object_name ="clients"
    def get_queryset(self):
        user= Agent.objects.get(pk=id)
        queryset = Client.objects.filter(user=user, agent__isnull=False).order_by('company_name')
        return queryset

My Urls.py:

from django.urls import path
from .views import AgentListView, AgentCreateView, AgentDetailView, AgentUpdateView, AgentDeleteView, AgentClientListView
app_name = 'agents'
urlpatterns = [
    path('', AgentListView.as_view(), name='agent-list'),
    path('<int:pk>/', AgentDetailView.as_view(), name='agent-detail'),
    path('<int:pk>/update/', AgentUpdateView.as_view(), name='agent-update'),
    path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'),    
    path('<int:pk>/agent_client_list', AgentClientListView.as_view(), name='agent_client_list'),   
    path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'),   
    path('create/', AgentCreateView.as_view(), name='agent-create'),
]

Here's the Client Model

class Client(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=20)
    mobile_number = models.CharField(max_length=12)
    email = models.EmailField(null=True, blank=True)
    
    organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE)
    agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL)
    category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL)
    company_name = models.CharField(max_length=50 , default=None)
    street_address = models.CharField(max_length=50 , default=None) 
    baranggay = models.CharField(max_length=50 , default=None)
    city = models.CharField(max_length=50 , default=None)
    region = models.CharField(max_length=50 , default=None)
    date_added = models.DateTimeField(auto_now_add=True)
    phoned = models.BooleanField(default=False)
    special_files = models.FileField(blank=True , null=True)

    def __str__(self):
        return self.company_name

And HTML:

{% extends "base.html" %}
{% block content %}
<section class="text-gray-600 body-font overflow-hidden">
    <div class="container px-5 py-24 mx-auto">
      <div class="lg:w-4/5 mx-auto flex flex-wrap">
        <div class="lg:w-1/2 w-full mx-auto">
            <h2 class="text-sm title-font text-gray-500 tracking-widest">AGENT</h2>
            <h1 class="text-gray-900 text-3xl title-font font-medium mb-4">{{ agent.user.first_name }} {{ agent.user.last_name }}</h1>
            <div class="flex mb-4">
              <a href="#" class="flex-grow text-blue-500 border-b-2 border-blue-500 py-2 text-lg px-1">
                Description
            </a>
            </a>
            <a href="#" class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1">
                Update
            </a>
        </div>
        <div class="flex flex-col w-full">
            <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                        <th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">Client Name</th>
                        <th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Point Person</th>
                        <th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Date Added</th>
                        <th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Client Status</th>
                    </thead>
                        {% for client in clients %}
                            <tbody>
                                <tr>
                                    <div>
                                        <td class="mt-3"><a href="{% url 'clients:client-detail' client.pk %}" class="text-xl hover:text-blue-500">{{ client.company_name }}</a></td>
                                        <td class="mt-3">{{ client.first_name }} {{ client.last_name }}</td>
                                        <td class="mt-3">{{ client.date_added }}</td>
                                        <td class="mt-3 px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> {{ client.category }}</td>
                                    </div>
                                </tr>
                            </tbody>
                        {% endfor %}
                    </table>
                    </div>
                </div>
            </div>        
{% endblock content %}

However I get this error:

TypeError at /agents/7/agent_client_list
Field 'id' expected a number but got <built-in function id>.
Request Method: GET
Request URL:    https://techcrm.herokuapp.com/agents/7/agent_client_list
Django Version: 3.1.4
Exception Type: TypeError
Exception Value:    
Field 'id' expected a number but got <built-in function id>.
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/models/fields/__init__.py, line 1776, in get_prep_value
Python Executable:  /app/.heroku/python/bin/python
Python Version: 3.9.2
Python Path:    
['/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python39.zip',
 '/app/.heroku/python/lib/python3.9',
 '/app/.heroku/python/lib/python3.9/lib-dynload',
 '/app/.heroku/python/lib/python3.9/site-packages']
Server time:    Mon, 31 May 2021 15:22:53 +0800

Thank you very much in advance!

Answer 1

You can not use id in the get_queryset, since this refers to the builtin id function, not the primary key of the object.

You can obtain the URL parameters with self.kwargs:

class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
    template_name = 'agents/agent_client_list.html'
    context_object_name ='clients'
    def get_queryset(self):
        agent = Agent.objects.get(pk=self.kwargs['pk'])
        return Client.objects.filter(agent=agent, agent__isnull=False).order_by('company_name')

It might be better to directly filter on the primary key however, and thus work with one query instead of two:

class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
    template_name = 'agents/agent_client_list.html'
    context_object_name ='clients'
    def get_queryset(self):
        return Client.objects.filter(agent_id=self.kwargs['pk'], agent__isnull=False).order_by('company_name')
Rent Charter Buses Company
READ ALSO
Vue.js disable blank comments

Vue.js disable blank comments

Usually, when Vuejs hides an element through v-if, a comment is left in its place

128
How do I get the correct value in dataframe while webscraping?

How do I get the correct value in dataframe while webscraping?

I am trying to get value from websraping however, I am not able to construct correct class for the value

47
Delete Multiple DB rows and Images with Same title

Delete Multiple DB rows and Images with Same title

I am trying to delete multiple rows based on 'slug' column using CodeigniterForm DB all rows are deleted but the problem is with Images

107
Click count using JavaScript for many buttons with default value &#39;0&#39;

Click count using JavaScript for many buttons with default value '0'

I want to use a click count function in JavaScript to measure the number of clicks on a button in otreeThe data should be stored in the database using a hidden input field

145