Django's views, forms, static files

view

Django concept of a view is a collection of classes having the same function and the page template. Like on library management system can be built at several views:

  • ---- provide user login page user login
  • ---- provide user registration user registration page
  • All books show ---- show all information Book Description
  • Book Details show ---- show details of a book

In Django, web pages and other content is coming from a view derived. Each view appears as a simple Python function. Django will be based on the URL requested by the user to choose which view to use.

A URL schema defines some basic format of the URL - for example: Define a Python function is login, you can get by 127.0.0.1/login/ login page.

Create a view

Each view has to do only two things: a return HttpResponse object that contains the requested page content, or throw an exception, such as Http404.

Now let's add more views to app01 / views.py years.

def login(request):
	return HttpResponse("这里是登录页面!")
def register(request):
	return HttpResponse("这里是注册页面!")

These add a new view into the project folder fristdjango the urls module, as long as adding a few url () function call on the line:

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/',views.login),
    url(r'^reg/',views.reg),
]

After this start Django project input 127.0.0.1/login/ or 127.0.0.1/register/ in the browser you can see the different results.

It should be noted that when we enter 127.0.0.1/login can also access the corresponding content, because if you do not visit when routing slash, will be automatically redirected to the internal slash route. You can see the actual browser in developer mode browser is a request twice.

Static files

In addition to server-generated HTML, web applications typically require some additional documents - such as images, scripts, and style sheets - to help render the web page. In Django, we put these documents are collectively referred to as "static files."

Static files on the static files in a folder corresponding app or static file in the project directory folder. You need to configure settings for the project under the name of static files.

STATIC_URL = '/static/'  # 接口前缀,默认情况下这个前缀跟静态文件夹名字一样
# 静态文件配置
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static'), # 静态文件夹路径
    os.path.join(BASE_DIR,'static1'),
    os.path.join(BASE_DIR,'static2')
]

STATIC_URL = '/ static /' is exposed to the outside world can still access the server folder all the resources below. static here is the interface prefix nothing to do with the name of the static folder, the tip is to visit static files by this name, the default prefix with the static folder name, as in the case!

Django default static files in the project directory folder and static files in each folder to find the app file, and then click Find, then list all of the static files to find the path to stop immediately return a 404 not found.

Forms

With sign-on capabilities we need to submit some data with a get or post method in the foreground, HTML form is a classic way interactive website.

HTTP protocol with the "request - reply" way of working. When the client sends a request, the data may be added in the request. Server by parsing the request, you can get data from the customer, and to provide specific services based on URL.

How to submit data to the specified address form and manner, action property controls submission address:

  • 1. Full Path
<form action="http://127.0.0.1:8000/login/">
  • 2. Write only the path suffix
<form action="/login/">
  • 3. Do not write (default submission to the current path)

form is the default form get request, the request for safe use post, submit to control by way of the method attribute from.

<form action="/login/" method="post">
    username: <input type="text" name="username"> <br>
    password: <input type="password" name="password"> <br>
    <input type="submit" value="提交">
</form>

Perform different logic code depending on client requests embodiment

def login(request):
	# 获取用户端提交的请求方式,拿到的请求方式是全大写的字符串
	if request.method == 'POST':
		return HttpResponse('登录成功!')
	return render(request,'login.html')

Get data submitted

All the data submitted over the front end are stored in the request.POST or request.GET, request.GET can be seen as a dictionary, a value transferred to the GET method are saved which can request.GET.get ( 'key' , None) to the value, no not being given.

Gets the value of the data submitted by get and getlist, get a list of value inside all the elements need to use getlist, get only get to the last element of the value of the list.

def login(request):
    if request.method == 'POST':
        print(request.POST)  # 你就把它当成一个大字典里面存放了客户端post提交的所有的数据
        # request.POST:< QueryDict: {'username': ['linwow'], 'password': ['123']} >
        print(request.POST.get('username'))  # value虽然是个列表但是获取value的时候拿到却是单个元素,这是因为默认只会取value列表里面的最后一个元素
		# request.POST:<QueryDict: {'username': ['lin', 'wow'], 'password': ['123']}>
        print(request.POST.getlist('username'))  # 要想一次性获取value列表里面所有的数据需要用getlist()
        # ['lin', 'wow']
		print(request.POST['password'])  # 不推荐使用该方法获取数据
        return HttpResponse('登录成功!')
    return render(request,'login.html')

Get get the requested data request with post exactly the same way!

Guess you like

Origin blog.csdn.net/linwow/article/details/91049387