想要避免在Django模板中对表单操作进行硬编码。代替
action="/en/accounts/change_profile/"
我更喜欢action=views.change_profile
。
是否可以将视图函数连接到表单操作而无需使用字符串?
我的表单
<form action="/en/accounts/change_profile/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
我的观点
@login_required
def change_profile(request):
form = None
if request.method == 'POST':
form = forms.UserProfileForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/en/accounts/profile')
else:
form = forms.UserProfileForm()
return shortcuts.render(request, 'project/change_profile.html',
{'form':form,})
答案 0 :(得分:1)
尝试使用url-Tag之类的:
<form action="{% url 'change_profile' %}" method="post">
定义路由后。 Here you have some examples.
在语言环境中有一点点技巧。我记得2009年,您可以通过中间件处理它。但现在更容易:Language prefix in urls,如:
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _
urlpatterns = i18n_patterns('',
url(_(r'^accounts/change_profile/$'), 'views.change_profile', name='change_profile'),
)
答案 1 :(得分:1)
:
url(r'^en/accounts/change_profile/', 'app.views.change_profile', name='change_profile'),
现在在你的模板中:
{% url change_profile %}