DEV Community

Phansivang
Phansivang

Posted on

Django Post Page and Post edit

modesl.py

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

class Post(models.Model):
    title = models.CharField(max_length=30)
    body = models.TextField(max_length=500)
    date_posted = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

run terminal

> python manage.py makemigrations
> python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

forms.py

class postForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body', ]
Enter fullscreen mode Exit fullscreen mode

vies.py

from .forms import  postForm,
from django.contrib.auth.forms import User

def postPage(request):
    if request.method == 'POST':
        form = postForm(request.POST)
        if form.is_valid():
            title = request.POST.get('title')
            body = request.POST.get('body')
            user = User.objects.filter(username=request.user.username).first()
            post = Post.objects.create(title=title, body=body, author=user)
            post.save()
            return redirect('home')
    else:
        form = postForm()

    return render(request, 'app/post.html', {'form': form})
Enter fullscreen mode Exit fullscreen mode

post.html

{% load crispy_forms_tags %}
{% block content %}
    <form method="POST">
    {% csrf_token %}
    {{ form|crispy }}<br>
    <button type="submit">Post</button>
    </form>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('post/',views.postPage,name='post'),

]
Enter fullscreen mode Exit fullscreen mode

FOR VIEW THE POST

views.py

from .models import Post

def homePage(request):
    posts = Post.objects.all()
    return render(request, 'app/home.html', {'posts': posts})
Enter fullscreen mode Exit fullscreen mode

home.html

{% block content %}
    {% for post in posts %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="#">{{ post.author }}</a>
              <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'Postview' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.body }}</p>
          </div>
        </article>
    {% endfor %}
{% endblock content %}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)