因此,我有一个显示表的页面,并且在每一行上都有一个名为删除的按钮,该按钮将删除该行以及数据库中与该行相关的所有信息。
删除按钮可以正常工作,因为它可以删除数据库中的信息,但是我想将其重定向到显示表的页面。
问题在于,要访问显示表格的页面,需要通过使用POST方法进行搜索来完成。我想到了将在搜索时保存的参数保存在全局变量中,然后再次呈现表页面,并使用初始搜索中保存的参数,虽然可以,但是我不希望这样:它改变了我单击删除后重定向到的URL,它不会手动更新页面,因此我仍然看到已删除的行,如果手动刷新它,将无法再看到已删除的行。
views.py:
def character_delete (request):
if request.method == "GET":
Id = request.GET.get("idChar")
char = Characterweapons.objects.all().filter(characterid=Id).delete()
char2 = Characters.objects.all().filter(characterid=Id).delete()
global cont
return render(request, 'users/characters_found_table.html',cont)
有什么想法吗?
谢谢!
答案 0 :(得分:1)
任何状态更改操作(如删除)都应以POST的形式发生,而任何读取操作应以GET的形式发生。另外,在任何成功的POST之后,您都需要进行重定向,因此如果用户按下“后退”按钮,该帖子将不会再次执行。
类似这样:
urls.py
...
(r'^characters/delete/$', views.delete_character),
(r'^characters/$', views.list_characters),
和views.py
def list_characters(request):
query_params = request.GET.get('q', '')
ctx = template.Context({
...,
query_params=urllib.quote(query_params) # <=== pass the query params to the template
})
return render(request, 'users/characters_found_table.html', ctx)
在模板中,生成删除链接,如下所示:
<form action="delete/" method=POST>
<input type=hidden name=q value="{{ query_params }}">
<input type=hidden name=idChar value="{{ ... }}">
<button type=submit>delete</button>
</form>
然后删除视图可以写为
def delete_character(request):
chracter_id = request.POST['idChar'] # fail hard if not provided
q = request.POST['q']
Characterweapons.objects.filter(characterid=chracter_id ).delete()
Characters.objects.filter(characterid=chracter_id ).delete()
return http.HttpResponseRedirect('../?q=' + q) # return to the list url (with search params)
这样,您无需保存任何全局状态。
答案 1 :(得分:1)
我建议您改用GET请求显示表。删除应该通过POST进行,并使用redirect
(而不是render
)再次进入GET请求。
如果要在请求之间存储过滤器参数,建议您使用Django Session
来存储该信息。
也许是这样的:
urls.py
url(r'^characters$',
views.show_characters,
name='show-characters'),
url(r'^characters/(?P<char_pk>[0-9]+)/delete/$',
views.delete_character,
name='delete-character'),
views.py
def show_characters(request):
# this will be a standard GET request to display the table
filter_param_1 = request.GET.get('filter_param_1', None)
if filter_param_1 is None:
# if there is no GET param, look in the session
filter_param_1 = request.session.get('filter_param_1', None)
else:
# if there is a GET param, store it in the session for the next time
request.session['filter_param_1'] = filter_param_1
ctx = {
'data': Characters.objects.filter(some_field=filter_param_1),
}
return render(request, 'users/characters_found_table.html', ctx)
def delete_character(request, char_pk):
if request.method == "POST":
character = get_obect_or_404(Characters, pk=char_pk)
# here you can delete other related objects, if they're not set up for delete CASCADE
character.delete()
messages.success(request, 'delete was successful')
return redirect('show-characters')
对您有用吗?