单独的用户帐户

问题描述

我想分隔站点中的打开会话,以便用户不能从另一个帐户删除/修改对象。如果有人可以解释我该怎么做,例如在这里使用删除功能。 这是我的代码

models.py

class User(AbstractUser): ##abstract user model
    pass

class Auction(models.Model): ##these are the objects
    user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True)
    name = models.CharField(max_length=64)
    img = models.ImageField(upload_to='listing_image',null=True,default="/static/default_image.jpg")
    description = models.TextField(blank=True)
    starting_bid = models.IntegerField()
    category = models.ForeignKey(Category,related_name="auctions",null=True)

views.py

@login_required(login_url="login")
def delete(request,id):
    auction = get_object_or_404(Auction,id=id)
    if request.method == "POST":
        auction.delete()
        return redirect ('index')
    return render(request,"auctions/delete.html",{
        "auction": auction
    })

html:

 {{auction.user}}
    <h1>{{ auction.name }}</h1>
    <img src="{{ auction.img.url }}" width="600"> 
            <h5>Starting price: ${{ auction.starting_bid }}</h5>
            <form method="POST" enctype="multipart/form-data">
                {%csrf_token%}
                <button type="submit" class="btn btn-primary">Place a New Bid</button>
                {{form.as_p}}
            </form>
            {%for bid in bids%}
            <h3>${{ bid.new_bid}}</h3>
            {%empty%}
            No offers yet.
            {%endfor%}
            {{auction.description}}
          
        <h2>Comments</h2>
    <ul>
        <p><a href="{% url 'new_comment' auction.id %}" class="btn btn-secondary">New Comment</a></p>

        {%for comment in comments%}
            <li>{{comment.user}} - {{comment.created_on}}
                <p><h4>{{comment.body}}</h4></p>              
            </li>
        {%empty%}
            <li>No comments yet.</li>
        {%endfor%}
    </ul>
    <p><a href="{% url 'edit' auction.id %}" class="btn btn-secondary">Edit</a>
    <a href="{% url 'delete' auction.id %}" class="btn btn-secondary">Delete</a></p>

解决方法

您还可以对用户进行过滤:

@login_required(login_url='login')
def delete(request,id):
    auction = get_object_or_404(Auction,id=id,user=request.user)
    if request.method == 'POST':
        auction.delete()
        return redirect ('index')
    return render(request,'auctions/delete.html',{
        'auction': auction
    })

如果.user中的Auction不是登录用户,则这将返回HTTP 404错误,因此他们将无法删除该对象。

在模板中,您需要检查用户是否已登录才能显示按钮。但是,即使您以某种方式显示按钮,如果您进行相应的过滤,用户也将无法触发逻辑:

{% if user == auction.user %}
<p><a href="{% url 'edit' auction.id %}" class="btn btn-secondary">Edit</a>
<a href="{% url 'delete' auction.id %}" class="btn btn-secondary">Delete</a></p>
{% endif %}