Django Pycharm creates and runs django projects, combined with Mysql

1.Create project

1.1 First pip install django in the virtual environment

1.2 pycharm creates project

The interpreter selects the corresponding virtual environment

Automatically generate folder after successful creation

Enter code to create app

python manage.py startapp BankManagerSys

Register the app in settings

Register the web page in urls (the specific code should be written in app.view)

 

Write code in view

Click to get started.

click the link

 Enter successfully.

 

2. Code to process database data

1. views.py, receive the form

def index (request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # 处理表单数据

            # 连接数据库
            conn = pymysql.connect(host='192.168.2.101', port=3306, user='mgs', password='abc123!Test',
                                   db='mgsdb', charset='utf8mb4')
            # 创建游标对象
            cursor = conn.cursor()
            # 执行SQL查询和更新操作
            account_id = form.cleaned_data['account_id']
            branch_name = form.cleaned_data['branch_name']
            account_balance = form.cleaned_data['account_balance']
            cursor.execute("INSERT INTO mgs_account (account_id, branch_name, account_balance ) VALUES (%s, %s, %s)", (account_id, branch_name, account_balance ))
            # 提交更改
            conn.commit()
            # 关闭游标和连接
            cursor.close()
            # 返回响应
            return render(request, 'success.html', {'name': account_id})
    else:
        form = MyForm()
    return render(request, 'my_form.html', {'form': form})

 form = MyForm(request.POST) # Convert the form sent from the web page to the set format

The following code updates the data into the database

2. Set the form format in class my form

3.html format

{ { form.as_p }}, here the form is displayed on the html page

{% extends 'base.html' %}

{% block content %}
  <h1>创建账户</h1>
  <form method="post">
    {% csrf_token %}
    {
   
   { form.as_p }}
    <button type="submit">开户</button>
  </form>
{% endblock %}

3. Final effect

3.1 Front-end page

3.2 Database

Inserted successfully

4. Follow-up

Beautify the front-end page and add css

Reference links:

1-10 Request and Response_bilibili_bilibili

Python Django Pycharm creates and runs django projects_JYliangliang's blog-CSDN blog

Guess you like

Origin blog.csdn.net/qq_44874004/article/details/130849619