[英]Django render different templates for two submit buttons in a form
我是Django開發的初學者,我正在嘗試制作食品日記應用程序。 用戶在index.html
上輸入電子郵件后,應根據他單擊的任何按鈕來呈現另一個網頁。
我可能可以添加兩個模板,但是如果用戶手動鍵入有效的URL(例如/apps/<user_email>/addDiaryEntry/
,我也希望我的應用能夠正常工作。 我不知道在/apps/urls.py
添加什么。 另外,我可以以某種方式訪問用戶對象的ID,以便我的路由URL改為/apps/<user_id>/addDiaryEntry/
嗎?
/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
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
urlpatterns = [
url(r'^$', views.index, name='index'),
]
謝謝您的幫助! 請隨時分享我未遵循的任何最佳做法。
1)將參數傳遞到url中,可以使用正則表達式組傳遞參數。 這是使用kwarg的示例:
url(r'^(?P<user_email>[^@]+@[^@]+\.[^@]+)/addDiaryEntry/$', views.add_diary, name='add-diary-entry'),
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');
入門總是很困難,請確保您花時間閱讀這些文檔,以下是一些有關這些主題的地方: 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.