检查请求的用户是否是 django 中的所有者

Check if requested user is owner in django

我开发了一款用于存储酒店信息的应用程序。我也想要编辑和删除功能,但编辑按钮应该只对已注册酒店的用户可见,而不是对所有经过身份验证的用户可见。如果请求的用户是通过 javascript 参数注册酒店的用户,我想通过。我该如何检查?

hotel_detail.html

<script type="text/javascript">

    var data = {
      pk:{{ instance.pk }},
      isUserAuthenticated:{% if request.user.is_authenticated %}true{% else %}false{% endif %},
      user:'{{request.user.username}}'
    }
    console.log('owner is', data.user);
    console.log(data);
    $(function() {
      app.showRoomDetail("hotelDetail",data);

    });

</script>

观看次数

def hotel_detail(request, pk):
    instance = get_object_or_404(Hotel, pk=pk)
    context = {
        'pk':instance.pk,
        'instance':instance
    }
    return render(request,'rentals/hotel_detail.html',context)

型号

class Hotel(models.Model):
    ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True,
        help_text=_("Owner's Full Name"))
    email = models.CharField(max_length=120,blank=True,null=True)
    phoneNumber = models.PositiveIntegerField(blank=False,null=True,
        help_text=_("Phone number of contact person"))
    hotelName =  models.CharField(_("Hotel Name"), max_length=255, blank=False,null=True)
    slug = models.SlugField(unique=True,blank=True,null=True)
    summary = models.TextField(max_length=500, blank=True,null=True,help_text=_("Description of the Hotel"))
    location = models.CharField(_("location"),max_length=10,null=True)
    room = models.PositiveIntegerField(_("No of Rooms"), blank=False, null=True,
        help_text=_("Number of bedrooms available"))
    price = models.PositiveIntegerField(blank=False,null=True,
        help_text=_("Price per room"))

那么你可以做的是添加用户字段或在你的 models.py 中说 hotelOwner 就像

hotelOwner = models.ForeignKey(User) # note you need to import user model

现在在 javascript 中的数据对象中,您应该执行以下操作

user:{% if request.user == instance.renter %}true{% else %}false{% endif %}