2016-09-29 64 views
0

我是Django开发人员的初学者,我正在尝试制作食物日记应用程序。用户在index.html上输入他的电子邮件后,应根据他点击的任何按钮呈现另一个网页。Django为表单中的两个提交按钮呈现不同的模板

我可以添加两个模板,但如果用户手动键入有效的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'), 
] 

谢谢你的帮助!请随意分享我没有遵循的最佳做法。

回答

0

1)传递参数到一个url中,你可以使用regex组来传递参数。下面是一个使用kwarg一个例子:

url(r'^(?P<user_email>[^@][email protected][^@]+\.[^@]+)/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/

相关问题