如何解决单独的用户帐户
我想分隔站点中的打开会话,以便用户不能从另一个帐户删除/修改对象。如果有人可以解释我该怎么做,例如在这里使用删除功能。 这是我的代码:
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 %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。