Queryset for current logged in user Django

前端 未结 4 1580
时光说笑
时光说笑 2021-01-14 06:22

I am doing queryset with my model. Now the queryset is displaying all the data in my html page. But I want to display only the logged in users data.

models.p

相关标签:
4条回答
  • 2021-01-14 07:08

    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})
    
    0 讨论(0)
  • 2021-01-14 07:16
    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})
    
    0 讨论(0)
  • 2021-01-14 07:18

    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 }}

    0 讨论(0)
  • 2021-01-14 07:25

    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})
    
    0 讨论(0)
提交回复
热议问题