重定向后 - 有没有办法从Django中的URL中删除表单字段?

时间:2017-12-06 06:30:27

标签: django django-forms django-views

发送表单后,我被重定向到另一页。

该页面的网址将包含网址+表单字段名称+表单字段值。

是否有办法以URL不显示表单字段名称和值的方式重定向(或者可能在没有重定向的情况下操作数据)?

我的项目(没有应用):

urls.py

:searchTerm

views.py

from django.conf.urls import url
from . import views

urlpatterns = [

url(r'^$', views.home, name='home'),
url(r'^translate/', views.translate, name='translate'),

]

hello.html的

from django.shortcuts import render


def home(request):
    return render(request, 'hello.html')


def translate(request):

original = request.GET['originaltext'].lower()
translation = ''
for word in original.split():
    if word[0] in ['a','e','i','o','u']:
        translation += word
        translation +='yay '
    else:
        translation += word[1:]
        translation += word[0]
        translation += 'ay '

return render(request, 'translate.html', {'original':original, 
'translate':translation})

translate.html

<h1> heading title </h1>

<form action="{% url 'translate' %}">
  <input type="text" name="originaltext"/>
  <br/>
  <input type="submit" value="Translate" />
</form>

因此,每当我发送表单时,我都会被重定向,并且URL变为:

  

http://127.0.0.1:8000/translate/?originaltext=user_text

1 个答案:

答案 0 :(得分:1)

也许尝试从表单发送POST请求:

<form action="{% url 'translate' %}" method="POST">{% csrf_token %}
<input type="text" name="originaltext"/>
<br/>
<input type="submit" value="Translate" />
</form>

在您看来:

def translate(request):
    context = {}
    if request.method == 'POST':
        original = request.POST.get('originaltext').lower()
        context['original'] = original
        translation = ''
        for word in original.split():
            if word[0] in ['a','e','i','o','u']:
                translation += word
                translation +='yay '
            else:
                translation += word[1:]
                translation += word[0]
                translation += 'ay '
        context['translation'] = translation
    return render(request, 'translate.html', context)