Django url, static file, POST request configuration, djangourl

Source: Internet
Author: User

Django url, static file, POST request configuration, djangourl

Pycharm is usually used, so this article mainly explains how to use the default django project created by pycharm. The project directory is as follows:

1. URL Configuration

After creating a project, run the project to view the default page of django. How can I access my own page?
Because django is a MVC-like development model. This involves URL configuration. Create your ownAPP(Also known as a module), including the following file content:

Then you needsetting.pyFileINSTALLED_APPSTo register the newly createdApp:

The default url configuration for the newly created project is as follows:

from django.conf.urls 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)),                       )

So how can we change the newly createdAppOfurls.pyAnd the default Projecturls.pyWhat about Association? The following configuration is required:

From django. conf. urls 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), # Use the include () function to include the url (R' ^ load/', include ('index. urls ')),)

In the newly created APPurls.pyThe configuration is as follows:

#!usr/bin/env python# coding: utf-8from django.conf.urls import patternsfrom django.conf.urls import urlurlpatterns = patterns('',                       url(r'^load_index/$', 'index.view.load_index', name='load_index'),                       )

The access url is:

Http: // 127.0.0.1: 8000/load/load_index/

The significance of the preceding two configuration files is:

When django receives the request, it will follow the first layer in the url level (in the example/load/) To scan the default configuration file, that is, the following statement:

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

If you can scan, follow the second layer.load_indexScan the include import url, that is, the newly created APP in the projecturls.pyIs there a match in the url.

2. static file configuration

When I was learning django, I spent a lot of time on static file configuration and did not solve the problem. I also searched a lot of solutions on the Internet, but still did not apply to my own projects. Because different versions of django will change, we strongly recommend that you read the official document based on your current version:

First, read the django official documentation (my version is django1.6 ):

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

A default configuration file is generated in the root directory of the project when a django project is created.setting.py:
The default static file configuration is as follows:

# Static files (CSS, JavaScript, Images) # Here we have generated the address of the official document # https://docs.djangoproject.com/en/1.6/howto/static-files/STATIC_URL = '/static/' TEMPLATE _ DIRS = (OS. path. join (BASE_DIR, 'templates '),)

After reading the official documentation (Strongly recommended), We only needsetting.pyAdd the following code to specify the directory of the static file:

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

When I browse the Web page, I can find the static file correctly. For example:

3. POST request configuration

ReadingpostBefore the request, take a look.getRequest method. The front-end jQuery code is as follows:

$(function () {    $('.test-post').on('click', function () {        var url = '/load/getmethod/'        $.ajax({            type: 'GET',            data:{              test:'test'            },            url: url,            success: testSuccess,            dataType: 'html',            async: false        });    });})var testSuccess =function (){};

Backend python processing method:

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

Can receivegetParameters:

Check the result, for example:

UsePOSTWhat will happen?
You only need to modify the parameters in jQuery code. First, modify the url:

var url = '/load/postmethod/'

Then modify:

 type: 'POST',

When you try to pass parameters on the backend again, the result is as follows:

Occurred403The request is rejected. This is because the default configuration of djangoMIDDLEWARE_CLASSESMiddlewareCSRF(Cross-Site Request Forgery), Wikipedia address (Click here ):

'django.middleware.csrf.CsrfViewMiddleware',

PairpostThe request is verified.

Solution 1:

First, we try to comment out this line to verify whether it can be sent normally.POSTRequest.
The result is:OKSuch:

Solution 2:

Import

from django.views.decorators.csrf import csrf_exempt

Module, andpostAdd the following prefix before the Parameter Function,

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

Verified and acceptedpostRequest (one disadvantage is that allPOSTThe request processing function must be marked as follows ):

CSRF recommended reading:
Http://www.cnblogs.com/lins05/archive/2012/12/02/2797996.html

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.