Come on, the front page of the Python Web recipe system

7.1 Initializing the Menu System Home page

If you have no basic knowledge of HTML and CSS, it may be difficult for you to learn. It is recommended that you supplement some front-end knowledge to facilitate subsequent learning. You can also directly enter the Learning stage of Django. It’s not a problem.

This blog began to build the front end of the recipe system page, the basic knowledge involved is the web template framework and front end, priority will be from the user authentication system began to write, the previous blog model related content, first put it, will continue to use soon.

Here we begin to write part of the front end of the home page code, we choose [BootStrap3 framework], this framework is easier to accept.

To implement a page in Django, you need to create a template HTML file, and then modify the views.py file to complete the view-handling function.

Create directories and files

Create the Templates folder in the MenuApp application directory, and then go ahead and create a subdirectory of Menuapp in that directory.

Create a new index.html file in the Templates /menuapp directory. This is the home page template file. I’m sure some people ask, does the code just type itself out? This is definitely not, if so, there is no front-end knowledge, WE can not go on learning, these content is modified. Open the Bootstrap3 Template page and select a template, such as the following.

In the open page, click the right mouse button to choose view source code, copy the content you want in the source code page, remove the relative path of the relevant part of the code, such as the following content.

<! -- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src=".. /.. /assets/js/ie10-viewport-bug-workaround.js"></script>Copy the code

This.. /.. / are removed, and you get the final source code.

<! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <! The above 3 meta tags must come first, and everything else must come after them! --> <meta name="description" content="" /> <meta name="author" content="" /> <link rel="icon" href=".. /.. /favicon.ico" /> <title>Jumbotron Template for Bootstrap</title> <! - the Bootstrap core CSS - > < link href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet" / >  </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header">  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar" > <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a rel="nofollow" class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right"> <div class="form-group"> <input type="text" placeholder="Email" class="form-control" /> </div> <div class="form-group"> <input type="password" placeholder="Password" class="form-control" /> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div> <! --/.navbar-collapse --> </div> </nav> <! -- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> Hello, world! <p> This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique. </p> <p> <a rel="nofollow" class="btn btn-primary btn-lg" href="#" role="button" >Learn more &raquo; </a > </p> </div> </div> <div class="container"> <! -- Example row of columns --> <div class="row"> <div class="col-md-4"> <h2>Heading</h2> <p> Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p> <a  rel="nofollow" class="btn btn-default" href="#" role="button" >View details &raquo; </a > </p> </div> <div class="col-md-4"> <h2>Heading</h2> <p> Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p> <a  rel="nofollow" class="btn btn-default" href="#" role="button" >View details &raquo; </a > </p> </div> <div class="col-md-4"> <h2>Heading</h2> <p> Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> <p> <a rel="nofollow" class="btn btn-default" href="#" role="button" >View  details &raquo; </a > </p> </div> </div> <hr /> <footer> <p>&copy; 2016 Company, Inc.</p> </footer> </div> <! -- /container --> <! -- Bootstrap core JavaScript ================================================== --> <! -- Placed at the end of the document so the pages load faster --> <script SRC = "https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js" > < / script > < script SRC = "https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" > < / script > < / body > < / HTML >Copy the code

Once the template file is written, you’re ready to try running the Django web site to achieve your ultimate goal.

Before running, you need to do some preparatory work, the first is to modify the default home page.

Edit the urls.py file below.

Modify the code as follows:

from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), Path ("", include("menuapp.urls"))]Copy the code

Django generally recommends creating a separate URL file for each APP, so add a new urls.py file to the menuApp file, which is the part of the path(“”, include(“menuapp.urls”) referenced above. The code location is shown below.

The code in the file is as follows:

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="defalut"),
]

Copy the code

When accessing the default path http://127.0.0.1:8000/, the index method in the views module will be called, so you need to modify the views.py file as follows:

from django.shortcuts import render
# Create your views here.
def index(request):
    return render(request, "menuapp/index.html")

Copy the code

