【问题标题】:Django render different templates for two submit buttons in a formDjango为表单中的两个提交按钮呈现不同的模板
【发布时间】:2017-02-07 06:17:16
【问题描述】:

我是 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'),
]

感谢您的帮助!请随时分享我未遵循的任何最佳做法。

【问题讨论】:

    标签: python django forms django-templates


    【解决方案1】:

    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/

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2014-12-03
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多