Examples of simplified Python Django framework code

Source: Internet
Author: User
Tags django tutorial
This article mainly introduces some examples of the Django framework code to simplify Python. In fact, this article only extracts some of the most basic functions of Django to simplify the complexity of beginners. Next, for more information, see Django's popularity and popularity. some developers still think that she is an outdated web development framework and is only suitable for content-rich web programs. However, most web programs are usually not rich, which makes Django seem to be the best web framework.

So let's take some time to get to know her from the current web development practices.

Simple and clear Django

A web framework helps web programs generate core architectures for reuse in other projects. Django quickly builds web programs based on this. The core of Django is the WSGI program, which processes HTTP requests and returns meaningful HTTP responses. She provides various tools, such as generating URL routes, processing cookies, parsing form data, and uploading files.

In addition, Django creates a dynamic template engine for HTTP responses. You can use it immediately. to enrich the web application build experience, she provides a variety of filters and tags to create dynamic and scalable templates.


With these tools, you can easily create simple and clear micro-frameworks in Django projects.

We know that some people like to build their own wheels. We don't mean to belittle this kind of behavior, but using Django for development will reduce our interference. For example, when you are struggling with Jinja2, Mako, Genshi, and Cheetah, you may already be using the existing Django template engine. Less tangle makes us enjoy more pleasant development processes.

Train new Django users

There is a big problem in Django and other web framework communities, that is, training for new users. Just as many Django users have created a voting program on the Django official website to learn about Django. Many of our old Django developers think that it is a "ceremony" for entering the Django community ". But is it the best way to learn Django? I don't think so.

Currently, this voting program has six parts. Although each part has its meaning, it is not until the third one that you can write your view and construct an HTTP response. Compared with simple "Hello World" programs, this is too far away in some popular python micro-frameworks (such as Flask and Bottle. The best way to learn is that when we learn a piece of Django, there are no too many obstacles, and we can focus on the interaction of processing requests and responses. New users can get help from other parts of the framework when building common web tasks, such as session management, user verification, and built-in admin interfaces.


Follow our instructions to build a simplified Django tutorial:

import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import HttpResponsefrom django.core.management import execute_from_command_line settings.configure(  DEBUG=True,  SECRET_KEY='placerandomsecretkeyhere',  ROOT_URLCONF=sys.modules[__name__],) def index(request):  return HttpResponse('Powered by Django') urlpatterns = patterns('',   (r'^$', index),) if __name__ == "__main__":  execute_from_command_line(sys.argv)

Simple. This short piece of code is all you need to run the Django project. Let's begin to explain the various sections of the code gradually.

First, make sure that HttpResponse is introduced and the content we want to return is returned.

from django.http import HttpResponse def index(request):  return HttpResponse('Powered by Django')

In general, this code should be in view. py. However, in this simplified version of the tutorial, we put all the code in the Django project into a single file.

The perfect link between the current and next parts of the application is the link structure. The above code expects such a url index, so we need to create one for it.

from django.conf.urls import patternsfrom django.http import HttpResponse def index(request):  return HttpResponse('Powered by Django') urlpatterns = patterns('',   (r'^$', index),)

With the above seven lines of code, we have built the foundation for running on Django for the application! Now, let's complete some basic settings so that the application can be executed.


import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import HttpResponse settings.configure(  DEBUG=True,  SECRET_KEY='placerandomsecretkeyhere',  ROOT_URLCONF=sys.modules[__name__],) def index(request):  return HttpResponse('Powered by Django') urlpatterns = patterns('',   (r'^$', index),)

You may have discovered that in the above example, we have stripped those settings, and especially omitted the database configuration. These settings can serve as a barrier for new users. when these new users try to determine which database to use, they may avoid confusion. When developing a project, we want to ensure that our work is focused on a specific part, thus reducing the obstacles in our work.

Note: set random SECRET_KEY in the settings. configure file to protect session and cross-site request forgery (CSRF ).

Because the start project command is not used to generate this structure, the manage. pyfile file is lost. Therefore, you need to manually add the relevant manage. pyand information:

import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import HttpResponsefrom django.core.management import execute_from_command_line settings.configure(  DEBUG=True,  SECRET_KEY='placerandomsecretkeyhere',  ROOT_URLCONF=sys.modules[__name__],) def index(request):  return HttpResponse('Powered by Django') urlpatterns = patterns('',   (r'^$', index),) if __name__ == "__main__":  execute_from_command_line(sys.argv)

Now you can start the application from the command line:

$ python project_name.py runserver

Visit 127.0.0.1: 8000 and you will see the "Powered by Django" page!

Here, you may ask: "Where are the models and views ?". Before that, let's relax. Let's discuss what Django is-she is a web framework that contains a series of tools that we often need, and you can easily reference them in projects. Next we will introduce these tools. Building a template is a good column. Let's get started.

Before adding a template file, we need to add urls and some necessary settings to let Django know where the template file is placed. Add these settings to the file.

import osimport sys BASE_PATH = os.path.dirname(__file__) from django.conf import settingsfrom django.conf.urls import patterns, urlfrom django.core.management import execute_from_command_linefrom django.shortcuts import render settings.configure(  DEBUG=True,  SECRET_KEY='placerandomsecretkeyhere',  ROOT_URLCONF=sys.modules[__name__],  TEMPLATE_DIRS=(    os.path.join(BASE_PATH, 'templates'),  ),) def index(request):  return render(request, 'index.html', {'request': request}) urlpatterns = patterns('',   url(r'^$', index, name='index'),) if __name__ == "__main__":  execute_from_command_line(sys.argv)

You will notice that the OS. path Python module is added at the top. By doing so, we have created an easy way to point to their project folder for new users. Now we can easily add the path pointing to the template in our TEMPLATE_DIRS settings, and start to experience the advantages of Django's built-in labels and filters!

As you can see, by dividing the basic parts of a Django application into smaller parts, we can create a simpler method for new built-in users. We need to learn how to create a Django application without ORM and Django management. You need to realize what built-in functions of Django are. They are not necessary when using the framework. if you feel that they are not necessary, you have not lost much. We started to use the good part of Django instead of feeling its weight, just as we learned the standard library of Python. Let's start moving out of date and look at its source code. the features are really rich.

Therefore, based on all these, you are considering building some applications that can be developed in a lightweight model?

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.