In this example, we'll learn how to update form using UpdateView

first, we need to write a listview for our post model

ListView example

models.py

1
2
3
4
5
class posts(models.Model):
    title = models.CharField(max_length=300, unique=True)
    time = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.title        

views.py

1
2
3
4
5
6
7
#dajngo listView
from django.views.generic.list import ListView

class posts_list(ListView):
    model = posts #model
    fields = '__all__' # fields 
    template_name = 'posts-list.html' # templete for list

urls.py

1
2
    #posts-list
    path('posts-list', posts_list.as_view(), name="posts-list"),

posts-list.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html>
    <head>
        <title>ListView</title>
        
    </head>

    <body>


<h1 style="padding-bottom: 30px">list of posts</h1>

{% for i in object_list %}
<div style="margin-bottom: 40px">

<h4>{{i.title}}</h4>
<a href="{% url 'Post_update' i.id %}">update</a>

</div>

{% endfor %}

<h3><a href="{% url 'create_article' %}">add</a></h3>

    </body>

</html>

updateview example

views.py

1
2
3
4
5
6
7
8
#UpdateView
from django.views.generic.edit import UpdateView

class update(UpdateView):
    model = posts #model
    fields = ['title'] # fields / if you want to select all fields use "__all__"
    template_name = 'update_form.html' # templete for updating
    success_url="/posts-list" # posts list url

urls.py

1
2
 #UpdateView
    path('post/<slug:pk>/', update.as_view(), name='Post_update'),

update_form.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<html>
    <head>
        <title>UpdateView</title>
        
    </head>

    <body>
<form method="POST">{% csrf_token %}
    
<!-- form variable -->    
 {{ form.as_p }} 

  <input type="submit" name="sumbit">
</form>
    </body>

</html>

result


django updateview simple example

English today is not an art to be mastered it's just a tool to use to get a result