【发布时间】:2015-10-22 00:45:55
【问题描述】:
我写了一个函数,允许用户删除他在博客网站上的文章。问题是,如果他对 url 稍加玩弄,他可以访问另一篇文章并将其删除。
使用 django 避免此类情况的常用策略是什么?
这是我为函数编写的代码:
views.py
def delete_article(request, id):
deleted = False
logged_user = get_logged_user_from_request(request) #that line allow to ensure that the user is connected. I use the session to achieve that instead of extending the User model
offer = get_object_or_404(Offer, id=id)
if request.method == 'POST':
offer.delete()
deleted = True
return render(request, 'offers/delete_article.html', locals())
urls.py
urlpatterns = patterns('article.views',
url(r'^send_article$', 'send_article', name='send_article'),
url(r'^my_articles$', 'show_my_articles', name='my_articles'),
url(r'^article/(?P<id>\d+)$', 'read', name='read'),
url(r'^articles$', 'show_articles', name='articles'),
url(r'^search_article$', 'search', name='search'),
url(r'^delete_article/(?P<id>\d+)$', 'delete_offer', name='delete_offer'),
)
delete_article.html
{% if not deleted %}
Hey, are you sure you want to delete {{ article.title }}?
<form method="POST">
{% csrf_token %}
<button type="submit" class="deleting_offer_button">delete</button>
</form>
{% elif deleted %}
<p>the article was successfully deleted</p>
<a href="/">get back to the homepage</a><br />
{% endif %}
如您所见,如果用户更改了url中id的数字,当他被引导到删除确认页面时,他可以删除其他文章。
网站管理员正在做什么来确保用户不会干扰其他用户的对象?
【问题讨论】:
标签: django forms model django-urls