I am a beginner at Django development, and I am trying to make a food diary application. After a user enters his email on index.html
, another web page should be rendered according to whichever button he clicks.
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/
. I don't know what to add in /apps/urls.py
. Also, can I somehow access a user object's Id so my routing URL become /apps/<user_id>/addDiaryEntry/
instead?
/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'),
]
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. Here is an example using a 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:
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.