📝 Django

Django CreateView

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
80
🌿
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

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 134
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 85
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 74

Did you like the article?

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