The Course App

Creating a view that uses a form

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

New files

templates/app/article_create.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Create article</title>
</head>
<body>
  <h1>Create Article</h1>
  <form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>
  </form>
</body>
</html>

Modified files

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

 urlpatterns = [
-    path("", home),
+    path("", home, name="home"),
+    path("articles/create/", create_article, name="create_article")
 ]
app/views.py
--- 
+++ 
@@ -1,7 +1,28 @@
-from django.shortcuts import render
+from django.shortcuts import render, redirect
 from app.models import Article
+from app.forms import CreateArticleForm


 def home(request):
     articles = Article.objects.all()
-    return render(request, "app/home.html", {"articles": articles})+    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})