当前位置:网站首页>Project practice - background employee information management (add, delete, modify, check, login and exit)

Project practice - background employee information management (add, delete, modify, check, login and exit)

2022-07-06 11:08:00 As。

Code below ~https://gitee.com/hedyyi/myobject.git

Here are the notes ~

Project structures, :
1. Create project :django-admin startproject myobject
2. Create an :python manage.py startapp myadmin/web/mobile
3. Create template directory :templates( The template corresponds to each application directory myadmin/web/mobile)
4. Create a static resource directory :static( The directory corresponds to each application directory myadmin/web/mobile, And place the picture file uploads)
5. Create view packages under each application directory views And delete the original views.py (init.py and index.py)
5. Put the project myobject Routing file in url.py Copy one copy to each application directory

6. Project framework configuration ; project myobject Under the table of contents setting.py file
1. Configure the host name information that is allowed to be accessed ALLOWED_HOSTS = ['*']
2. take myadmin,web,mobile Add the application of to the project framework INSTALLED_APPS
3. Configure template directory os.path.join(BASE_DIR,'templates') TEMPLATES
4. Configure the database connection information of the project ;DATABASES
5. Set time zone and language LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai'
6. Configure the static resource directory of the website STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]

7. project myobject Routing under the directory urls.py To configure
Introduction package

from django.urls import include
urlpatterns = [
#path('admin/', admin.site.urls),
path('', include("web.urls")),                #  Default front desk lobby ordering end 
path('myadmin/', include("myadmin.urls")),     #  Background management end 
path('mobile/', include("mobile.urls")),    #  Mobile member end 
]

8. Route under each application directory urls.py To configure

from django.urls import path
from myadmin.views import index
urlpatterns = [
    #  The background page 
    path('', index.index, name="myadmin_index"),
]

9. View under each application directory views/index.py To configure

   from django.shortcuts import render
    from django.http import HttpResponse
    # The background page 
    def index(request):
        return HttpResponse(' Welcome to the order system website background management !')

10. Run the test ; Start the service under the project root directory ;python manage.py runserver

11. Put the background homepage ( Involving front-end content ) from github Download a simple background template :https://github.com/ColorlibHQ/AdminLTE

12. Put the inside of the template bower_components、dist、local、package.json Copy to the background static resource directory of the project static/myadmin/ in

13. stay templates/myadmin establish index Catalog , It creates index.html file , take github downloaded html Copy the contents of the page , Fill the path inside {% static 'myadmin/... '%}

14. stay templates/myadmin establish base.html file , In order to inherit and use , take index.html Cut all the contents inside , Cut and occupy places that do not need inheritance {% block main_body %} {% endblock %}

15. go back to index.html File ;{% extends 'myadmin/base.html' %}; Represents inheritance myadmin Below base.html file

{% block main_body %}
Copy what you cut in the previous step
{% endblock %}

Project practice - Background employee information management -
16. Create... In the database user surface ( Employee account number id, Employee account number , nickname , password , Password interference value , state , Creation time , Modification time )
17. Definition Model class (myadmin/models.py); Field information in the scheduled list
18. New view file (myadmin/views/user.py), It mainly defines the methods of adding, deleting, modifying and querying ;
18. To configure urls Routing information ;(myadmin/urls.py), Put the defined method of adding, deleting, modifying and querying into the route
19. Edit background template , establish templates/myadmin/user/index.html, Inherit base.html Content And will AdminLTE Copy part of the contents in, modify and copy to index.html that will do ( Mainly change the field information displayed in the list and make a cycle and various judgments )
20. edit base.html Content , Reverse parse the home page and the address managed by the employee , home page {% url ‘myadmin_index’ %}; Employee management {% url ‘myadmin_user_index’ %}

21. List paging operation ; stay myadmin/views/user.py Add paging operation in browsing method ;
22.templates/myadmin/user/index.html Circular list data in the file , And add the judgment of selecting the current page and the previous page and the next page

23. List search ; Copy the search criteria to index.html (

) below

              <div class="input-group-btn">
                <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
              </div>
            </div>
            </form>

