如何仅在Django中打印当前登录的用户数据?

时间:2018-11-17 11:08:24

标签: python django django-models django-templates django-views

from django.db import models
from django.contrib import auth
from django.urls import reverse
from django.contrib.auth.models import User

models.py

class placement(models.Model):
    user=models.ForeignKey(User,related_name='placeid', null=True, default=None,on_delete=models.CASCADE)
    name=models.CharField(max_length=150, blank=True, null=True)  
    ad_space=models.CharField(max_length=100, blank=False, null=False)  
    PID_TYPE = (  
        ('FN','FORMAT_NATIVE'),  
        ('FNB','FORMAT_NATIVE_BANNER'),  
        ('FI','FORMAT_INTERSTITIAL'),  
        ('FB','FORMAT_BANNER'),  
        ('FMR','FORMAT_MEDIUM,RECT'),  
        ('FRV','FORMAT_REWARDED_VIDEO'),  
    )

    format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False)
    pid=models.CharField( max_length=50,default='',blank=False, null=False)
    cpm=models.IntegerField(default=0,blank=False, null=False)
    ADS_TYPE=(
        ('FB','FACEBOOK'),
        ('G','GOOGLE'),
    )
source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False)
    comments=models.TextField(default='',blank=False, null=False)  
    objects=models.Manager()


    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("dashapp:disp")

views.py

class createPlace(LoginRequiredMixin,CreateView):  
    fields=('name','ad_space','format','pid','cpm','source','comments')
    model=placement  
    template_name='createpl.html'  
    def form_valid(self, form):  
        form.instance.user = User.objects.get(id = self.request.user.id)  
        return super(createPlace, self).form_valid(form)  


class Idlist(LoginRequiredMixin,ListView):

    model=placement
    template_name='placement_list.html'
    def get_queryset(self):
        query_set=super().get_queryset()
        return query_set.filter(placement.objects.filter(user=self.request.user))

现在我必须在Idlist的{​​{1}}类中进行什么查询才能仅获取当前登录的用户相关数据。而我在Views.py中执行的查询给我的错误是

Idlist

我对此并不陌生,任何帮助对我来说都是最好的。请看看并帮助新手

1 个答案:

答案 0 :(得分:0)

您应该过滤查询集本身,例如:

class Idlist(LoginRequiredMixin,ListView):

    model=placement
    template_name='placement_list.html'

    def get_queryset(self):
        query_set=super().get_queryset()
        return query_set.filter(user=self.request.user)

因此,我们在.filter(..)上应用query_set,这样我们只能获得placementuser的{​​{1}}。