![](/img/trans.png)
[英]How to make a button click update the database and redirect to a view in Django?
[英]Django: how to switch to another view with the click of a button?
我正在使用Django 1.9.5和Python 2.7.11構建django應用程序。 我的項目(我將其命名為djan_web)目錄如下所示:
djan_web\
manage.py
djan_frontend\
views.py
templates\
djan_frontend\
upload.html
djan_homepage\
index.html
djan_web/
urls.py
我可以加載index.html
,這是我的主頁。 在index.html
,我有一個按鈕,單擊該按鈕時,我想加載upload.html
。 這是我的相關文件:
index.html:
<!DOCTYPE html>
<html>
<head>
<title >Django Wed Project</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
<div class="header">
<p> some text </p>
<div class="container" style="width:95%">
<center>
<div class="col-md-1 center-block text-center" style="font-size: xx-large">
<a href="/upload-file" class="dark" style="cursor: pointer;">
<span class="glyphicon glyphicon-upload"></span>Let's get started!</a>
</div>
</center>
</div>
</div>
</body>
</html>
urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from djan_frontend import views
from django.views.generic import TemplateView
urlpatterns = [
url(r'^', views.homepage, name="homepage"),
url(r'^admin/', admin.site.urls),
url(r'^upload-file/$', views.upload, name='upload')
]
views.py:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from .upload_file import UploadFileForm
from .models import Document
from .tasks import process_csv
def homepage(request):
return render(request, 'djan_frontend/djan_homepage/index.html')
def upload(request):
return render(request, 'djan_frontend/upload.html')
我可以加載index.html
,但是當我單擊“ Let's get started
”按鈕時,除了URL(將upload-file/
附加到URL)之外,什么都沒有發生。
我也嘗試使用TemplateView,因此將按鈕定義中的href
部分更改為href="{% url 'upload' %}"
,並將urls.py
的第三個url模式更改為
url(r'^upload/$', TemplateView.as_view(template_name='upload.html'), name='upload')
並在views.py
刪除了upload
功能,但無法正常工作。 任何幫助是極大的贊賞!
您需要在urls.py
修復您的URL。 嘗試:
urlpatterns = [
url(r'^$', views.homepage, name="homepage"),
url(r'^admin/', admin.site.urls),
url(r'^upload-file/$', views.upload, name='upload')
]
請注意$
在regexs結束。 您需要在網址格式中添加結束錨,尤其是在第一個網址格式上。 沒有結尾的$
它可以匹配任何內容,因此任何傳入的請求都將定向到您的主頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.