At this point, the template file is officially loaded.

We were then able to run our application using Python manage.py runServer, but we had another problem, namely the following error.

This error indicates that the template file has not been loaded for two reasons. The first error is the location of the template file, note that it is in the menuApp application directory. If you are not sure, please go back to the above illustration. We haven’t added menuApp to settings.INSTALLED_APPS in settings.py. Importing can’t load the app. Modify settings.py as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'menuapp'
]

Copy the code

If the following page is displayed, the template file is loaded successfully.

7.2 Migrating Static Files in the Recipe System

In the above code index. The HTML file, use the following content, the content is called the CDN to accelerate the url link (after fully studied the front, can be added in this part of knowledge), these addresses completely the decision, is not in our hands, so you need to amend the following content to the menu item in the static files.

< link href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet" / > < script SRC = "https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js" > < / script > < script SRC = "https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" > < / script >Copy the code

Open the Bootstrap 3 website and download the source material in advance.

Copy the downloaded files to the static directory. The final result is shown in the following figure.

Next, learn how to apply static files to Django templates. Step 1: Insert the {% load static %} statement at the top of the template page that requires static files. } {% static ‘js/bootstrap.min.js’ %} {% static ‘js/bootstrap.min.js’ %} The path is because Settings. Py STATIC_URL setting in the value and path, become the final address, such as the static/js/bootstrap. Min. Js step 4: in urls. Increase the static file handler code in py

The code files involved in the preceding steps are modified as follows: The index. HTML is modified

{% load static %} <! DOCTYPE HTML > < HTML lang=" zh-cn "> <head> <meta charset=" utF-8 "> <title> ---- homepage </title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> <body> <! </div> <! -- /container --> <script src="{% static 'js/bootstrap.min.js' %}"></script> </body> </html>Copy the code

The urls.py file is modified as follows. Note that this file belongs to the project directory, not the MenuApp application directory

from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', Admin.site.urls), # include the menuApp URL Settings in the project URL Settings path("", include("menuapp.urls")) ] urlpatterns += staticfiles_urlpatterns()Copy the code

Run the program again using Python manage.py runserver and browse the page to see that the data is ok.

7.3 Django Template Language

The {% statement %} section used above is the template language in Djangos. Templates differ from regular text files in two ways. Templates contain variables that will be replaced with values when the page renders the page, and templates contain logic code called tags.

Variables are denoted by {{variable name}} in double curly braces in the template.

Tags in templates are represented by {% %}, which can contain business logic code, and sometimes start and end tags.

For example, the tag that implements the if statement is written like this:

<ul>
  {% if menu %}
  <li>{{ menu.name }}</li>
</ul>
{% endif %}

Copy the code

Template languages use block and extends tags to implement inheritance, which is simply a collection of common templates.

Block is used for placeholder in the parent template and extends is used for inheritance in the child template.

7.3.1 Splitting a Template

Next, split the template, extracting the headers from the index.html file. Create a new file in the Templates/Menuapp directory.

Frame. HTML is the parent template, where {% block title %}{% endblock%} is the placeholder. {% block Content %}{% endblock %} is a placeholder.

{% load static %} <! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8" /> <title>{% block title %}{% endblock%}</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" /> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <! </div> </nav> <! -- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <! </div> {% block content %}{% endblock %} <script SRC ="{% static 'js/bootstrap.min.js' %}"></script> </body> </html>Copy the code

The index.html file code is as follows:

{% extends "menuApp /frame.html" %} {% block title %} Menu system ---- home {% endBlock %} {% block Content %} <div Class ="container"> Code content </div> <! -- /container --> {% endblock %}Copy the code

The source of the views.py file remains unchanged, as follows:

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "menuapp/index.html")

Copy the code

The running effect is as follows:

7.4 This blog section

This blog post is about creating a simple Django homepage. It will help you learn about the Python Web without any front-end knowledge. Give it a thumbs up.

This article from www.jianshu.com/p/1c81e8625… , if there is infringement, please contact to delete.