今回の記事はPythonのWebフレームワークDjangoを使って、html上の画像をクリックし、別ページに遷移する方法を紹介する初心者向けの記事です。Django・Python初心者でWebアプリ作成の練習中の方などは是非参考にしてみてください。
Djangoプロジェクト環境
私の環境はMac OS、python 3.6です。
Djangoプロジェクトを作成する手順は下記です。
// プロジェクトの作成
django-admin startproject imageclick
フォルダ構成は下記です。
Djangoプロジェクトのhtml上の画像クリックでページ移動
templatesファイルにindex.htmlとmove.htmlをセットします。
「127.0.0.1:8000/」にアクセスすると「index.html」が表示されます。その「index.html」内の画像をクリックすることで移動先の「move.html」にページ移動するサンプルを作成していきます。
修正するコードは下記です。
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('templates/', views.move_show, name='move_show'),
path('templates/', views.move, name = 'move'),
path('templates/', views.ret, name='ret'),
]
<title>test</title>
<a>
test_click
</a>
<body>
<form action="{% url 'move' %}" method="POST">
{% csrf_token %}
{% load static %}
<input type="image" src="{% static "pic.png" %}" name="button_1">
</form>
</body>
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('templates/', views.move, name = 'move'),
path('templates/', views.ret, name='ret'),
]
from django.shortcuts import render
def move_show(request):
return render(request, 'move.html')
def index(request):
return render(request, 'index.html')
def move(request):
if request.method == 'POST':
if 'button_1' in request.POST:
return render(request, 'move.html')
def ret(request):
if request.method == 'POST':
if 'button_2' in request.POST:
return render(request, 'index.html')
これでプロジェクトを起動すると画像が表示されるので、その画像をクリックすることでページが表示されます。
今回の記事は以上です。ほかにもDjango関連の記事を記載しているので是非興味がある方は参考にしてみてください。
コメント