24. stay myadmin/views/user.py Continue to package and improve methods ;
“”“ obtain , Judge and encapsulate keyword Key search ”“”
mywhere = []
kw = request.GET.get(“keyword”,None)
if kw:
#ulist = ulist.filter(username__contains=kw) # Single search
ulist = ulist.filter(Q(username__contains=kw) | Q(nickname__contains=kw)) #Q Is the relationship expressed as and
mywhere.append(“keyword=”+kw)

25. stay index.html Perfect can also be selected when turning pages according to search conditions

  <li><a href="{% url 'myadmin_user_index' pIndex|add:-1 %}?{
    { mywhere|join:'&' }}">&laquo;</a></li>
                  {
    % for p in plist %}
                {
    # According to the judgment condition data, the current page list #}
                <li {
    % if p == pIndex %} class="active"{
    % endif %}><a href="{% url 'myadmin_user_index' p %}?{
    { mywhere|join:'&' }}">{
    {
     p }}</a></li>
                  {
    % endfor %}
                {
    # The next page #}
                <li><a href="{% url 'myadmin_user_index' pIndex|add:1 %}?{
    { mywhere|join:'&' }}">&raquo;</a></li>

26. Add operation ;myadmin/views/user.py
add; Only load pages return render(request, "myadmin/user/add.html")
insert Execution add ;return render(request, "myadmin/info.html", context); The content encapsulation required for the addition operation

27. establish myadmin/user/add.html; stay AdminLTE Find add.html dependent , Just copy the part ; Remember to inherit

{% extends “myadmin/base.html” %}
{% block main_body %}
Put the added content here
{% endblock %}

28. establish myadmin/info.html; It is mainly to add the prompt after success .

{
    % extends "myadmin/base.html" %}
{
    % block main_body %}
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h4>
         message :
      </h4>
    </section>

    <div class="pad margin no-print">
      <div class="callout callout-info" style="margin-bottom: 0!important;padding-left: 50px">
        <h3><i class="fa fa-exclamation-triangle"></i>  &nbsp; {
    {
     info }}</h3>
      </div>
    </div>
{
    % endblock %}

29. stay myadmin/user/indexl.html; change add.html This part ;

 <a role="button" href="{% url 'myadmin_user_add' %}" class="btn btn-primary">

30. You can successfully add the operation on the page

31. Delete operation ;myadmin/views/user.py; Continue to package and improve

def delete(request,uid=0):
    ''' Execution add '''
    try:
        ob = User.objects.get(id=uid)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {
    "info": " Delete successful !"}
    except Exception as err:
        print(err)
        context = {
    "info": " Delete failed "}
    return render(request, "myadmin/info.html", context)

32. stay myadmin/user/index.html, In the operation of delete button , hold url Render in

 <button type="button" onclick="doDel('{% url 'myadmin_user_delete' vo.id %}')" class="btn btn-danger btn-xs">
 <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>  Delete </button>

33. stay templates/myadmin/base.html Add the prompt message after the deletion is successful

 <script type="text/javascript">
    function doDel(url){
    
    Modal.confirm({
    
        msg: " Are you sure you want to delete ?",
        title: '  message ',
        btnok: ' determine ',
        btncl:' Cancel '
      }).on(function (e){
    
        if(e){
    
            window.location.href=url;
        }
      });
    }

34. You can delete the successful operation on the page

35. Edit and modify ; encapsulation edit and update Method ;

def edit(request,uid=0):
    ''' Execution add '''
    try:
        ob = User.objects.get(id=uid)
        context = {
    "user": ob}
        return render(request, "myadmin/user/edit.html", context)
    except Exception as err:
        print(err)
        context = {
    "info": " No information found to modify "}
        return render(request, "myadmin/info.html", context)

def update(request,uid):
    ''' Execution add '''
    try:
        ob = User.objects.get(id=uid)
        ob.status = request.POST['status']
        ob.nickname = request.POST['nickname']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {
    "info": " Modification successful !"}
    except Exception as err:
        print(err)
        context = {
    "info": " Modification failed !"}
    return render(request, "myadmin/info.html", context)

