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

Check if requested user is owner in django

本文关键字:所有者 django 用户 请求 检查 是否是      更新时间:2023-09-26

我开发了一款关于存储酒店信息的应用程序。我也想要一个编辑和删除功能,但编辑按钮应该只对注册酒店的用户可见,而不是对所有经过身份验证的用户可见。如果请求的用户是通过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"))

你可以在你的模型中添加用户字段或说hotelOwner.py,比如

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

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

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