Categories
Class Based Views

CBV – UpdateView

From Classy Class Based Views UpdateView

View for updating an object, with a response rendered by a template.

Attributes

Two attributes are required to get the template to render. We’ve seen queryset before and in CreateView we saw fields. As a brief refresher

  • fields: specifies what fields from the model or queryset will be displayed on the rendered template. You can you set fields to __all__ if you want to return all of the fields
  • success_url: you’ll want to specify this after the record has been updated so that you know the update was made.

Example

views.py

class myUpdateView(UpdateView):
    queryset = Person.objects.all()
    fields = '__all__'
    extra_context = {
        'type': 'Update'
    }
    success_url = reverse_lazy('rango:list_view')

urls.py

path('update_view/<int:pk>', views.myUpdateView.as_view(), name='update_view'),

<template>.html

{% block content %}
    <h3>{{ type }} View</h3>
    {% if type == 'Create' %}
        <form action="." method="post">
    {% else %}
        <form action="{% url 'rango:update_view' object.id %}" method="post">
    {% endif %}
    {% csrf_token %}
    <table>
    {{ form.as_p }}
    </table>
    <button type="submit">SUBMIT</button>
    </form>
{% endblock %}

Diagram

A visual representation of how UpdateView is derived can be seen here:

Conclusion

A simple way to implement a form to update data in a model. Step 3 for a CRUD app is now complete!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.