Configuration of the URL, static file, POST request in Django

Source: Internet
Author: User

Pycharm is usually used, so this article is mainly based on the Django project created by the Pycharm default. Project directory such as:

Configuration of 1.URL

When you create a project, you can see the Django default page when you run the project. So how do you access the pages you create?
Because Django is a development pattern for class MVC. This is a matter of configuring URLs. Create your own APP (also known as a module) that contains the contents of the file such as:

Then you need to setting.py register the newly created in the file INSTALLED_APPS App :

The default URL configuration for newly created projects is as follows:

fromimport patterns, include, urlfromimport adminadmin.autodiscover()urlpatterns = patterns(‘‘,                       # Examples:                       # url(r‘^$‘, ‘django_static_file_config.views.home‘, name=‘home‘),                       # url(r‘^blog/‘, include(‘blog.urls‘)),                       url(r‘^admin/$‘, include(admin.site.urls)),                       )

So how do you relate the newly created to the App urls.py project by default urls.py ? The following configuration is required:

from  django.conf.urls Span class= "Hljs-keyword" >import  patterns, include, Urlfrom  django.contrib import  adminadmin.autodiscover () Urlpatterns = Patterns (                       , # Examples:                        # url (r ' ^$ ', ' django_static_file_config.views.home ', name= ' home '),  # url (r ' ^blog/', include (' Blog.urls ')),  URL (r ' ^admin/$ ' , include (Admin.site.urls)),  #通过include () function contains URL of the new app type  URL (r ' ^load/' , include (),)  

The configuration in the newly created app is urls.py as follows:

#!usr/bin/env python# coding: utf-8fromimport patternsfromimport urlurlpatterns = patterns(‘‘,                       url(r‘^load_index/$‘‘index.view.load_index‘, name=‘load_index‘),                       )

Then the URL to access is:

http://127.0.0.1:8000/load/load_index/

The meanings of the above two configuration files are:

When Django receives the request, it scans the default configuration file by the first layer in the URL (in the example /load/ ), which is the following statement:

 url(r‘^load/‘, include(‘index.urls‘)),

If you can scan it, then follow the second layer load_index scanning the Include import URL, which is the URL for the new app created in the project urls.py .

2. Configuration of static files

Prior to learning Django, the configuration of static files spent a lot of time, and did not solve the problem, online is a lot of various solutions, but still do not use their own projects. Because different versions of Django will change, it is strongly recommended that you choose to read the official documentation according to your current version:

First look at Django's official documentation (the version I'm using is the django1.6 version):

https://docs.djangoproject.com/en/1.6/howto/static-files/

When creating a Django project, a default configuration file is generated at the root of the project setting.py :
The default configuration for static files is the following code:

# Static files (CSS, JavaScript, Images)# 这里已经为我们生成了官方文档的地址# https://docs.djangoproject.com/en/1.6/howto/static-files/‘/static/‘TEMPLATE_DIRS = (    os.path.join(BASE_DIR,  ‘templates‘),)

After reading the official documentation ( highly recommended ), we only need to setting.py add the following code to specify the directory of static files:

# -----config static fileSTATICFILES_DIRS = (    os.path.join"static"),)

When I browse the Web page, I can find that the static files are found correctly. Such as:

Configuration of 3.POST Requests

Before looking at post request, look at the way get request, the front-end jquery code is as follows:

$ (function   ()  { $ (). On (  ' click ' , function   ()  { var  url =  $.ajax ({type:  ' GET ' , data : {test: ' test ' }, Url:url, Success:testsu ccess, DataType:  ' html ' , Async: false}); });}) var  testsuccess = function   ()  {}; 

The way back-end python handles:

def getmethod(request):    test = request.GET.get(‘test‘,‘‘)    return HttpResponse(test)

The parameters that can be get passed in a normal manner are received:

Look at the results, such as:

What about POST the way you use it?
Just modify the parameters in the jquery code, and first modify the URL to:

var‘/load/postmethod/‘

Then modify:

type‘POST‘,

When you try to pass the parameters back again, the results are as follows:

An 403 error occurred and the request was rejected. This is because the Django default configuration MIDDLEWARE_CLASSES in one middleware CSRF (cross-site request forgery), Wikipedia address (click here):

‘django.middleware.csrf.CsrfViewMiddleware‘,

The post request was verified.

The first of these solutions:

We first try to comment out this line to verify that the request is being sent properly POST .
You can see OK the results, such as:

The second solution:

Import

from django.views.decorators.csrf import csrf_exempt

module, and add the post following prefix to the function of the accepted parameter,

@csrf_exemptdef postmethod(request):    test = request.POST.get(‘test‘,‘‘)    return HttpResponse(test)

It is verified that the request can be accepted normally post (there is a disadvantage that it has to be added before all the request handlers for the project POST ):

CSRF Recommended Reading:
Http://www.cnblogs.com/lins05/archive/2012/12/02/2797996.html

Configuration of the URL, static file, POST request in Django

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.