36. newly added templates/user/edit.html page ( Copy add.html You can modify it again )

37. modify index.html Jump link edited in

           <a type="button" href="{% url 'myadmin_user_edit' vo.id %}" class="btn btn-success btn-xs">
              <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>  edit </a>

38. Add, delete, modify and check to complete the operation

39. After the actual combat of the project, the console administrator logs in and exits , Will use Django In the framework session, and session The information is stored in the database , So first use the data migration command in MySQL In the database, there are some Django Default built-in table . python manage.py migrate

40. Add Middleware , This middleware judges whether to log in to the background website access , Just visit URL The address is “/admin” The first one will perform login judgment verification

41. stay myadmin Create Middleware in the application , create a file :myobject/myadmin/shopmiddleware.py

#  Custom middleware class 
from django.shortcuts import redirect
from django.urls import reverse

import re

class ShopMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.
        print("ShopMiddleware")

    def __call__(self, request):

        #  Gets the current request path 
        path = request.path
        #print("mycall..."+path)

        #  Background request routing judgment 
        #  Define the route that can be accessed without login in the background of the website url
        urllist = ['/myadmin/login','/myadmin/dologin','/myadmin/logout','/myadmin/verify']
        #  Determine whether the current request is to visit the website background , also path be not in urllist in 
        if re.match(r"^/myadmin",path) and (path not in urllist):
            #  Judge whether the current user is not logged in 
            if "adminuser" not in request.session:
                #  Execute login interface jump 
                return redirect(reverse('myadmin_login'))


        #  Request to continue 
        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        return response

42. Register the customized middleware into the project , edit myobject/settings.py The configuration file , Add code

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'myadmin.shopmiddleware.ShopMiddleware',     # Register middleware 
]

43. Configure the routing 、 Template and test middleware ; Configure the routing myobject/myadmin/urls.py Add the following code

  #  Background administrator routing 
    path('login', index.login, name="myadmin_login"),
    path('dologin', index.dologin, name="myadmin_dologin"),
    path('logout', index.logout, name="myadmin_logout"),

44. Authoring views myobject/myadmin/views/index.py file And add the following code

# ============== Background administrator operation ====================
#  Member login form 
def login(request):
    return render(request,'myadmin/index/login.html')

#  Members execute login 
def dologin(request):
    pass

#  Members withdraw 
def logout(request):
    pass

45. Create login template file : templates/myadmin/index/login.html The code is as follows

{
    % load static from static%}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title> Background management login interface </title>
  <!--  Support responsive layout  -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/bootstrap/dist/css/bootstrap.min.css' %}">
  <!--  Hieroglyphs  -->
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/font-awesome/css/font-awesome.min.css' %}">
  <!--  Icon  -->
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/Ionicons/css/ionicons.min.css' %}">
  <!--  Theme style  -->
  <link rel="stylesheet" href="{% static 'myadmin/dist/css/AdminLTE.min.css' %}">
  <!-- AdminLTE  The skin . The choice here is skin-blue style , We can also have other skin options . -->
  <link rel="stylesheet" href="{% static 'myadmin/dist/css/skins/skin-blue.min.css' %}">
  <!--  compatible IE9 The following browsers  -->
  <!--[if lt IE 9]>
  <script src="{% static 'myadmin/local/js/html5shiv.min.js' %}"></script>
  <script src="{% static 'myadmin/local/js/respond.min.js' %}"></script>
  <![endif]-->
  <!-- Google Font -->
  <link rel="stylesheet" href="{% static 'myadmin/local/css/google_fonts.css' %}">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">
    <a href="index2.html"><b> Background management of catering system </b></a>
  </div>
  <!-- /.login-logo -->
  <div class="login-box-body">
    <p class="login-box-msg" style="color:red"> Login account or password error !</p>

    <form action="index2.html" method="post">
      <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder=" account number ">
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder=" password ">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="text" class="form-control" style="width:150px" placeholder=" Verification Code ">
        <span class="form-control-feedback" style="width:150px">
            <img src="{% static 'myadmin/dist/img/verify.png' %}"/>
        </span>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <button type="submit" class="btn btn-primary btn-block btn-flat"> Sign in </button>
        </div>
        <!-- /.col -->
      </div>
    </form>

  </div>
  <!-- /.login-box-body -->
