Detailed explanation of ORM operation deletion and editing implementation of django

  • 2021-07-26 08:33:08
  • OfStack

Transfer data to server terminal

There are 2 methods, 1 is through the url address and 2 is through the path

Parameter transfer mode to server terminal

1. Through the data http://127.0.0.1: 8000/blog/? id=2

2. Through the path http://17.0.0.1: 8000/blog/20

# url(r'blog/(\d{4})')

Delete function:

In the url file, create an delbook path and get it to id through the address of url for deletion


urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^$',views.index),# Specify 1 Root directory, also pointing to index Page 
  url(r'^index/$',views.index),
  url(r'^addbook/$',views.addbook),
  url(r'^delbook/$',views.delbook), -------------------------------------------del Delete function, corresponding to view function 
  #(\d+) After grouping, it is passed as a parameter to editorbook Function, editorbook ( request , 1 Or 2  Etc.) 
  url(r'^editorbook/(\d+)',views.editorbook),
]

On the index. html page, click the Delete button and add? id = {{book. id}} Books to be deleted,

When get is requested, url is added to id clicked during deletion, and id is obtained to delete #}


<a href="/delbook/?id={{ book.id }}" rel="external nofollow" rel="external nofollow" ><button class="btn btn-primary"> Delete </button></a>

After deleting a record, the order of pages is out of order. id of database is displayed at the front end, and forloop. counter is displayed cyclically from 1 by default, which has nothing to do with id of database.

<td>{{ forloop.counter }}</td>


