Python + django implements simple file upload,

Source: Internet
Author: User

Python + django implements simple file upload,

Today, we will share a small example of simple File Upload implemented by Django.

Procedure
• Create a Django project and a Django Application
• Design Model
• Processing urls. py and views. py
• Design templates and Design Forms
• Run the project and view the database

Next let's complete each small part separately.

Create a project and an application

Django-admin startproject Django_upload

Django-admin startapp app

Add a directory named upload, which will be used later.

Then remember to add 'app' to INSTALLED_APPS in settings. py ',. Pay attention to the comma ~~

Design Model

To upload a file, you must know who uploaded the file and what it was uploaded. Therefore, our model is simple, with a user name and a file name. The following app. models. py

from __future__ import unicode_literalsfrom django.db import models# Create your models here.# User CLass for user,username and userimg pathclass NormalUser(models.Model):  username = models.CharField(max_length=30)  headImg = models.FileField(upload_to='./upload')  def __unicode__(self):    return self.username  class Meta:    ordering = ['username']

After the model is created, synchronize the database. The command is simple. Because my Django version is 1.9.6

Python manage. py syncdb is unavailable

We can use the following command to replace

Python manage. py makemigrations

Python manage. py migrate

Urls. py and views. py

These two files exist to implement the V and C of the MVC model.
Views. py is as follows:

from django.shortcuts import render,render_to_responsefrom django import formsfrom django.http import HttpResponsefrom app.models import *# Create your views here.class NormalUserForm(forms.Form):  username = forms.CharField()  headImg = forms.FileField()def registerNormalUser(request):  if request.method == "POST":    uf = NormalUserForm(request.POST,request.FILES)    if uf.is_valid():      # get the info of the form      username = uf.cleaned_data['username']      headImg = uf.cleaned_data['headImg']      # write in database      normalUser = NormalUser()      normalUser.username = username      normalUser.headImg = headImg      normalUser.save()      return HttpResponse('Upload Succeed!')  else:    uf = NormalUserForm()  return render(request,'register.html',{'uf':uf})

Urls. py

"""Django_upload URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:  https://docs.djangoproject.com/en/1.9/topics/http/urls/Examples:Function views  1. Add an import: from my_app import views  2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views  1. Add an import: from other_app.views import Home  2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf  1. Import the include() function: from django.conf.urls import url, include  2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminfrom app.views import *urlpatterns = [  url(r'^admin/', admin.site.urls),  url(r'^register/$',registerNormalUser),]

Generally, we create a super Administrator with the following command:

Python manage. py createsuperuser

Then follow the prompts to create it.

Design templates and forms

As a matter of fact, we can see a class named NormalUserForm in views. py just now. Its significance is to conveniently retrieve the form data we need from the request. I'm afraid you have noticed that the NormalUserForm field is the same as that of the NormalUser model. Learn each other's philosophies :-)

Templates/register.html

<!DOCTYPE html>

There are three important points:
• <Form method = "POST" enctype = "multipart/form-data">:The specific format of the Form. Make sure that enctype is specified when uploading data.

• {% Csrf_token % }:For cross-origin requests, we need to add the template tag inside the form tag, and use render instead of render_to_response in views. py to implement

• {Uf. as_p }}:With the. as_p method, django outputs all fields of the form on the template page according to the default style.

Debug and enable the application

Well, most of the tasks are done. Let's open our development server to verify it.

Python manage. py runserver

Open the browser and enter http: // 127.0.0.1: 8000/register

Then enter the form as required. When the is_valid () method is added, views. py will automatically help us verify the form data fields!

Open our database management software and you will find that only the path is stored, not the real data. This also reflects the core concept of big data storage. Click the upload directory and find that the file has been uploaded successfully!

Summary

Although this small example is very simple today, there are many things worth pondering. My gains are as follows.
• Use models. FileField () to implement the File Upload Component

• Add a form class for the corresponding model, with the same fields. This makes it easier to obtain form data. Uf = NormalUserForm (request. POST, request. FILES ).

• Form output on the html page in the form enctype format and. as_p Mode

That's it!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.