Skip to content

Commit

Permalink
Merge pull request #9 from zablon-oigo/create-post
Browse files Browse the repository at this point in the history
Create post
  • Loading branch information
Akash1362000 authored Feb 25, 2024
2 parents 351cccd + 404300b commit 5fd1cef
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 1 deletion.
9 changes: 9 additions & 0 deletions blog/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django import forms

from .models import Post


class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content"]
3 changes: 3 additions & 0 deletions blog/templates/blog/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
<li class="nav-item">
<a class="nav-link" href="{% url 'profile' %}">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'create_post' %}">Create Post</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Logout</a>
</li>
Expand Down
10 changes: 10 additions & 0 deletions blog/templates/blog/create_post.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "blog/base.html" %}

{% block content %}
<h1>Create Post</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock content %}
1 change: 1 addition & 0 deletions blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
urlpatterns = [
path("", views.home, name="blog-home"),
path("about/", views.about, name="blog-about"),
path("create-post/", views.create_post, name="create_post"),
]
22 changes: 21 additions & 1 deletion blog/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from .forms import PostForm
from .models import Post


Expand All @@ -10,3 +13,20 @@ def home(request):

def about(request):
return render(request, "blog/about.html", {"title": "About"})


@login_required
def create_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.author = request.user
user.save()
messages.success(request, "The post has been created successfully.")
return redirect("blog-home")
else:
messages.error(request, "Please correct the following errors:")
else:
form = PostForm()
return render(request, "blog/create_post.html", {"form": form})

0 comments on commit 5fd1cef

Please sign in to comment.