My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled

My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled. I have searched similar problems but the context was just a little different and the fixes couldn't work on my project.

My models

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    pass

class Post(models.Model):
    body = models.TextField()
    date = models.DateTimeField(auto_now_add = True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=None)

    def __str__(self):
        return f"{self.body} by {self.author} at {self.date}"

Forms.py

from django import forms
from django.forms import ModelForm

from .models import Post

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ['body']

        widgets = {
            "body": forms.Textarea(attrs={'class': 'form-control col-md-5 col-lg-6'}),
        }

Views.py

def create_post(request):
    posted = False
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return HttpResponseRedirect("/create_post?posted=True")
    else:
        form = PostForm()
        if "posted" in request.GET:
            posted = True
    return render(request, "network/create_post.html", {
        "form": form,
        "posted": posted
    })        

Urls

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("create_post", views.create_post, name="create_post"),
    path("create_post_page", views.create_post_page, name="create_post_page")
    ]

The template

{% extends "network/layout.html" %}

{% block body %}

{% if posted %}
 Succseful
{% else %}
<h2>Create a new post</h2>
<form action="{% url 'create_post' %}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input class="btn btn-secondary" type="submit" value="Post">
</form>
{% endif %}
{% endblock %}

It just won't show on the page except as a warning after clicking Post(Submit). Thank you in advance.

Back to Top