Reputation: 41
url to display DB data is
url(r'^editinvoice/(?P<pk>\d+)/$',views.edit_invoice,name='editinvoice'),
template.html code that redirects to this page is
<a href="{% url "editinvoice" pk=invoices.id %}">{{ invoices.invoice_number }}</a></td>
invoices.id
is foreign key of above DB table.
The link passes correct pk and details are correctly displayed. However if I just change the id in url, I can see information even if I am not the user related to it. What should be done that information should be available to logged in user only if user if owner of it.
Upvotes: 0
Views: 60
Reputation: 25559
For your views method edit_invoice
, use @login_required
decorator.
In the method you would raise 403 error:
from django.core.exceptions import PermissionDenied
def edit_invoice(request, pk):
invoice = Invoice.objects.get(pk=pk)
if invoice.user != request.user:
raise PermissionDenied
See django docs about @login_required
.
Also see django doc about PermissionDenied.
Edit:
Yea having a "does not exist" makes more sense. The most common one is to raise 404 exception, as if user is visiting a url that doesn't exist:
from django.http import Http404 raise Http404
Upvotes: 1