In Django, how can I delete object inside template by clicking link? - python

I made a notification system. When "B" user comments at "A" user's post, notification sends to A.
This is my part of my code.
models.py
from django.db import models
from freeboard.models import FreeBoardComment
from users.models import CustomUser
class Notification(models.Model):
TYPE_CHOCIES = (
("FreeBoardComment", "FreeBoardComment"),
)
creator = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name="creator")
to = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name="to")
notification_type = models.CharField(max_length=50, choices=TYPE_CHOCIES)
comment = models.CharField(max_length=1000, blank=True, null=True)
post_id = models.IntegerField(null=True)
class Meta:
ordering = ["-pk"]
def __str__(self):
return "From: {} - To: {}".format(self.creator, self.to)
notification/views.py
from django.views.generic import ListView
from .models import Notification
def create_notification(creator, to, notification_type, comment, post_id):
if creator.email != to.email:
notification = Notification.objects.create(
creator=creator,
to=to,
notification_type=notification_type,
comment=comment,
post_id=post_id,
)
notification.save()
class NotificationView(ListView):
model = Notification
template_name = "notification/notification.html"
freeboard/views.py
...
#login_required
def comment_write(request, pk):
post = get_object_or_404(FreeBoardPost, pk=pk)
if request.method == 'POST':
form = CreateFreeBoardComment(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.comment_writer = request.user
comment.post = post
comment.save()
# 포인트
award_points(request.user, 1)
### NOTIFICATION PART!!!! ###
create_notification(request.user, post.author, "FreeBoardComment", comment.comment_text, post.pk)
### NOTIFICATION PART !!! ###
return redirect("freeboard_detail", pk=post.id)
else:
form = CreateFreeBoardComment()
return render(request, "bbs/freeboard/free_board_comment.html", {"form": form})
notification.html
{% extends "base.html" %}
{% block css_file %}
<link href="/static/css/notification/notification.css" rel="stylesheet">
{% endblock %}
{% block content %}
<ul class="list-group">
{% for notification in notification_list %}
<li class="list-group-item dropdown">
<a href="{% if notification.notification_type == "FreeBoardComment" %}/free/{{ notification.post_id }}{% endif %}"
class="dropdown-toggle" style="color: #555; text-decoration: none;">
<div class="media">
<img src="{{ notification.creator.image.url }}" width="50" height="50"
class="pull-left img-rounded" style="margin: 2px"/>
<div class="media-body">
<h4 class="media-heading"><span
class="genre">[#{{ notification.to.nickname }}]</span> {{ notification.comment }}
</h4>
<span style="font-size: 0.9rem;"><i
class="fa fa-user"></i> {{ notification.creator.nickname }}</span>
</div>
</div>
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
And what I'm trying to add is notification delete feature WITHOUT TEMPLATE(deleteview).
When user clicked the notification and redirected to url, I want to delete that notification.
Is there way I can do this?

you code is a little bit confusing but i here is the thing, i think it would be better to use DRF and remove the notification without the redirection like #Edgardo_Obregón mentioned. or if you don't wanna use DRF, then it would be a good idea if you simply use a small view:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt # if you wanna bypass csrf, otherwise you can use csrf with ajax docs
def delete_notification(request,pk):
if request.METHOD == "DELETE": # optional
notification = Notification.objects.get(pk=pk)
if notification is not None:
notification.delete()
csrf with ajax docs

Related

Getting NoReverseMatch while click the comment button

I was getting that same error while click the like button, But the error was solved..
again after creating comment view and its other staff I'm getting that error again...When I click the comment button then the error appears..I'm very new to Django,,, help me please..
My project models.py, template page, urls.py, views.py are attached herewith
**models.py**
from email.policy import default
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Blog(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200, verbose_name="Put a Title")
blog_content = models.TextField(verbose_name="What is on your mind")
blog_image = models.ImageField(upload_to="blog_images", default = "/default.png")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Comment(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_comment" )
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_comment")
comment = models.TextField()
comment_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.comment
class Like(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_liked")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_liked")
class Unlike(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_unliked")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_unliked")
**blog_page.html**
{% extends "main.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div style="text-align:center;">
<h2>{{blog.title}}</h2>
<img src="{{blog.blog_image.url}}" alt="" width="630px" height="300px">
</div>
<div style="text-align:center;">
{{blog.blog_content|linebreaks}}
</div>
{% if not liked and not unliked %}
<h4> Like </h4>
<h4>Unlike</h4>
{% elif unliked %}
<h4> Like </h4>
{% elif liked %}
<h4>Unlike</h4>
{% endif %}
<div>
<h4>
Comments:
</h4>
{% for comment in comments %}
<div>
{{ user }} <br>
<h5>{{ comment }}</h5>
</div>
{% endfor %}
<!-- <h6>Add your comment:</h6> -->
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}} <br>
<a class="btn btn-sm btn-info" href="{% url 'comment' %}">Comment</a>
</form>
</div>
{% endblock content %}
**urls.py**
from django.urls import path
from blog_app import views
urlpatterns = [
path("", views.home, name='home'),
path("blog_page/<str:pk>/", views.blog_view, name='blog_page'),
path("like/<str:pk>/", views.like, name="like"),
path("unlike/<str:pk>/", views.unlike, name="unlike"),
path("comment/", views.comment, name="comment"),
]
**views.py**
from django.shortcuts import render
from . models import Blog, Comment, Like, Unlike
from . forms import CommentForm
# Create your views here.
def home(request):
blogs = Blog.objects.all()
context = {'blogs': blogs}
return render(request, 'blog_app/home.html', context)
def blog_view(request, pk):
blog = Blog.objects.get(id=pk)
form = CommentForm()
comments = Comment.objects.filter(blog=blog)
context = {"blog": blog, "comments": comments, "form":form}
return render(request, 'blog_app/blog_page.html', context)
def like(request, pk):
blog = Blog.objects.get(id=pk)
user = request.user
liked, like = Like.objects.get_or_create(blog=blog, user=user)
context = {"liked" : liked, "blog": blog }
return render(request, "blog_app/blog_page.html", context)
def unlike(request, pk):
blog = Blog.objects.get(id=pk)
user = request.user
unliked, unlike = Unlike.objects.get_or_create(blog=blog, user=user)
context = {"unliked" : unliked, 'blog': blog}
return render(request, "blog_app/blog_page.html", context)
def comment(request):
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
form.save()
context = {}
return render(request, "blog_app/blog_page.html", context)
Your comment button is just a link, is it normal ? I think, you want to submit your form when you click on?
<div>
<h4>
Comments:
</h4>
{% for comment in comments %}
<div>
{{ user }} <br>
<h5>{{ comment }}</h5>
</div>
{% endfor %}
<!-- <h6>Add your comment:</h6> -->
<form action="{% url 'comment' %}" method="POST">
{% csrf_token %}
{{form|crispy}} <br>
<button type="submit" class="btn btn-sm btn-info">Comment</button>
</form>
</div>
And i think, your problem occured because you dispolay this template from comment view without set blog in context data.
def blog_view(request, pk):
blog = Blog.objects.get(id=pk)
form = CommentForm()
comments = Comment.objects.filter(blog=blog)
context = {"blog": blog, "comments": comments, "form":form}
return render(request, 'blog_app/blog_page.html', context)
def comment(request):
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
form.save()
return redirect("blog_page", pk=form.instance.blog.pk)
return HttpResponse(status_code=400) # error case
else:
return HttpResponse(status_code=501) # try to GET page
Better solution is to pass blog pk in the url for being able to render page with error:
path("blog/<int:pk>/comment/", views.comment, name="comment")
<form action="{% url 'comment' blog.pk %}" method="POST">
{% csrf_token %}
{{form|crispy}} <br>
<button type="submit" class="btn btn-sm btn-info">Comment</button>
</form>
def comment(request, pk):
blog = get_object_or_404(Blog, pk=pk)
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
form.save()
return redirect("blog_page", pk=blog.pk)
return render(request, "...", {"blog": blog, "form": form})

Field 'id' expected a number but got 'xyz'

In Models.py
class Post(models.Model):
user = models.CharField(max_length=100)
likes = models.IntegerField(default=0)
content = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Profile(models.Model):
following = models.ForeignKey('User',on_delete=models.CASCADE,related_name='following')
user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user')
def __str__(self):
return self.user
In views.py
def viewProfile(request,username):
posts = Post.objects.filter(user=username).order_by('id').reverse()
profile = Profile.objects.filter(user=username)
no_of_followers = profile.following.count()
return render(request, "network/profile.html",{
"posts":posts,
"username":username,
"no_of_followers":no_of_followers
})
In profile.html
{% extends "network/layout.html" %}
{% block body %}
<h2 style="margin-left: 20px;">Posts of {{username}}</h2>
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h5 class="card-title">Profile Details</h5>
<p class="card-text">Followers:{{no_of_followers}}</p>
<p class="card-text">Followings:0</p>
Go somewhere
</div>
</div>
</div>
{% for post in posts %}
<div class="card" style="width:70%;margin-left: 10%;margin-right: 20%;">
<div class="card-body">
<h5 class="card-title">{{post.user}}</h5>
<div class="form-group">
<p>{{post.date}}<br>{{post.content}}</p>
</div>
<p>{{post.likes}}</p>
</div>
</div>
{% endfor %}
{% endblock %}
Facing an error of Field 'id' expected a number but got 'xyz'. xyz is the username
If I replace profile = Profile.objects.filter(user=username)with profile = Profile.objects.filter(user__user=username) then I am getting the error django.core.exceptions.FieldError: Related Field got invalid lookup: user
The lookup should be:
profile = Profile.objects.get(user__username=username)
since you want to retrieve a Profile for which the user has a username that has the given username.
You probably should use .get(…) [Django-doc] here to retrieve a Profile object, not a QuerySet of Profiles.
You might want to use the get_object_or_404(…) function [Django-doc] instead, such that it returns a 404 in case no such profile exists:
from django.shortcuts import get_object_or_404
def viewProfile(request,username):
posts = Post.objects.filter(user__username=username).order_by('-id')
profile = get_object_or_404(Profile, user__username=username)
no_of_followers = profile.following.count()
return render(request, 'network/profile.html',{
'posts':posts,
'username':username,
'no_of_followers":no_of_followers
})

Django add comment section on posts feed

I want to share a project that currently can create user and each user can create N posts
The source is available on github
and I has two models users and post
and the template layers
Currently the feed for each post has a button that send an commenting the post I want to change that to put the comments of the post and not send and email each user should be able to comment a post and the comment should remain
{% block container %}
<body id="bg" img style="zoom: 85%; background-position: center center; background-attachment: fixed;background-repeat:no-repeat;padding:5px; background-image: url('{% static "/back.png"%}') ";>
<div style="background-image: url({% static 'static/img/back.png' %});">
<div class="row" style="align:center">
{% for post in posts %}
<div class="col-sm-12 col-md-8 offset-md-4 mt-5 p-0 post-container,width:50%;">
<div class="card" style="width: 32rem;width:50%;">
<div class="card-body">
<div class="media pt-3 pl-3 pb-1">
<a href="{% url " users:detail" post.user.username%}">
<img alt="{{ post.user.username }}" class="mr-3 rounded-circle" height="35"
src="{{ post.profile.picture.url }}">
</a>
<h3 class="card-title">{{ post.title }}</h3>
</div>
<p class="card-text">{{ post.desc }}</p>
</div>
</div>
<img alt="{{ post.title }}" src="{{ post.photo.url }}" style="width: 50%; heigth:60%">
<div class="media-body">
<b><p style="margin-top: 5px;">#{{ post.user.username }} - <small>{{ post.created }}</small>
<a href="" style="color: #000; font-size: 20px;">
<i class="far fa-heart"></i>
</a>
<br>
</p></b>
</div>
<!-- COMENT SECTION THAT I WANT TO IMPLEMENT MY FEATURE-->
<form action="{% url 'posts:comment_new' %}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="title"
size="16"
type="hidden"
value="{{post.title}}"
>
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="first_name "
size="16"
type="hidden"
value="{{user.first_name}}"
>
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="last_name "
size="16"
type="hidden"
value="{{user.last_name}}"
>
<textarea class="form-control" cols="50" name="comment" rows="5"
style="width:50%;" value="{{ comments.comment }}"></textarea>
<button class="btn btn-outline-info btn-lg" style="width:35%; display:block;margin:auto;" type="submit">
Publish
</button>
</form>
</div>
<br>
{% endfor %}
</div>
</div>
{% endblock %}
As I said I want to replace this form function call to create a comment section instead sending a email with the comment
< form action = "{% url 'posts:comment_new' %}">
def comment_new(request):
if request.method == 'POST':
message = request.POST['comment']
subject = request.POST['title']
user = request.POST['first_name']
last_name = request.POST['last_name']
# lastname = request.POST['lastname']
send_mail("[MAIL] " + subject, user + " " + last_name + " said " + message + " on http://url.com:8000",
'guillermo.varelli#gmail.com',
['guillermo.varelli#gmail.com'], fail_silently=False)
posts = Post.objects.all().order_by('-created')
return render(request, os.path.join(BASE_DIR, 'templates', 'posts', 'feed.html'), {'posts': posts})
I think this maybe create a comment with user and post id with the comment detail
def comment_new(request):
if request.method == 'POST':
message = request.POST['comment']
subject = request.POST['title']
user = request.POST['first_name']
last_name = request.POST['last_name']
#lastname = request.POST['lastname']
form = PostForm(request.POST, request.FILES)
form.save()
One options its create a comment
class Comment(models.Model):
"""
#id= models.AutoField(max_length=1000, blank=True)
# post = models.ForeignKey(Post, related_name='',on_delete=models.CASCADE,default=0)
"""
#comment = models.ForeignKey('posts.Post', related_name='posts_rel', to_field="comments", db_column="comments",
# on_delete=models.CASCADE, null=True, default=1, blank=True)
post = models.IntegerField(blank=True,null=True,unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)
username = models.CharField(blank=True, null=True, unique=True ,max_length=200)
comment = models.CharField(max_length=254, blank=True, null=True)
and then the form
class CommentForm(forms.ModelForm):
class Meta:
"""form settings"""
model = Comment
fields = ('user','username','post','comment',)
finally with the function I'm able to persist but not able to render
form = CommentForm(request.POST, request.FILES)
# print formset.errors
if form.is_valid():
form.save()
but I can't find the way to render the object on the html file
please feel free to suggest any solution or better create a pull request on the public git hub repo
In the book Django 2 by Example we can find a step by step guide to create a comment system, wherein the users will be able to comment on posts.
In order to do it, is as simple as the following four steps
Create a model to save the comments
Create a form to submit comments and validate the input data
Add a view that processes the form and saves the new comment to the database
Edit the post detail template to display the list of comments and the form to add a new comment
Create a model to save the comments
In your models.py file for the application, add the following code
class Comment(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
The new Comment model you just created is not yet synchronized into the database. Run the following command to generate a new migration that reflects the creation of the new model:
python manage.py makemigrations APPNAME
and
python manage.py migrate
After this, the new table exists in the database. Now, open the admin.py file of the blog application, import the Comment model, and add the following ModelAdmin class:
from .models import Post, Comment
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'post', 'created', 'active')
list_filter = ('active', 'created', 'updated')
search_fields = ('name', 'email', 'body')
Create a form to submit comments and validate the input data
Edit the forms.py file of your blog application and add the following lines:
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
Add a view that processes the form and saves the new comment to the database
Edit the views.py file, add imports for the Comment model and the CommentForm form, and modify the post detail view to make it look like the following:
from .models import Post, Comment
from .forms import EmailPostForm, CommentForm
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
Edit the post detail template to display the list of comments and the form to add a new comment
At this point we have created the functionality to manage comments for a post. Now, we will need to adapt our post/detail.html template to do the following things:
- Display the list of comments
- Display a form for users to add a new comment
Append the following lines to the post/detail.html template for the list of comments:
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{ forloop.counter }} by {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
Then, for the other point, add the following lines:
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}

Django comments not showing in template

I have a system setup to show comments on a post detail page, however the comments are not showing. I have been focusing on the template tags, because I have used this view code elsewhere and it has worked, however I may be wrong. No errors returning, just not showing the comment in the detail view.
userpost_detail.html:
{% extends 'base.html' %}
{% block content %}
<div class="main">
<h1 class="posttitle">{{ userpost.title }}</h1>
<p class="postcontent">{{ userpost.post_body }}</p>
{% if request.user.is_authenticated and request.user == post.author %}
<a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a>
{% endif %}
Add Comment
{% for comment in userpost.usercomment.all %}
{% if user.is_authenticated %}
{{ comment.create_date }}
<!--
<a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}">
<span class="glyphicon glyphicon-remove"></span>
</a>
-->
<p>{{ comment.comment_body }}</p>
<p>Posted By: {{ comment.author }}</p>
{% endif %}
{% empty %}
<p>No Comments</p>
{% endfor %}
</div>
{% include 'feed/sidebar.html' %}
{% endblock %}
app PostDetailView:
class PostDetailView(DetailView):
model = UserPost
app add_comment_to_post view:
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(UserPost,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('feed:post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request,'feed/comment_form.html',{'form':form})
app urls:
from django.conf.urls import url
from feed import views
app_name = 'feed'
urlpatterns = [
url(r'^new/$',views.CreatePostView.as_view(),name='new_post'),
url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/(?P<pk>\d+)/edit/$',views.UpdatePostView.as_view(),name='edit_post'),
url(r'^post/(?P<pk>\d+)/delete/$',views.DeletePostView.as_view(),name='delete_post'),
url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment'),
]
Models.py:
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class UserPost(models.Model):
author = models.ForeignKey(User,related_name='userpost',null=True)
post_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=150,blank=False)
post_body = models.TextField(max_length=1000,blank=False)
def publish(self):
self.save()
def get_absolute_url(self):
return reverse('index')
def __str__(self):
return self.title
class UserComment(models.Model):
post = models.ForeignKey('feed.UserPost',related_name='comments')
author = models.ForeignKey(User,related_name='usercomment')
comment_date = models.DateTimeField(auto_now_add=True)
comment_body = models.TextField(max_length=500)
def publish(self):
self.save()
def get_absolute_url(self):
return reverse("userpost_list")
def __str__(self):
return self.comment_body
As #user6731765 mentioned you need comments coz of related_name
{% for comment in userpost.comments.all %}
When you get comment_remove error
You need to define a url for comment_remove and define a view for that.
urlpatterns = [
. . . . . .
url(r'^comment/remove/(?P<pk>\d+)/$',views.DeleteCommentView.as_view(),name='comment_remove'),
]
Then in views.py
class DeleteCommentView(DeleteView):
model=UserComment
Due to the related_name you are using for posts in UserComment, try using
{% for comment in userpost.comments.all %}
in your template instead.

Django won't display textfield from model

I have a login system where you need to be logged in to submit a new post. My "New Post" page/form work fine and the content the user submits is properly posted in the database, how when it comes to displaying that content on the home page only the title and subtitle are shown (which are Charfields) and no the body text of the post (which is a text field).
inde.html
{% extends "blog/base.html" %}
{% block body_block %}
<div class="left">
{% if userposts %}
{% for posts in userposts %}
<div class="front-post">
<h2 class="post-title">{{ posts.post_title }}</h2>
<h3 class="post-sub-title">{{ posts.post_sub_title }}</h3>
<p class="post-author">{{ post.post_author }}</p>
<p class="post-date">{{ post.post_date }}</p>
<p class="post-body">{{ post.post_body }}</p>
</div>
{% endfor %}
{% endif %}
</div>
<div class="right">
<p>SIDE BAR</p>
</div>
{% endblock %}
views.py
from django.shortcuts import render
from blog.forms import UserForm,UserProfileInfoForm,AddPost
from blog.models import UserPosts
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
post_list = UserPosts.objects.order_by('post_date')
post_dict = {'userposts':post_list}
return render(request, 'blog/index.html',context=post_dict)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = ''
post_date = models.DateField(auto_now=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
forms.py
from django import forms
from django.contrib.auth.models import User
from blog.models import UserProfileInfo,UserPosts
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','email','password')
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ('portfolio_site','profile_pic')
class AddPost(forms.ModelForm):
class Meta():
model = UserPosts
fields = '__all__'
Watch your naming. Your for loop variable is named posts (with an s at the end) but you're trying to display post.post_body. In some places it's working because you're using posts.post_title.
To fix this issue, rename posts to just post everywhere in your for loop.
{% for post in userposts %}
<div class="front-post">
<h2 class="post-title">{{ post.post_title }}</h2>
<h3 class="post-sub-title">{{ post.post_sub_title }}</h3>
<p class="post-author">{{ post.post_author }}</p>
<p class="post-date">{{ post.post_date }}</p>
<p class="post-body">{{ post.post_body }}</p>
</div>
{% endfor %}
Django will silently fail any expressions it can't evaluate in the templates, which is why nothing was being shown.

Categories