The Course App

Creating articles with Class-Based Views

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $15

Modified files

app/urls.py
--- 
+++ 
@@ -1,7 +1,7 @@
 from django.urls import path
-from app.views import home, create_article
+from app.views import home, ArticleCreateView

 urlpatterns = [
     path("", home, name="home"),
-    path("articles/create/", create_article, name="create_article")
+    path("articles/create/", ArticleCreateView.as_view(), name="create_article")
 ]
app/views.py
--- 
+++ 
@@ -1,6 +1,8 @@
-from django.shortcuts import render, redirect
+from django.shortcuts import render
+from django.urls import reverse_lazy
+from django.views.generic import CreateView
+
 from app.models import Article
-from app.forms import CreateArticleForm


 def home(request):
@@ -8,21 +10,8 @@
     return render(request, "app/home.html", {"articles": articles})


-def create_article(request):
-    if request.method == "POST":
-        form = CreateArticleForm(request.POST)
-        if form.is_valid():
-            form_data = form.cleaned_data
-            new_article = Article(
-                title=form_data["title"],
-                status=form_data["status"],
-                content=form_data["content"],
-                word_count=form_data["word_count"],
-                twitter_post=form_data["twitter_post"],
-            )
-            new_article.save()
-
-            return redirect("home")
-    else:
-        form = CreateArticleForm()
-    return render(request, "app/article_create.html", {"form": form})+class ArticleCreateView(CreateView):
+    template_name = "app/article_create.html"
+    model = Article
+    fields = ["title", "status", "content", "word_count", "twitter_post"]
+    success_url = reverse_lazy("home")