S
S
Stanislav Konovalov2019-03-09 20:04:14
Django
Stanislav Konovalov, 2019-03-09 20:04:14

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

Here are the buttons, maybe here you need to redo the condition:
{% 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 %}

Tried different conditions, but still doesn't work. Who will have time, tell me, please. And, in general, in addition to my question, in representations, how is all this done most correctly? Maybe we need to write some more exceptions so that everything works more correctly and smoothly, so that it is safer.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question