[Django]-Queryset for current logged in user Django

1๐Ÿ‘

โœ…

Below code should work fine.

 {% for data in filter %}
     <li>{{ data.user.username }} - {{ data.user.get_full_name }}</li>
 {% endfor %}

 {% for Data in filter %}
    <tr>
      <td>{{ Data.user }}</td>
      <td>{{ Data.Date }}</td>
      <td>{{ Data.Status }}</td>
    </tr>
  {% empty %}

As you would not be using filters, so filters.py should be removed.
This will also not work. Make the changes as required.
{{ filter.form.as_table }}

๐Ÿ‘คRyuCoder

3๐Ÿ‘

There could be better ways to do this. As you are still learning below code does the trick.

@login_required
def search(request, *args, **kwargs):
    status_list = Data.objects.get(user=request.user)

    month = request.GET.get("month", None)
    year = request.GET.get("year", None)

    if month:
        status_list = status_list.filter(Date__month=month)

    if year:
        status_list = status_list.filter(Date__year=year)

    return render(request, 'users/data.html', {'filter': status_list})
๐Ÿ‘คRyuCoder

2๐Ÿ‘

You can simplify your code, django provides many helpers function to help to programmer.

in your views.py you can do:

@login_required
def search(request):
    status_list = Data.objects.all()
    status_filter = status_list.filter(user=request.user) //get current user id
    return render(request, 'users/data.html', {'filter': status_filter})
๐Ÿ‘คRicardo Prado

2๐Ÿ‘

status_list = Data.objects.get(user=self.request.user) 

is wrong as self is only used in class based views. No wonder it did not work.
Please try with the below code instead

status_list = Data.objects.filter(user=request.user) or 
status_list = Data.objects.get(user=request.user)

So, the final code will be like

@login_required
def search(request):
    status_list = Data.objects.get(user=request.user)
    render(request, 'users/data.html', {'filter': status_list})
๐Ÿ‘คRyuCoder

Leave a comment