在自強學堂上學習了下django,自己花了點時間寫個輸入網址生成二維碼的網頁。大概思路:在前端網頁輸入要轉化成二維碼的網址,網頁提交表單通過urls.py找到views.py相應的方法,生成二維碼圖片。
動手玩玩。
創建項目
django-admin.py startproject lsk_tool
在新建的項目裏新建一個app
python manage.py startapp tools
在app中新建templates文件夾,把寫好的網頁文件夾中,index.html代碼如下:
<!DOCTYPE html>
<head>
<title>生成二維碼</title>
</head>
<body>
<form method='post' action='/sub/'>
<p>網址:<input type='text' name='website' value='http://'></p>
<button type="submit">提交</button>
{% csrf_token %}
</form>
</body>
修改app中的視圖文件views.py,修改代碼如下:
from django.utils.six import BytesIO
import qrcode
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request,'index.html')
def generate_Image(request):
website = request.POST.get('website')
if(len(website) != 0):
img = qrcode.make(str(website))
buf = BytesIO()
img.save(buf)
image_stream = buf.getvalue()
response = HttpResponse(image_stream,content_type="image/png")
return response
return HttpResponse(u"網址不能爲空!")
修改好視圖文件後,修改項目的配置文件,修改settings.py文件,主要修改這兩項。設置所有域名都可以訪問
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tools',
]
修改urls.py文件:
from django.conf.urls import url
from django.contrib import admin
from tools import views as t_views
urlpatterns = [
url(r'^$',t_views.home),
url(r'^sub/',t_views.generate_Image),
url(r'^admin/', admin.site.urls),
]
大功告成!啓動項目:
python manage.py runserver 你的域名或者IP:開放的端口
效果圖:
有什麼問題,希望大家糾正!!!