Answer the question
In order to leave comments, you need to log in
Django. How to prevent a user from editing other people's posts?
Hello. At the moment, I can delete and edit my own and other people's ads, but how can I prevent others from changing them? Also, an unregistered user can also delete and modify ads if he goes to the address, although I have hidden the edit buttons if the user is not in the system.
Here is the view:
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
listing.delete()
messages.success(request, 'Объявление удалено!')
return redirect('dashboard')
def listing_edit(request, listing_id):
form = ListingForm(instance = Listing.objects.get(id = listing_id))
if request.method == "POST":
form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id))
if form.is_valid():
listing = form.save()
messages.success(request, 'Объявление изменено!')
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {
'form': form
})
def listing_add(request):
form = ListingForm()
if request.method == "POST":
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
listing = form.save(commit=False)
listing.realtor = request.user
listing.save()
messages.success(request, 'Объявление добавлено!')
return redirect('dashboard')
return render(request, 'listings/listing_add.html', {
'form': form
})
{% if user.is_authenticated %}
<a href="{% url 'listing_edit' listing.id %}" class="btn btn-secondary mb-4">
<h5><i class="fas fa-edit"> Редактировать</i></h5></a>
<a href="{% url 'listing_delete' listing.id %}" class="btn btn-danger mb-4">
<h5><i class="fa fa-trash-alt"> Удалить</i></h5></a>
{% endif %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question