Menu

Django: Write Create and Edit Views Twice as Fast with CreateView and UpdateView in 5 Minutes
πŸ“°

Django: Write Create and Edit Views Twice as Fast with CreateView and UpdateView in 5 Minutes

DEV Community: djangoΒ·Linh Fish DevΒ·3 days ago
#1MfiWcNe
#devtodjango#devto#dev#form#views
Reading 0:00
15s threshold

When you need a form to create and edit a record, you don’t have to rewrite the familiar GET/POST view pair. Django already ships two class-based views built for exactly this job β€” CreateView and UpdateView : just declare the model, the list of fields and the template, and Django handles the rest β€” rendering the form, validating it, saving and redirecting. These two views fit best when your form maps directly onto a model through a ModelForm .

The Problem

In a blog app, a function-based view for creating a post is usually about 25 lines long: check request.method , build the form from request.POST or an empty form, call is_valid() , save and redirect. The view for editing a post is nearly identical, differing only in the line that fetches the object with get_object_or_404 and passes instance=post .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.