0
0
Djangoframework~5 mins

UpdateView for editing in Django

Choose your learning style9 modes available
Introduction

UpdateView helps you easily create a page to edit existing data in your database without writing much code.

You want users to change details of an existing item, like editing a blog post.
You need a simple form page to update user profile information.
You want to reuse Django's built-in features for editing data safely and quickly.
Syntax
Django
from django.views.generic.edit import UpdateView
from .models import YourModel

class YourModelUpdateView(UpdateView):
    model = YourModel
    fields = ['field1', 'field2']
    template_name = 'yourmodel_form.html'
    success_url = '/success/'

model tells Django which data to edit.

fields lists the fields users can change.

Examples
This example lets users edit the title and author of a book.
Django
class BookUpdateView(UpdateView):
    model = Book
    fields = ['title', 'author']
    template_name = 'book_edit.html'
    success_url = '/books/'
Here, users can update their bio and avatar picture.
Django
class ProfileUpdateView(UpdateView):
    model = Profile
    fields = ['bio', 'avatar']
    success_url = '/profile/'
Sample Program

This code creates a page to edit an Article's title and content. When saved, it redirects to /articles/.

Django
from django.urls import path
from django.views.generic.edit import UpdateView
from django.db import models

# Simple model
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

# UpdateView for editing Article
class ArticleUpdateView(UpdateView):
    model = Article
    fields = ['title', 'content']
    template_name = 'article_form.html'
    success_url = '/articles/'

# URL pattern
urlpatterns = [
    path('article/<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_edit'),
]

# Template (article_form.html) example:
# <form method="post">
#   {% csrf_token %}
#   {{ form.as_p }}
#   <button type="submit">Save</button>
# </form>
OutputSuccess
Important Notes

Make sure your template includes the CSRF token for security.

The URL must include the primary key (pk) to tell Django which item to edit.

You can customize the success_url to control where users go after saving.

Summary

UpdateView makes editing existing data easy with little code.

Set model, fields, template_name, and success_url to configure it.

Use URL patterns with pk to link to the right item for editing.