</div>
<!-- /.login-box -->

<!-- jQuery 3 -->
<script src="{% static 'myadmin/bower_components/jquery/dist/jquery.min.js' %}"></script>
<!-- Bootstrap 3.3.7 -->
<script src="{% static 'myadmin/bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>
</body>
</html>

46. Start service test , The backstage of the website can't get in , Unified call jump login page
47. Login and logout ; Configure the routing myobject/myadmin/urls.py Add the following code ( step 43 Already added , Can be fooled )

  #  Background administrator routing 
    path('login', index.login, name="myadmin_login"),
    path('dologin', index.dologin, name="myadmin_dologin"),
    path('logout', index.logout, name="myadmin_logout"),

48. Write a view file , Authoring views myobject/myadmin/views/index.py file And add the following code

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from myadmin.models import User

# ============== Background administrator operation ====================
def login(request):
    ''' Load the login page '''
    return render(request,"myadmin/index/login.html")

def dologin(request):
    ''' Perform a login '''
    try:
        # Get user information according to the login account 
        user = User.objects.get(username=request.POST['username'])
        #  Verify whether the current user status is administrator 
        if user.status == 6:
            # Get the password and md5
            import hashlib
            md5 = hashlib.md5()
            n = user.password_salt
            s = request.POST['pass']+str(n) 
            md5.update(s.encode('utf-8'))
            #  Verify that the password is correct 
            if user.password_hash == md5.hexdigest():
                #  Set the current login successful user information as adminuser This key Put in session in 
                request.session['adminuser']=user.toDict()
                return redirect(reverse('myadmin_index'))
            else:
                context={
    "info":" Login password error !"}
        else:
            context={
    "info":" This user is not a background management account !"}
    except Exception as err:
        print(err)
        context={
    "info":" Login account does not exist !"}
    return render(request,"myadmin/index/login.html",context)

def logout(request):
    ''' Execute exit '''
    del request.session['adminuser']
    return redirect(reverse('myadmin_login'))

49. Create login template file : templates/myadmin/index/login.html The code is as follows

