Home > Net >  Django retrieve filter value in views.py
Django retrieve filter value in views.py

Time:02-10

I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).

Example:

models.py

class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name

views.py


def users(request):
    users= User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)

users.html

{% block content %}

<div>
    <table style="width:100%" >
        <thead >
            <tr>
                <th>Name</th>
                <th>E mail</th>
                <th>Address</th>
            </tr>
        </thead>
        {% for i in users%}
            <tr>
                <td>{{i.name}}</td>
                <td>{{i.email}}</td>
                <td>{{i.address}}</td>
            </tr>
        {% endfor %}
    </table>

</div>

{% endblock content%}

I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.

Any idea on how to proceed ?

CodePudding user response:

If I understood correctly, you could make a form like this

<form method="post">
    <label for="users">Choose a user:</label>
    <select name="users" id="users">
        {% for user in users %}
            <option value="{{ user.name }}">{{ user.name }}</option>
        {% endfor %}
    </select>
    <button id="submit" type="submit">Submit</button>

</form>

and then when submitted, get the value of selected option using like this

selected_user = request.POST.get('users')

or something along these lines

CodePudding user response:

In your html add select element and append users data first with <table> body empty.

<div>
    <select  id="user" name="user">
        {% for i in users %}
            <option value="{{i.id}}">{{i.name}}</option>
        {% endfor %}
    </select>
    <table id="userTable" style="width:100%" >
        <thead >
            <tr>
                <th>Name</th>
                <th>E mail</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

And in your script call new url using jQuery.ajax() with every .change() event of <select> element to get corresponsing user value with provided userid value and append data to the table. By this way you don't need to refresh the page and get your data with every change event.

<script>
    $('#user').on('change', function() {
        $.ajax({
            url: "/user/"   $(this).val(),
            method: 'GET',
            contentType : 'application/json',
            success: function (data) {
                var tr = '<tr><td>'  data.name  '</td><td>'  data.email  '</td><td>'  data.address  '</td></tr>';
                $('#userTable tbody').append(tr);
            },
            error : function(x) {
                console.log(x);
            }
        });
    });
</script>

Then in your urls.py add new url as

path('user/<str:user_id>/', views.user_data, name='user-data')

Add in your views.py

from django.shortcuts import get_object_or_404
from django.http import JsonResponse

def user_data(request, user_id):
    user = get_object_or_404(GuruUsers, id=user_id)
    user_data = {
        'name' : user.name,
        'email' : user.email,
        'address' : user.address
    }
    return JsonResponse(user_data, status=200)
  • Related