๐Ÿ“ Django

Django CreateView

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
283
๐ŸŒฟ
Level
Medium

CreateView is a CBV for creating an object through a form.

Basic Example

from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Task
from .forms import TaskForm

class TaskCreateView(CreateView):
    model = Task
    form_class = TaskForm
    template_name = 'tasks/task_form.html'
    success_url = reverse_lazy('task-list')

URL

path('tasks/new/', views.TaskCreateView.as_view(), name='task-create'),

Template

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Create</button>
</form>

Automatic Owner Assignment

class TaskCreateView(LoginRequiredMixin, CreateView):
    model = Task
    fields = ['title', 'description', 'priority', 'project']

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('task-detail', kwargs={'pk': self.object.pk})

fields vs form_class

# Simple option โ€” list the fields directly
fields = ['title', 'description', 'priority']

# Advanced option โ€” use a form with custom validation
form_class = TaskForm

Initial Values

def get_initial(self):
    initial = super().get_initial()
    initial['project'] = self.request.GET.get('project')
    return initial

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 280
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 565
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 316

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!