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

时间:2016-04-29 05:04:36

标签: javascript django django-1.9

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

1 个答案:

答案 0 :(得分:0)

您可以做的是在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 %}