{
    % load static from static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title> Background management login interface </title>
  <!--  Support responsive layout  -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/bootstrap/dist/css/bootstrap.min.css' %}">
  <!--  Hieroglyphs  -->
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/font-awesome/css/font-awesome.min.css' %}">
  <!--  Icon  -->
  <link rel="stylesheet" href="{% static 'myadmin/bower_components/Ionicons/css/ionicons.min.css' %}">
  <!--  Theme style  -->
  <link rel="stylesheet" href="{% static 'myadmin/dist/css/AdminLTE.min.css' %}">
  <!-- AdminLTE  The skin . The choice here is skin-blue style , We can also have other skin options . -->
  <link rel="stylesheet" href="{% static 'myadmin/dist/css/skins/skin-blue.min.css' %}">
  <!--  compatible IE9 The following browsers  -->
  <!--[if lt IE 9]>
  <script src="{% static 'myadmin/local/js/html5shiv.min.js' %}"></script>
  <script src="{% static 'myadmin/local/js/respond.min.js' %}"></script>
  <![endif]-->
  <!-- Google Font -->
  <link rel="stylesheet" href="{% static 'myadmin/local/css/google_fonts.css' %}">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">
    <a href="index2.html"><b> Background management of catering system </b></a>
  </div>
  <!-- /.login-logo -->
  <div class="login-box-body">
    <p class="login-box-msg" style="color:red">{
    {
     info }}</p>
    <form action="{% url 'myadmin_dologin' %}" method="post">
      {
    % csrf_token %}
      <div class="form-group has-feedback">
        <input type="text" name="username" class="form-control" placeholder=" account number ">
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" name="pass"  class="form-control" placeholder=" password ">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="text" name="code" style="display:inline;width:170px;" class="form-control"  placeholder=" Verification Code ">
           <img src="{% static 'myadmin/dist/img/verify.png' %}"/>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <button type="submit" class="btn btn-primary btn-block btn-flat"> Sign in </button>
        </div>
        <!-- /.col -->
      </div>
    </form>

  </div>
  <!-- /.login-box-body -->
</div>
<!-- /.login-box -->

<!-- jQuery 3 -->
<script src="{% static 'myadmin/bower_components/jquery/dist/jquery.min.js' %}"></script>
<!-- Bootstrap 3.3.7 -->
<script src="{% static 'myadmin/bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>
</body>
</html>

50. Modify template file :templates/myadmin/base.html The code is as follows , The code is in the header ,155 Row or so

<ul class="dropdown-menu">
  <!-- The user image in the menu -->
  <li class="user-header">
    <img src="{% static 'myadmin/dist/img/user2-160x160.jpg'%}" class="img-circle" alt="User Image">

    <p>
      {
    {
    request.session.adminuser.nickname}} -  Administrators 
      <small>{
    {
     request.session.adminuser.create_at }} Join in </small>
    </p>
  </li>
  <!-- Menu Footer-->
  <li class="user-footer">
    <div class="pull-left">
      <a href="#" class="btn btn-default btn-flat"> Personal information </a>
    </div>
    <div class="pull-right">
      <a href="{% url 'myadmin_logout' %}" class="btn btn-default btn-flat"> refund   Out </a>
    </div>
  </li>
</ul>

51. Start service test , You can test whether the website background can be used . Note that only administrators can log in
52. Add the verification code at the background login , Configure the routing myobject/myadmin/urls.py Add the following code

#  Background administrator routing 
    path('login', index.login, name="myadmin_login"),
    path('dologin', index.dologin, name="myadmin_dologin"),
    path('logout', index.logout, name="myadmin_logout"),
    path('verify', index.verify, name="myadmin_verify"), # Verification Code 

53. Authoring views myobject/myadmin/views/index.py file And add the following code , Add the output verification code method in the background administrator operation verify(), Set font file STXIHEI.TTF Copied to the static/ Under the table of contents

# ============== Background administrator operation ====================
#  Member login form 
def verify(request):
    # Introduce random function module 
    import random
    from PIL import Image, ImageDraw, ImageFont
    # Defining variables , The background color used in the picture 、 wide 、 high 
    #bgcolor = (random.randrange(20, 100), random.randrange(
    # 20, 100),100)
    bgcolor = (242,164,247)
    width = 100
    height = 25
    # Create a picture object 
    im = Image.new('RGB', (width, height), bgcolor)
    # Create a brush object 
    draw = ImageDraw.Draw(im)
    # Call the paintbrush point() Function to draw noise 
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # Define alternatives to the verification code 
    #str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '0123456789'
    # Random selection 4 Value as verification code 
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # Construct font objects ,ubuntu The font path of is “/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('static/arial.ttf', 21)
    #font = ImageFont.load_default().font
    # Construct font color 
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # draw 4 A word 
    draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
    # Release the paintbrush 
    del draw
    # Deposit in session, For further verification 
    request.session['verifycode'] = rand_str
    """ python2 For the  #  Memory file operation  import cStringIO buf = cStringIO.StringIO() """
    #  Memory file operation --> This method is python3 Of 
    import io
    buf = io.BytesIO()
    # Save pictures in memory , The file type is png
    im.save(buf, 'png')
    # Return the image data in memory to the client ,MIME The type is picture png
    return HttpResponse(buf.getvalue(), 'image/png')

54. Set release in middleware , To write :myobject/common/shopmiddleware.py file , stay call() Methodical urllist Add... To the variable :/myadmin/verify

 #  Define the route that can be accessed without login in the background of the website url
    urllist = ['/myadmin/login','/myadmin/dologin','/myadmin/logout','/myadmin/verify']

55. Use the verification code in the login template , Login template file : templates/myadmin/index/login.html Add the code as follows

  <p class="login-box-msg" style="color:red">{
    {
     info }}</p>
    <form action="{% url 'myadmin_dologin' %}" method="post">
      {
    % csrf_token %}
      <div class="form-group has-feedback">
        <input type="text" name="username" class="form-control" placeholder=" account number ">
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" name="pass"  class="form-control" placeholder=" password ">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="text" name="code" style="display:inline;width:170px;" class="form-control"  placeholder=" Verification Code ">
           <img src="{% url 'myadmin_verify'%}" onclick="this.src='{% url 'myadmin_verify' %}?sn='+Math.random()" style="float:right;margin:5px 20px;" />
      </div>
      <div class="row">
        <div class="col-xs-12">
          <button type="submit" class="btn btn-primary btn-block btn-flat"> Sign in </button>
        </div>
        <!-- /.col -->
      </div>
    </form>

56. Verification code verification , Edit view file :myobject/myadmin/views/index.py file , Execute login method for members in the view file dologin() Add validation code

#  Members execute login 
def dologin(request):
    ''' Perform a login '''
    # Verification judgment 
    verifycode = request.session['verifycode']
    code = request.POST['code']
    if verifycode != code:
        context = {
    'info':' Verification code error !'}
        return render(request,"myadmin/index/login.html",context)

    try:
        # Get user information according to the login account 
        user = User.objects.get(username=request.POST['username'])
        #  Verify whether the current user status is administrator 
        if user.status == 6:
            # Get the password and md5
            import hashlib
            md5 = hashlib.md5()
            n = user.password_salt
            s = request.POST['pass']+str(n) 
            md5.update(s.encode('utf-8'))
            #  Verify that the password is correct 
            if user.password_hash == md5.hexdigest():
                #  Set the current login successful user information as adminuser This key Put in session in 
                request.session['adminuser']=user.toDict()
                return redirect(reverse('myadmin_index'))
            else:
                context={
    "info":" Login password error !"}
        else:
            context={
    "info":" This user is not a background management account !"}
    except Exception as err:
        print(err)
        context={
    "info":" Login account does not exist !"}
    return render(request,"myadmin/index/login.html",context)

57. Start service test , You can test whether the website background can be used . Note that only administrators can log in

58. Backstage store information management ; In the database osdb Created in shop surface

CREATE TABLE `category` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT ' Classification of dishes id',
  `shop_id` int(11) DEFAULT NULL COMMENT ' The store id',
  `name` varchar(50) DEFAULT NULL COMMENT ' Category name ',
  `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT ' state :1 normal  9 Delete ',
  `create_at` datetime DEFAULT NULL COMMENT ' Add the time ',
  `update_at` datetime DEFAULT NULL COMMENT ' Modification time ',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

59. Defining models Model class ; Get into myadmin Edit in the application directory :myobject/myadmin/models.py Model file

# Store information model 
class Shop(models.Model):
    name = models.CharField(max_length=255)        # Shop name 
    cover_pic = models.CharField(max_length=255)# Cover picture 
    banner_pic = models.CharField(max_length=255)# Icon Logo
    address = models.CharField(max_length=255)    # Shop address 
    phone = models.CharField(max_length=255)    # contact number 
    status = models.IntegerField(default=1)        # state :1 normal /2 Pause /9 Delete 
    create_at = models.DateTimeField(default=datetime.now)    # Creation time 
    update_at = models.DateTimeField(default=datetime.now)    # Modification time 

    def toDict(self):
        shopname = self.name.split("-")
        return {
    'id':self.id,'name':shopname[0],'shop':shopname[1],'cover_pic':self.cover_pic,'banner_pic':self.banner_pic,'address':self.address,'phone':self.phone,'status':self.status,'create_at':self.create_at.strftime('%Y-%m-%d %H:%M:%S'),'update_at':self.update_at.strftime('%Y-%m-%d %H:%M:%S')}

    class Meta:
        db_table = "shop"  #  Change table name 

60. project urls Routing information configuration ; Open the root route file :myobject/myadmin/urls.py Routing file , Edit routing configuration information

from django.urls import path

from myadmin.views import index
from myadmin.views import user
from myadmin.views import shop

urlpatterns = [
    ...

    # Store routing 
    path('shop/<int:pIndex>', shop.index, name="myadmin_shop_index"),
    path('shop/add', shop.add, name="myadmin_shop_add"),
    path('shop/insert', shop.insert, name="myadmin_shop_insert"),
    path('shop/del/<int:sid>', shop.delete, name="myadmin_shop_del"),
    path('shop/edit/<int:sid>', shop.edit, name="myadmin_shop_edit"),
    path('shop/update/<int:sid>', shop.update, name="myadmin_shop_update"),

    ...
]

61. Edit view file ; Create a new view file :myobject/myadmin/views/shop.py view file , And edit it

62. Write template file ; Open the parent class template :/templates/myadmin/base.html , Edit the navigation bar code

<!--  Navigation list , You can change the icon yourself  -->
<li class="active"><a href="{% url 'myadmin_index' %}"><i class="fa fa-home"></i> <span> home page </span></a></li>
<li><a href="{% url 'myadmin_user_index' 1 %}"><i class="fa fa-users"></i> <span> Employee management </span></a></li>
<li><a href="{% url 'myadmin_shop_index' 1 %}"><i class="fa fa-sitemap"></i> <span> Shop management </span></a></li>

63. Backstage store information browsing page template :/templates/myadmin/shop/index.html

{
    % extends "myadmin/base.html" %}

{
    % block main_body %}
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
         Dish category management 
        <small> Ordering system background management </small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i>  home page </a></li>
        <li class="active"> Dish classification information management </li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content container-fluid">

      <div class="row">
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header">
              <h3 class="box-title"><i class="fa fa-calendar"></i>  Food classification information table </h3>

              <div class="box-tools">
                <div class="input-group input-group-sm" style="width: 150px;">
                  <input type="text" name="table_search" class="form-control pull-right" placeholder="Search">

                  <div class="input-group-btn">
                    <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
                  </div>
                </div>
              </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive no-padding">
              <table class="table table-hover">
                <tr>
                  <th>ID</th>
                  <th> Shop name </th>
                  <th> Category name </th>
                  <th> current state </th>
                  <th> Add the time </th>
                  <th> Modification time </th>
                  <th> operation </th>
                </tr>
                {
    % for vo in categorylist %}
                <tr>
                  <td>{
    {
     vo.id }}</td>
                  <td>{
    {
     vo.shopname }}</td>
                  <td>{
    {
     vo.name }}</td>
                  <td>
                    {
    % if vo.status == 1 %}
                      <span style="color:green"> normal </span>
                    {
    % elif vo.status == 9 %}
                      <span style="color:red"> deleted </span>
                    {
    % else %}
                      <span style="color:red"> Unknown status </span>
                    {
    % endif %}
                  </td>
                  <td width="12%">{
    {
     vo.create_at|date:'Y-m-d' }}</td>
                  <td width="12%">{
    {
     vo.update_at|date:'Y-m-d' }}</td>
                  <td width="25%">
                    <a href="{% url 'myadmin_category_edit' vo.id %}" class="btn btn-success btn-xs">
                      <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>  edit </a>
                    <button type="button" onclick="doDelete('{% url 'myadmin_category_del' vo.id %}')" class="btn btn-danger btn-xs">
                      <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>  Delete </button>
                    <a href="#" class="btn btn-warning btn-xs">
                      <span class="glyphicon glyphicon-search" aria-hidden="true"></span>  View dishes </a>
                  </td>
                </tr>
                {
    % endfor %}
              </table>
            </div>
            <!-- /.box-body -->
            <div class="box-footer clearfix">
              <a role="button" href="{% url 'myadmin_category_add' %}" class="btn btn-primary">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>  Add dish classification </a>
                <ul class="pagination pagination-sm no-margin pull-right">
                    <li><a href="{% url 'myadmin_category_index' pIndex|add:-1 %}?{
    {mywhere|join:'&'}}">&laquo;</a></li>
                    {
    % for p in plist %}
                    <li {
    % if p == pIndex %}class="active"{
    % endif %}><a href="{% url 'myadmin_category_index' p %}?{
    {mywhere|join:'&'}}">{
    {
    p}}</a></li>
                    {
    % endfor %}
                    <li><a href="{% url 'myadmin_category_index' pIndex|add:1 %}?{
    {mywhere|join:'&'}}">&raquo;</a></li>
                </ul>
            </div>
          </div>
          <!-- /.box -->
        </div>
      </div>

    </section>
    <!-- /.content -->
{
    % endblock %}

64. Add a form page template to the backstage store information :/templates/myadmin/shop/add.html

{
    % extends "myadmin/base.html" %}


{
    % block main_body %}
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
         Dish classification management 
        <small> Ordering system background management </small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i>  home page </a></li>
        <li class="active"> Dish classification information management </li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content container-fluid">

      <div class="row">
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header">
                <h2 class="box-title"><span class="glyphicon glyphicon-calendar" aria-hidden="true"> Add dish classification information </h2>
            </div>
            <!-- /.box-header -->
            <!-- form start -->
            <form class="form-horizontal" action="{% url 'myadmin_category_insert' %}" method="post">
                {
    % csrf_token %}
              <div class="box-body">
                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-2 control-label"> Shop name :</label>

                  <div class="col-sm-4">
                    <select name="shop_id" class="form-control select2" style="width: 100%;">
                      {
    % for svo in shoplist %}
                        <option value="{
    { svo.id }}">{
    {
     svo.name }}</option>
                      {
    % endfor %}
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-2 control-label"> Category name :</label>

                  <div class="col-sm-4">
                    <input type="text" name="name" class="form-control" id="inputText2" placeholder=" Category name " />
                  </div>
                </div>
              </div>
              <!-- /.box-body -->
              <div class="box-footer">
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-primary"> Submit </button> &nbsp; 
                  <button type="reset" class="btn btn-default"> Reset </button>
                <div class="col-sm-offset-2 col-sm-10">
              </div>
              <!-- /.box-footer -->
            </form>
          </div>
          <!-- /.box -->
        </div>
      </div>

    </section>
    <!-- /.content -->
{
    % endblock %}

65. Background store information editing template :/templates/myadmin/shop/edit.html

{
    % extends "myadmin/base.html" %}


{
    % block main_body %}
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
         Dish classification management 
        <small> Ordering system background management </small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i>  home page </a></li>
        <li class="active"> Dish classification information management </li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content container-fluid">

      <div class="row">
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header">
                <h2 class="box-title"><span class="glyphicon glyphicon-calendar" aria-hidden="true"> Edit dish classification information </h2>
            </div>
            <!-- /.box-header -->
            <!-- form start -->
            <form class="form-horizontal" action="{% url 'myadmin_category_update' category.id %}" method="post">
                {
    % csrf_token %}
              <div class="box-body">
                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-2 control-label"> Shop name :</label>

                  <div class="col-sm-4">
                    <select name="shop_id" class="form-control select2" style="width: 100%;">
                      {
    % for svo in shoplist %}
                        <option value="{
    { svo.id }}" {
    % if category.shop_id == svo.id %}selected{
    % endif %} >{
    {
     svo.name }}</option>
                      {
    % endfor %}
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-2 control-label"> Category name :</label>

                  <div class="col-sm-4">
                    <input type="text" name="name" value="{
    { category.name }}" class="form-control" id="inputText2" placeholder=" Category name " />
                  </div>
                </div>
              </div>
              <!-- /.box-body -->
              <div class="box-footer">
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-primary"> preservation </button> &nbsp; 
                  <button type="reset" class="btn btn-default"> Reset </button>
                <div class="col-sm-offset-2 col-sm-10">
              </div>
              <!-- /.box-footer -->
            </form>
          </div>
          <!-- /.box -->
        </div>
      </div>

    </section>
    <!-- /.content -->
{
    % endblock %}

66. Start the service under the project root directory , And use the browser to access the test
( See bug, Modify the operating , Re upload shop pictures and logo Not saved to data )

67. After the actual combat of the project, Taiwan cuisine category information management

After the actual combat of the project, Taiwan cuisine information management

Background member information management of project practice

原网站

版权声明
本文为[As。]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912299708.html