简体   繁体   中英

How to insert data from html form into MySQL database using python django

I have created an html form in add_appointment.html and have created database "hospital", table "appointment" in MySQL. I able to view values that I inserted into my database on another html page called view_appointment.html but I do not know how to take html form input from the "add_appointment.html" file and insert it into MySQL database. I searched for a solution everywhere, but I don't see people doing it in python Django, its just php everywhere and python but with flask, if you can help with some link I'll be grateful.
(I'm a beginner, in college, doing a project for the first time. I figured it out somehow until now but got stuck here. My project is almost done except this one thing, I promise if someone helps me the day I become good enough I'll try my best to help others as well )

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")


what you need is a <form method="POST">... </form> that surrounds all <input> fields. Inside that form you also need a <button class="btn" type="submit">Submit</button> so that the data your user enters is sent to the function that renders this html.

This function could look something like this (in 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')

If the appointment always has the same attributes, it also would be easier to look into Models and ModelForms.

I'll take a shot at answering this, although I'm by no means a pro.

It seems like you might be misunderstanding how Django works. From my understanding, Django is going to be interacting with your database for you. Django's models allow you to specify what format you want your data in, and based on that, will create tables in SQL for you. Check out Writing your first Django app part 2 . It has an example of models being defined, and what SQL django generates for those models.

So in your situation, you need 3 things:

  • A model, specifying what data you want to include in your database, for example:

models.py

class AppointmentInformation(models.Model):
    username = models.CharField()
    email = models.EmailField()
    # etc etc
  • A form. You can let Django automatically generate this from the model, or if you'd rather not do that, you can specify the form manually. If you'd like to specify manually, take a look at this post regarding saving Django form data without using ModelForm. In any case, you need to specify how you want the form to display in forms.py . I would suggest looking through the Django form building documentation for this. In your HTML you're currently missing an action (where the browser will return the form data, this will usually be the view that you've written to handle the POST data), and a method (if you're submitting data, this will be post), eg:
<form action="." method="post">
    <!-- form stuff -->
    <input type="submit" value="OK">
</form>
  • A view. This tells Django what you want to do with the form data, and where the form data will be saved. For example:

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})
     

In the above view, the obj.save() function will save the data from your form in the database.

If you're new to Django, I'd really recommend completing the tutorial on their website, and then completing it a second time, it will cement the workflow much better for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM