Search code examples
javascriptdjangodjango-1.9

Check if requested user is owner in django


I have developed an app which is about storing hotel information. I want an edit and delete feature too but edit button should be visible only to that user who has registered hotel not to all the authenticated user. I want to pass if requested user is the one who has registered hotel through javascript argument. How can i check this?

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>

views

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)

Models

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"))

Solution

  • Well what you can do is add user field or say hotelOwner in your models.py like

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

    now in your data object inside javascript you should do following

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