【问题标题】:How to insert data from html form into MySQL database using python django如何使用 python django 将数据从 html 表单插入 MySQL 数据库
【发布时间】:2022-01-28 00:18:47
【问题描述】:

我在 add_appointment.html 中创建了一个 html 表单,并在 MySQL 中创建了数据库“hospital”、表“appointment”。我可以在另一个名为 view_appointment.html 的 html 页面上查看我插入数据库的值,但我不知道如何从“add_appointment.html”文件中获取 html 表单输入并将其插入 MySQL 数据库。 我到处寻找解决方案,但我没有看到人们在 python Django 中这样做,它只是到处都是 php,而 python 但使用烧瓶,如果你能提供一些链接,我将不胜感激。
(我是一个初学者,在大学里,第一次做一个项目。直到现在我想通了,但被困在这里。我的项目几乎完成了,除了这件事,我保证如果有人帮助我,我成为很好,我也会尽力帮助别人)

filename: add_appointment.html
<!doctype html>
<html lang="en">
<head><title>Add Appointment</title></head>
<body>
<div class="container">
               <form id="form" class="form">
                   <div class="from-control">
                   <h1>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Add Appointment</h1>
                   <div class="form-control">
                       <label for="username">Name</label>
                       <input type="text" id="name" placeholder="Enter name">
                       <small>Error Message</small>
                   </div>
                   <div class="form-control">
                       <label for="email">Email</label>
                       <input type="text" id="email" placeholder="Enter email">
                       <small>Error Message</small>
                   </div>
                   <div class="form-control">
                       <label for="id">ID</label>
                       <input type="text" id="id" placeholder="Enter ID">
                       <small>Error Message</small>
                   </div>
                   <div class="form-control">
                       <label for="category">Disease</label>
                       <input type="text" id="category" placeholder=" disease">
                       <small>Error Message</small>
                   </div>
                   <button>Add</button>
               </form>
           </div>
       <center><a href="view_appointment.html">View Appointments</a></center>
</body>
</html>
filename: appointment.py
import mysql.connector
import webbrowser

conn = mysql.connector.connect(user='root', password='Newtonlaw3', host='localhost', database='hospital')

if conn:
    print("connected successfully")
else:
    print("connection not established")

select_admin = """SELECT * FROM appointment"""
cursor = conn.cursor()
cursor.execute(select_admin)
result = cursor.fetchall()

p = []

tbl = "<tr><td><NAME</td><td>EMAIL</td><td>ID<td>SPECIALITY</td></tr>"
p.append(tbl)

for row in result:
    a = "<tr><td>%s</td>" % row[0]
    p.append(a)
    b = "<td>%s</td>" % row[1]
    p.append(b)
    c = "<td>%d</td>" % row[2]
    p.append(c)
    d = "<td>%s</td></tr>" % row[3]
    p.append(d)

contents = '''<!DOC TYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>
<head>
<meta content ="text/html; charset=ISO-8859-1"
http-equiv = "content-type">
<title> View Appointments</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
''' % (p)

filename = 'view_appointment.html'

def main(contents, filename):
    output = open(filename, 'w')
    output.write(contents)
    output.close()


main(contents, filename)
webbrowser.open(filename)

if (conn.is_connected()):
    cursor.close()
    conn.close()
    print("my sql connection is closed")


【问题讨论】:

    标签: python html mysql django


    【解决方案1】:

    您需要的是一个包围所有&lt;input&gt; 字段的&lt;form method="POST"&gt; ... &lt;/form&gt;。 在该表单中,您还需要一个&lt;button class="btn" type="submit"&gt;Submit&lt;/button&gt;,以便将用户输入的数据发送到呈现此 html 的函数。

    这个函数可能看起来像这样(在views.py中):

    def add_appointment(request):
        if request.method == 'POST':
            # retrieve data from input fields
            # save data to MySQL
            return redirect('view_appointment')
        return render(request, 'add_appointment')
    
    

    如果约会总是具有相同的属性,那么查看模型和模型表单也会更容易。

    【讨论】:

      【解决方案2】:

      我会尝试回答这个问题,虽然我绝不是专业人士。

      您似乎误解了 Django 的工作原理。据我了解,Django 将为您与您的数据库进行交互。 Django 的models 允许您指定您希望数据采用的格式,并在此基础上为您创建 SQL 表。查看Writing your first Django app part 2 。它有一个正在定义的模型示例,以及 SQL django 为这些模型生成的内容。

      所以在你的情况下,你需要三样东西:

      • 一个模型,指定要包含在数据库中的数据,例如:

      models.py

      class AppointmentInformation(models.Model):
          username = models.CharField()
          email = models.EmailField()
          # etc etc
      
      • 表格。您可以让 Django 从模型中自动生成它,或者如果您不想这样做,您可以手动指定表单。如果您想手动指定,请查看this 关于在不使用 ModelForm 的情况下保存 Django 表单数据的帖子。在任何情况下,您都需要指定表单在forms.py 中的显示方式。我建议为此查看Django form building documentation。在您的 HTML 中,您当前缺少一个操作(浏览器将返回表单数据,这通常是您为处理 POST 数据而编写的视图)和一个方法(如果您正在提交数据,这个将发布),例如:
      <form action="." method="post">
          <!-- form stuff -->
          <input type="submit" value="OK">
      </form>
      
      • 一个视图。这告诉 Django 你想对表单数据做什么,以及表单数据将被保存在哪里。例如:

      views.py

      def create_appointment(request):
          if request.method == 'POST':
              # Whatever you named your form in forms.py
              form = ExampleForm(request.POST)
              if form.is_valid():
                  # Whatever you named your model.
                  obj = ExampleModel()
                  # If you used model form, you can use obj.save(). If you 
                  # manually specified your form, you'll have to follow the example 
                  # in the link above regarding saving data without model form
          else:
               # If request.method == "GET", render form to be filled in webpage.
               form = ExampleForm()
               return render(request, 'add_appointment.html', {'form':form})
           
      

      在上面的视图中,obj.save() 函数会将表单中的数据保存到数据库中。

      如果您是 Django 新手,我真的建议您在他们的网站上完成本教程,然后再完成第二次,它将更好地巩固工作流程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        • 2019-01-12
        • 1970-01-01
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多