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
run terminal
> python manage.py makemigrations
> python manage.py migrate
forms.py
class postForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'body', ]
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})
post.html
{% load crispy_forms_tags %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form|crispy }}<br>
<button type="submit">Post</button>
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('post/',views.postPage,name='post'),
]
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})
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 %}
Top comments (0)