[英]Django render different templates for two submit buttons in a form
I am a beginner at Django development, and I am trying to make a food diary application. 我是Django开发的初学者,我正在尝试制作食品日记应用程序。 After a user enters his email on
index.html
, another web page should be rendered according to whichever button he clicks. 用户在
index.html
上输入电子邮件后,应根据他单击的任何按钮来呈现另一个网页。
I can possibly add two templates, but I also want my app to work if a user manually types a valid URL such as /apps/<user_email>/addDiaryEntry/
. 我可能可以添加两个模板,但是如果用户手动键入有效的URL(例如
/apps/<user_email>/addDiaryEntry/
,我也希望我的应用能够正常工作。 I don't know what to add in /apps/urls.py
. 我不知道在
/apps/urls.py
添加什么。 Also, can I somehow access a user object's Id so my routing URL become /apps/<user_id>/addDiaryEntry/
instead? 另外,我可以以某种方式访问用户对象的ID,以便我的路由URL改为
/apps/<user_id>/addDiaryEntry/
吗?
/templates/apps/index.html /templates/apps/index.html
<form method="post" action="/apps/">
{% csrf_token %}
<label for="email_add">Email address</label>
<input id="email_add" type="text">
<button type="submit" name="add_entry">Add entry</button>
<button type="submit" name="see_history">See history</button>
/apps/views.py /apps/views.py
def index(request):
if request.POST:
if 'add_entry' in request.POST:
addDiaryEntry(request)
elif 'see_history' in request.POST:
seeHistory(request)
return render(request, 'apps/index.html');
def addDiaryEntry(request):
print ("Add entry")
def seeHistory(request):
print ("See history")
/apps/urls.py /apps/urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Thank you for your help! 谢谢您的帮助! Please feel free to share any best practices which I am not following.
请随时分享我未遵循的任何最佳做法。
1) passing in an argument into a url, you can use regex groups to pass arguments. 1)将参数传递到url中,可以使用正则表达式组传递参数。 Here is an example using a kwarg:
这是使用kwarg的示例:
url(r'^(?P<user_email>[^@]+@[^@]+\.[^@]+)/addDiaryEntry/$', views.add_diary, name='add-diary-entry'),
2) just render a different template depending on which button was pressed: 2)根据所按下的按钮,仅渲染一个不同的模板:
def index(request):
if request.POST:
if 'add_entry' in request.POST:
addDiaryEntry(request)
return render(request, 'apps/add_entry.html');
elif 'see_history' in request.POST:
seeHistory(request)
return render(request, 'apps/see_history.html');
It's always tough starting out, make sure you put in the time to go over the docs, here are some places to look over regarding these topics: https://docs.djangoproject.com/en/1.10/topics/http/urls/#named-groups https://docs.djangoproject.com/en/1.10/topics/http/views/ 入门总是很困难,请确保您花时间阅读这些文档,以下是一些有关这些主题的地方: https : //docs.djangoproject.com/en/1.10/topics/http/urls/ #named-groups https://docs.djangoproject.com/en/1.10/topics/http/views/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.