姜戈。如何防止其他用户编辑和删除我的列表?

Django. How can I prevent another user from editing and deleting my listings?

请帮助我实施这些功能,以便其他用户无法删除或编辑我的广告。目前只有未注册用户不能编辑和删除。

@login_required
def listing_delete(request, listing_id):
    listing = Listing.objects.get(id=listing_id)
    listing.delete()
    return redirect('index')

@login_required
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()
            return redirect('listing', listing_id)

    return render(request, 'listings/listing_edit.html', {'form': form})

@login_required
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.realtor
            listing.save()
            return redirect('dashboard')

    return render(request, 'listings/listing_add.html', {'form': form})



 class Listing(models.Model):
            realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')

...

class Realtor(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')

您只需检查发出 POST 请求的用户是否为房源的作者(房地产经纪人):

@login_required
def listing_edit(request, listing_id):
    listing = Listing.objects.get(id=listing_id)  # avoid multiple database calls
    form = ListingForm(instance=listing)
    if request.method == "POST" and request.user == listing.realtor.user:
        form = ListingForm(request.POST, request.FILES, instance=listing)    
        if form.is_valid():                 
            listing = form.save()
            return redirect('listing', listing_id)

    return render(request, 'listings/listing_edit.html', {'form': form})

同样适用于删除视图。

@login_required
def listing_delete(request, listing_id):
    listing = Listing.objects.get(id=listing_id)
    if request.user == listing.realtor.user:
        listing.delete()
    return redirect('index')