{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="{% static '/bootstrap-3.3.7/dist/css/bootstrap.css/' %}" rel="external nofollow" >

  <style>

    .container{
      margin-top: 50px;
    }
  </style>

</head>
<body>
<div class="container">
  <div class="row">

    <div class="col-md-8 col-md-offset-2">

    <table class="table table-striped">
      <tr>
        <th>ID</th>
        <th> Book title </th>
        <th> Price </th>
        <th> Date of publication </th>
        <th> Author </th>
        <th> Publishing house </th>
        <th> Classification </th>
        <th> Operation </th>
      </tr>

       {% for book in book_list %}
      <tr>

{#  What is displayed at the front end is the database id , use forloop.counter  Default from 1 Begins a loop display, which is related to the database's id It's irrelevant,    <td>{{ book.id }}</td>#}
          <td>{{ forloop.counter }}</td>-------------------- Displayed in sequence, 
          <td>{{ book.name }}</td>
          <td>{{ book.price }}</td>
          <td>{{ book.Date }}</td>
          <td>{{ book.auth }}</td>
          <td>{{ book.publish }}</td>
          <td>{{ book.classification }}</td>
          <td>
{#             Current ip And ports can be omitted and added automatically, a Tag accesses the addbook Path #}
             <a href="/addbook/" rel="external nofollow" ><button class="btn btn-primary"> Add </button></a>
{#              In get Upon request, url Add the clicked when deleting id , get the id You can delete #}
             <a href="/delbook/?id={{ book.id }}" rel="external nofollow" rel="external nofollow" ><button class="btn btn-primary"> Delete </button></a>
{#              Get the path, #}
            <a href="/editorbook/{{ book.id }}" rel="external nofollow" ><button class="btn btn-primary"> Edit </button></a>
          </td>d

      </tr>
      {% endfor %}
    </table>
  </div>  
 </div>
</div>
</body>
<script>
</script>
</html>

In the views file, edit the delbook function,

django deletion and editing, the premise is to find first, using filter () method, the condition is id or name, etc.,

Step 1, get id from url path by get method,

Step 2, when the id of the database corresponds to the id obtained in the url, the delete () method is executed, the specified record is deleted, and the database will also reduce one record.


# To delete and modify, you must first find the record (object) 
def delbook(request):

  # Filter first, add filtering conditions, and then use delete()
  # Toward server End-to-end parameter mode 
  #1 , through data  http://127.0.0.1:8000/blog/?id=2
  #2,  Passing path  http://17.0.0.1:8000/blog/20
            # url(r'blog/(\d{4})')
  # Add to the front page id Value, {{book.id}}

  # Pass url Get iD Yes get The method, "id" Yes url In key,
  id = request.GET.get("id")
  # Front id Is a field in the table, put get Obtained from the address bar id Assign values to those in the table id You can delete 
  #
  Book.objects.filter(id = id).delete()

  return redirect('/index/')

=======

Edit Function of ORM

Create the editorbook path in the url file and map it to the view function,

Through the access path, get id,


urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^$',views.index),# Specify 1 Root directory, also pointing to index Page 
  url(r'^index/$',views.index),
  url(r'^addbook/$',views.addbook),
  url(r'^delbook/$',views.delbook), -------------------------------------------del Delete function, corresponding to view function 
  #(\d+) After grouping, it is passed as a parameter to editorbook Function, editorbook ( request , 1 Or 2  Etc.) 
  url(r'^editorbook/(\d+)',views.editorbook),-----------------------------editorbook  Edit function, corresponding to 1 View function 
]

Edit an editorbook page,

When editing, get which object to edit,

For example: blog/20, 20 is the id to be obtained

Through the path http://17.0.0.1: 8000/blog/20

# url (r 'blog/(\ d {4})')


{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="{% static '/bootstrap-3.3.7/dist/css/bootstrap.css/' %} " rel="external nofollow" >

  <style>
    .container{
      margin-top: 50px;
    }
  </style>

</head>
<body>


<div class="container">

  <div class="row">

    <div class="col-md-6 col-md-offset-2">
{#      {{ csrf-token }}#}

{#       With post Method to submit data, go to editbook  View function #}
      <form class=editorbook" action="/editorbook/{{ book_obj.id }}/" method="post"> ----------- Plus what I got from the database id No., 

{#       When the Add button is clicked, the view function is executed to add in the database 1 A record , Then add this record to the index Page #}

      <div class="form-group">
        <label for="bookname"> Title: </label>
        <input type="text" class="form-control" id="bookname" name="bookname" value="{{ book_obj.name }}">
      </div>
      <div class="form-group">
        <label for="price"> Price: </label>
        <input type="text" class="form-control" id="price" name="price" value="{{ book_obj.price }}">
      </div>
      <div class="form-group">
        <label for="Date"> Date: </label>
        <input type="text" class="form-control" id="Date" name="Date" value="{{ book_obj.Date }}">
      </div>
      <div class="form-group">
        <label for="auth"> By: </label>
        <input type="text" class="form-control" id="auth" name="auth" value="{{ book_obj.auth }}">
      </div>

      <div class="form-group">
        <label for="publish"> Press: </label>
        <input type="text" class="form-control" id="publish" name="publish" value="{{ book_obj.publish }}">
      </div>

      <div class="form-group">
        <label for="publish"> Classification: </label>
        <input type="text" class="form-control" id="publish" name="classification" value="{{ book_obj.classification }}">
      </div>

      <input class="btn btn-info" type="submit" value=' Submit '>

      </form>
    </div>
  </div>

</div>


</body>

</html>

In views file, write editorbook function,

The form is submitted by post method, and the value of each input box is obtained by post method, and then saved to the database


def editorbook(request,id):

# 2,  Passing path  http://17.0.0.1:8000/blog/20
# url(r'blog/(\d{4})')
# Pass id Gets the object to be modified, and gives each field attribute of the object to the front end value , you can find it in input Box displays the value to edit 
  # book_obj = Book.objects.filter(id = id)[0]
  book_obj = Book.objects.filter(id = id).first()

  if request.method == "POST":
    bookname = request.POST.get('bookname')
    price = request.POST.get('price')
    Date = request.POST.get('Date')
    auth = request.POST.get('auth')
    publish = request.POST.get('publish')
    classification = request.POST.get('classification')


    # Method 2 update Modify and save data   , name  Is a field of the database, bookname Is the front end form In the form   Adj. name Attribute value, the value obtained in the input box is saved to the fields in the database, 
    Book.objects.filter(id = id).update(name = bookname,price = price, Date = Date, auth = auth , publish = publish, classification = classification)

    return redirect('/index/')

  return render(request,'editorbook.html',{'book_obj':book_obj})

Related articles: