For web development, user login, registration, file upload, etc. are the most basic functions. There are many related articles for different web frameworks, but after searching, I found that most of them are not complete. For those who want to learn web development For novices, there is no way to practice step by step; for web applications, it includes the creation of the database, the development of the front-end page, and the processing of the intermediate logic layer.
This series focuses on operability and introduces how to implement some simple functions through the Django web framework. Each chapter is complete and independent. Novice users can experience the process of web development through hands-on experience. Please refer to relevant documents for details during the process.
Environment for this operation:
===================
deepin linux 2013 (based on ubuntu)
python 2.7
Django 1.6.2
===================
Create projects and applications
#CreateProject
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite2
fnngj@fnngj-H24X:~/djpy$ cd mysite2
#Create a disk application under the project
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py startapp disk
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'disk', )
Design Model (database)
Open the mysite2/disk/models.py file and add the following content
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length = 30) headImg = models.FileField(upload_to = './upload/') def __unicode__(self): return self.username
The following is the synchronization of the database
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py syncdb Creating tables ... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session Creating table disk_user You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): yes 输入yes/no Username (leave blank to use 'fnngj'): 用户名(默认当前系统用户名) Email address: fnngj@126.com 邮箱地址 Password: 密码 Password (again): 确认密码 Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s)
1. Open the mysite2/disk/views.py file
from django.shortcuts import render,render_to_response # Create your views here. def register(request): return render_to_response('register.html',{})
2. Create a registration page
First create the templates directory in the mysite2/disk/ directory, and then create the register.html file in the mysite2/disk/templates/ directory:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <h1 id="register">register</h1> </body> </html>
3. Set template path
#template TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite2/disk/templates' )
4. Set URL
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite2.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^disk/', 'disk.views.register'), )
5. Start the service
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py runserver Validating models... 0 errors found May 20, 2014 - 13:49:21 Django version 1.6.2, using settings 'mysite2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
6. Visit http://127.0.0.1:8000/disk/
If the registration page can be opened normally, it means that the entire process has been completed. This is also the basic routine of Django development. Readers must be proficient in understanding this basic routine.
完善表单提交
通过上面的过程,我们只是把过程串了起来,细心你一定发现,我们的register.html 文件,并没有创建用户提交的表单,views.py文件中也并没有对用户提交的信息做处理。下面我们就针对这两个文件进一步的补充。
打开mysite2/disk/templates/register.html 文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <h1 id="register">register</h1> <form method="post" enctype="multipart/form-data" > {{uf.as_p}} <input type="submit" value="ok"/> </form> </body> </html>
打开mysite2/disk/views.py 文件:
from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse # Create your views here. class UserForm(forms.Form): username = forms.CharField() headImg = forms.FileField() def register(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): return HttpResponse('upload ok!') else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
再次刷新http://127.0.0.1:8000/disk/ 页面
填写用户名,选择本地上传文件,点击“ok”
抛出一个错误,这个错误比较友好,所以不是我们操作过程中的小错误。
打开mysite2/mysite2/settings.py文件,将下面一行代码注释:
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
再次刷新http://127.0.0.1:8000/disk/ 页面,我们就可以正常将用户名和文件提交了!
将数据写入数据库
虽然已经实现了数据的提交,但用户名与文件并没有真正的写入到数据库。我们来进一步的完善mysite2/disk/views.py 文件:
#coding=utf-8 from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse from disk.models import User # Create your views here. class UserForm(forms.Form): username = forms.CharField() headImg = forms.FileField() def register(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): #获取表单信息 username = uf.cleaned_data['username'] headImg = uf.cleaned_data['headImg'] #写入数据库 user = User() user.username = username user.headImg = headImg user.save() return HttpResponse('upload ok!') else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
再次刷新http://127.0.0.1:8000/disk/ 页面,完成文件的上传。
那数据库中保存的是什么呢?
fnngj@fnngj-H24X:~/djpy/mysite2$ sqlite3 db.sqlite3 SQLite version 3.7.15.2 2013-01-09 11:53:05 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> select * from disk_user; 1 | Alen | upload/desk.jpg sqlite>
通过查看数据库发现,我们数据库中存放的并非用户上传的文件本身,而是文件的存放路径。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool