django curd demo

Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary support for Update Views but let’s check how it is done manually through a function-based view. This article revolves around Update View which involves concepts such as Django FormsDjango Models

For Update View, we need a project with some models and multiple instances which will be displayed. Basically, Update view is a combination of Detail view and Create view. 

 db設置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoblog',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'host',
        'PORT': 3306,
    }
}

 

Django Update View – Function Based Views

Illustration of How to create and use Update view using an Example. Consider a project named geeksforgeeks having an app named geeks.  

Refer to the following articles to check how to create a project and an app in Django. 
 

 
 

After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,  

Python3

 
# import the standard Django Model
# from built-in library
from django.db import models
  
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
 
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title

After creating this model, we need to run two commands in order to create Database for the same. 

 
Python manage.py makemigrations
Python manage.py migrate

Now let’s create some instances of this model using shell, run form bash, 

Python manage.py shell

Enter following commands 

>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()

Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ 

 

Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder, 

Python3

 
from django import forms
from .models import GeeksModel
 
 
# creating a form
class GeeksForm(forms.ModelForm):
 
    # create meta class
    class Meta:
        # specify model to be used
        model = GeeksModel
 
        # specify fields to be used
        fields = [
            "title",
            "description"]

 

 或者:

from django import forms
from .models import Weight

class WeightForm(forms.ModelForm):
    class Meta:
        model = Weight
        fields = ['weight', 'date']

 

For Update_view one would need some identification to get a particular instance of the model. Usually it is unique primary key such as id. To specify this identification we need to define it in urls.py. Go to geeks/urls.py, 

Python3

 
from django.urls import path
 
# importing views from views..py
from .views import update_view, detail_view
 
urlpatterns = [
    path('<id>/', detail_view ),
    path('<id>/update', update_view ),
]

或者:

from django.urls import path
from . import views

urlpatterns = [
   path('', views.index, name='index'),
   path('create', views.create, name='create'),
   path('edit/<int:num>', views.edit, name='edit'),
   path('delete/<int:num>', views.delete, name='delete'),
]

 

 

Python3

 或者view:
from django.shortcuts import render, redirect
from .models import Weight
from .forms import WeightForm

# Create your views here.
def index(request):
    data = Weight.objects.all()
    params = {
    'title' : 'my weight memory',
    'data' : data
    }
    return render(request, 'weight/index.html', params)

def create(request):
    params = {
    'title': 'score',
    'form': WeightForm()
    }

    if (request.method=='POST'):
        obj = Weight()
        weight = WeightForm(request.POST, instance=obj)
        weight.save()
        return redirect(to='/weight')
    return render(request, 'weight/create.html', params)

def edit(request, num):
    obj = Weight.objects.get(id=num)
    if (request.method=='POST'):
        weight = WeightForm(request.POST, instance=obj)
        weight.save()
        return redirect(to='/weight')
    params = {
    'title' : 'edit',
    'id':num,
    'msg': '修改',
    'form': WeightForm(instance=obj)
    }
    return render(request, 'weight/edit.html', params)

def delete(request, num):
    weight = Weight.objects.get(id=num)
    if (request.method=='POST'):
        weight.delete()
        return redirect(to='/weight')
    params = {
    'title': 'delete',
    'msg': '刪除嗎?',
    'id':num,
    'obj':weight
    }
    return render(request, 'weight/delete.html', params)

 

from django.shortcuts import (get_object_or_404,
                              render,
                              HttpResponseRedirect)
 
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
 
# after updating it will redirect to detail_View
def detail_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
  
    # add the dictionary during initialization
    context["data"] = GeeksModel.objects.get(id = id)
          
    return render(request, "detail_view.html", context)
 
# update view for details
def update_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # fetch the object related to passed id
    obj = get_object_or_404(GeeksModel, id = id)
 
    # pass the object as instance in form
    form = GeeksForm(request.POST or None, instance = obj)
 
    # save the data from the form and
    # redirect to detail_view
    if form.is_valid():
        form.save()
        return HttpResponseRedirect("/"+id)
 
    # add form dictionary to context
    context["form"] = form
 
    return render(request, "update_view.html", context)

Now create following templates in templates folder, 
In geeks/templates/update_view.html,

HTML

index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css"
     href="{% static 'weight/css/style.css'%}">
    <title>{{title}}</title>
  </head>
  <body>
    <table>
      <tr>
        <th>ID</th>
        <th>Weight</th>
        <th>date</th>
        <th>修改</th>
        <th>刪除</th>
      </tr>
      {% for item in data %}
      <tr>
        <td>{{item.id}}</td>
        <td>{{item.weight}}</td>
        <td>{{item.date}}</td>
        <td><a href="{% url 'edit' item.id %}">edit</a></td>
        <td><a href="{% url 'delete' item.id %}">delete</a></td>
      </tr>
      {% endfor %}
    </table>
    <a href="{% url 'create'%}">創建</a>
  </body>
</html>

 

create.html

{% load static %}
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css"
     href="{% static 'weigth/css/style.css'%}">
    <title>{{title}}</title>
  </head>
  <body>
    <h1>{{title}}</h1>
    <form action="{% url 'create' %}" method="post">
      {% csrf_token%}
      {{ form.as_table}}
      <tr>
        <td></td><td><input type="submit" name="" value="send"></td>
      </tr>
    </form>
    <a href="{% url 'index'%}">返回</a>
  </body>
</html>

 

 delete.html
{% load static%}
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css"
     href="{% static 'weight/css/style.css'%}">
    <title>{{title}}</title>
  </head>
  <body>
    <h1>{{title}}</h1>
    <h2>{{msg}}</h2>
    <table>
      <tr>
        <th>ID</th><td>{{obj.id}}</td>
      </tr>
      <tr>
        <th>Weight</th><td>{{obj.weight}}</td>
      </tr>
      <tr>
        <th>Date</th><td>{{obj.date}}</td>
      </tr>
      <form action="{% url 'delete' id%}" method="post">
        {% csrf_token %}
        <tr>
          <td><input type="submit" name="" value="削除"></td>
        </tr>
      </form>
    </table>
  </body>
</html>

 edit.html

edit.html
{% load static%}
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css"
     href="{% static 'weight/css/style.css'%}">
    <title>{{title}}</title>
  </head>
  <body>
    <h1>{{title}}</h1>
    <h2>{{msg}}</h2>
    <table>
      <form action="{% url 'edit' id %}" method="post">
        {% csrf_token%}
        {{ form.as_table}}
        <tr>
          <td></td><td><input type="submit" name="" value="send"></td>
        </tr>
      </form>
    </table>
  </body>
</html>

 

style.css

style.css
table {
  margin: 10px;
  font-size: 14px;
  text-align: center;
}

table tr th {
  background-color: #009;
  color: white;
  padding: 2px 10px;
  border-width: 2px;
  text-align: center;
}

table tr rd {
  background-color: #eee;
  color: #666;
  padding: 2px 10px;
  border-width: 2px;
  text-align: center;
}

 

 

<div class="main">
    <!-- Create a Form -->
    <form method="POST">
        <!-- Security token by Django -->
        {% csrf_token %}
 
        <!-- form as paragraph -->
        {{ form.as_p }}
 
        <input type="submit" value="Update">
    </form>
 
</div>

In geeks/templates/detail_view.html, 

HTML

 
<div class="main">
    <!-- Display attributes of instance -->
    {{ data.title }} <br/>
    {{ data.description }}
</div>

Let’s check if everything is working, visithttp://localhost:8000/1/update

django-update-view-

Here you can see the form with data already filled from the instance, Now one can edit this data and update it easily, let’s check it out 
 

django-update-view-edit-data

Hit update and done. 
 

django-update-view-result

 


 
Last Updated : 17 May, 2021
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章