Unable to Post comments to blog post with Django - python

I am creating a blog for a project and I am having problem getting my comments to post to the back end.
My code is as follows:
models.py
from django.contrib.auth.models import User
from products.models import Category
class Post(models.Model):
"""Model to create blog posts"""
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=250)
body = models.TextField(blank=True, null=True)
image = models.ImageField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
class Comment(models.Model):
"""Model to handle user comments"""
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.body[0:50]
forms.py
from .models import Post, Comment
class PostForm(ModelForm):
"""
Form to allow site owner to create a new blog post
"""
class Meta:
model = Post
fields = ['category', 'title', 'body', 'image']
class CommentForm(ModelForm):
"""Form to handle user comments"""
class Meta:
model = Comment
fields = ('body',)
views.py
def add_comment(request):
"""Method to add comments to a blog post"""
post = get_object_or_404(Post, post_id)
comments = post.comments.all()
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
template = 'blog/post_detail.html'
context = {
'post': post,
'comments': comments,
'new-comment': new_comment,
'comment_form': comment_form,
}
return render(request, template, context)
urls.py
from . import views
urlpatterns = [
path('', views.view_blog, name="blog"),
path('<int:post_id>/', views.post_detail, name="post_detail"),
path('add_post/', views.add_post, name="add_post"),
path('edit_post/<int:post_id>/', views.edit_post, name="edit_post"),
path('delete/<int:post_id>/', views.delete_post, name="delete_post"),
path('add_comment/', views.add_comment, name="add_comment"),
path('delete/comment/<int:comment_id>/', views.delete_comment, name="delete_comment"),
]
Could anyone see where I am going wrong please? I have been playing around and getting different type of name and value error and am not getting any further forward.
Current template
<div id="comment-input">
{% if request.user.is_authenticated %}
<form action="{% url 'add_comment' %}" method="POST">
{% csrf_token %}
<div class="w-100 mb-2">
{{ comment_form | crispy }}
<button class="form-control btn btn-black border border-black rounded-0" type="submit">Submit
</button>
</div>
{% endif %}
</div>
<div class="comment-wrapper">
{% for comment in post.comments.all %}
<div id="comment-details">
<div id="comment-author">
{{comment.author}} - {{comment.created|timesince}} ago
</div>
<div id="comment-body">
{{comment.body}}
</div>
</div>
<div id="delete-comment">
{% if request.user == comment.author %}
Delete Comment
{% endif %}
</div>
<hr>
{% endfor %}
</div>

Related

Django 5 star rating system is not saving reviews and rating

I build a model for user reviews and rating. And made the form for my model , then I call the form in my views . When i click on button from detail page to get the "rate.html" it get me there but did not save the data from there and give me this error .
IntegrityError at /product/new-shoes/rate/
NOT NULL constraint failed: products_review.user_id
my models.py is:
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product , on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
text = models.TextField(max_length=3000 , blank=True)
rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES)
likes= models.PositiveIntegerField(default=0)
dislikes = models.PositiveIntegerField(default=0)
def __str__(self):
return self.user.full_name
my forms.py is:
class RateForm(forms.ModelForm):
text = forms.CharField(widget=forms.Textarea(attrs={'class':'materialize-textarea'}),required=False)
rate = forms.ChoiceField(choices=RATE_CHOICES, widget=forms.Select(),required=True)
class Meta:
model = Review
fields= ('text', 'rate')
my views.py is:
class RateView(CreateView):
form_class = RateForm
template_name = 'rate.html'
def form_valid(self, form):
form.instance.product = Product.objects.get(slug=self.kwargs['slug'])
return super().form_valid(form)
def get_success_url(self):
return reverse('products:detail', kwargs={'slug': self.object.product.slug})
and my rate.html is:
{% extends "base.html"%}
{% block content %}
<form method="POST" action="" role="form" class="col s12">
{% csrf_token %}
<div class="input-field col s12">
{{ form.rate }}
</div>
<div class="input-field col s12">
{{ form.text }}
<label for="textarea1">Opinion</label>
</div>
<button type="submit" name="action" class="waves-effect waves-light btn"><i class="material-icons left">star</i>Rate</button>
</form>
{% endblock %}
my urls.py for the view is:
path('<slug:slug>/rate/', RateView.as_view(), name='rate-product1'),
The error message is telling you that the user field is not being set. You can do this in the form_valid function:
def form_valid(self, form):
...
form.instance.user = self.request.user
form.instance.product = Product.objects.get(slug=self.kwargs['slug'])
...
return super().form_valid(form)
Try to use this :-
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product , on_delete=models.CASCADE,null=True)
date = models.DateTimeField(auto_now_add=True)
text = models.TextField(max_length=3000 , blank=True)
rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES)
likes= models.PositiveIntegerField(default=0)
dislikes = models.PositiveIntegerField(default=0)
def __str__(self):
return self.user.full_name
What i have changed :-
I have set null = True in your product variable, which is with ForeignKey

'Category' object is not iterable

I am new to programming
I have different categoriries in my django website, I created the model, view. but when I try to go to the localhost/category/categoryname, I get the error: "Category object is not iterable"
I appreciate your help in advance
#url.py
urlpatterns = [
path('', home, name='home'),
path('article/<slug:slug>', detail, name='detail'),
path('article', article, name='article'),
path('category/<slug:slug>', category, name='category')]
###############################################
#views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse, Http404
from .models import Article, Category
# Create your views here.
def home(request):
context = {
"articles": Article.objects.filter(status="Published")
}
return render(request, 'website/home.html', context)
def detail(request, slug):
context = {
"article": get_object_or_404(Article, slug=slug, status="Published")
}
return render(request, 'website/detail.html', context)
def article(request):
context = {
"articles": Article.objects.filter(status="Published"),
"category": Category.objects.filter(status=True)
}
return render(request, 'website/article.html', context)
def category(request, slug):
context = {
"category": get_object_or_404(Category, slug=slug, status=True)
}
return render(request, 'website/category.html', context)
###############################
#models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=300, verbose_name="Category Topic")
slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address")
status = models.BooleanField(default=True, verbose_name="Do you want to show?")
position = models.IntegerField(verbose_name="position")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['position']
def __str__(self):
return self.title
class Article(models.Model):
STATUS_CHOICES = (
('Draft', 'Draft'),
('Published', 'Published')
)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=100, unique=True)
category = models.ManyToManyField(Category, verbose_name="Category", related_name="articles")
description = models.TextField()
thumbnail = models.ImageField(upload_to="images")
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
class Meta:
ordering = ['-publish']
def __str__(self):
return self.title
######################
#category.html
{% for article in category.articles.all %}
<article class="entry" data-aos="fade-up">
<div class="entry-img">
<img src="{{ article.thumbnail.url }}" alt="" class="img-fluid">
</div>
<h2 class="entry-title">
{{ article.title }}
</h2>
<div class="entry-meta">
<ul>
<li class="d-flex align-items-center"><i class="icofont-user"></i>
John Doe</li>
<li class="d-flex align-items-center"><i class="icofont-wall-clock"></i>
<time>{{ article.publish }}</time></li>
<li class="d-flex align-items-center"><i class="icofont-tags"></i>
<ul class="tags">
{% for cat in article.category.all %}
{{ cat.title }}
{% endfor %}
</ul>
</li>
<li class="d-flex align-items-center"><i class="icofont-comment"></i>
12 Comments</li>
</ul>
</div>
<div class="entry-content">
{{ article.description|truncatewords:30}}
<div class="read-more">
Read More
</div>
</div>
</article><!-- End blog entry -->
{% endfor %}
your code is shallow- please do this to retrieve category list
def get_queryset(self):category =
get_object_or_404(Category, slug=self.kwargs.get("slug"))
return Post.objects.filter(category_id=category).order_by("-created")
you can use this to retieve category by specific list
Article.objects.filter(post__category__contains='politics'),
I changed the view and the problem solved:
def category(request, slug):
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"category": cat.articles.all()
}
return render(request, 'website/category.html', context)

My comments are not being displayed in a django blog

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}

How can I add a comment to user on an app that has a relationship many-to-many with another model that has a relationship with other?

I get a huge stuck. now I have many of models which has a relationship between them at many apps I 'll explain that as following:
- The first model is (UserProfile) that has (one to one) relation with (User) model
also, I have (UserAsking) that has relation (ForeignKey) with (UserProfile) and last part is (Comment) That has (Many to many) relations with (UserAsking). in this case, I want to make a comment and this comment that has a relationship with UserAsking model. I'm in trouble, how can I do that?
I find that (many-to-many) is different from any another relationship and I can't get the instance as an argument in (Comment) model
if anyone can give me any help?
thank you in advance
account/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
CHOICE = [('male', 'male'), ('female', 'female')]
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
city = models.CharField(max_length=20, blank=False)
phone = models.IntegerField(default=0, blank=True)
sex = models.CharField(max_length=10, default='male', choices=CHOICE)
skill = models.CharField(max_length=100, default='You have no skills yet')
logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(receiver=create_profile, sender=User)
community/models.py
from django.db import models
from account.models import UserProfile
from django.db.models.signals import post_save
CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]
class UserAsking(models.Model):
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
def __str__(self):
return self.title
class Comment(models.Model):
userasking = models.ManyToManyField(UserAsking)
comment = models.TextField(max_length=500, blank=True)
community/views.py
from django.shortcuts import render, redirect, get_list_or_404
from .forms import UserAskingForm, CommentForm
from .models import UserAsking
from django.contrib.auth.decorators import login_required
#login_required
def user_asking(request):
form = UserAskingForm
if request.method == 'POST':
form = UserAskingForm(request.POST, instance=request.user.userprofile)
if form.is_valid():
asking = form.save(commit=False)
asking.title = form.cleaned_data['title']
asking.question = form.cleaned_data['question']
asking.field = form.cleaned_data['field']
asking = UserAsking.objects.create(userprofile=request.user.userprofile,
title=asking.title,
question=asking.question,
field=asking.field)
asking.save()
return redirect('community:user_questions')
else:
form = UserAskingForm()
return render(request, 'community/asking_question.html', {'form': form})
return render(request, 'community/asking_question.html', {'form': form})
#login_required
def user_questions(request):
all_objects = UserAsking.objects.all().order_by('-title')
all_objects = get_list_or_404(all_objects)
return render(request, 'community/user_questions.html', {'all_objects': all_objects})
def question_view(request, user_id):
my_question = UserAsking.objects.get(pk=user_id)
comment_form = CommentForm
#x = request.user.userprofile.userasking_set
if request.method == 'GET':
comment_form = comment_form(request.GET)
if comment_form.is_valid():
comments = comment_form.save(commit=False)
comments.comment = comment_form.cleaned_data['comment']
# you have to edit on userasking instance
#comments = Comment.objects.create(userasking=request.user.userprofile.userasking_set, comment=comments)
comments.save()
#return render(request, 'community/question_view.html', {'x': x})
return render(request, 'community/question_view.html', {'my_question': my_question,
'comment': comment_form})
community/forms.py
from django import forms
from .models import UserAsking, Comment
class UserAskingForm(forms.ModelForm):
title = forms.CharField(required=True,
widget=forms.TextInput(attrs={'placeholder': 'Type Your Title...',
'class': 'form-control',
'data-placement': 'top',
'title': 'type your title',
'data-tooltip': 'tooltip'
}),
help_text='Be specific and imagine you’re asking a question to another person')
question = forms.CharField(required=True,
widget=forms.Textarea(attrs={'placeholder': 'Type Your Details Of Your Question...',
'class': 'form-control',
'data-placement': 'top',
'title': 'type your question simply',
'data-tooltip': 'tooltip'
}),
help_text='Include all the information someone would need to answer your question')
class Meta:
model = UserAsking
fields = '__all__'
exclude = ['userprofile']
class CommentForm(forms.ModelForm):
comment = forms.CharField(max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': 'Type your comment simply',
'class': 'form-control'}))
class Meta:
model = Comment
fields = ['comment']
community/question_view.html
{% extends 'base.html' %}
{% block title %} This Question Belong To User: {{ request.user }} {% endblock %}
{% block body %}
<!-- Full Question View -->
<div class="my_question">
<div class="container">
<div class="answer-question">
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="title">
<h3 class="text-primary">{{ my_question.title }}</h3>
<span class="clock">1 hour ago</span>
</div>
<div class="question">
<p class="">{{ my_question.question }}</p>
</div>
<div class="field">
<span>{{ my_question.field }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Options e.g 'Edit, Comment, Delete etc...' -->
<div class="options">
<div class="container">
<div class="col-sm-12">
<a data-showin=".my-form" class="showin">Comment</a> |
Edit |
Delete
<span>
Like |
Unlike
</span>
</div>
<hr>
<!-- Comment Text -->
<div class="user-answer">
<div class="row">
<div class="col-xs-12">
{% for field in comment %}
<p>(medo) - sub comment</p>
<p>1 hour ago</p>
{% endfor %}
</div>
</div>
</div>
<!-- Comment Field -->
{% include 'community/comment_form.html' %}
{{ x }}
</div>
</div>
{% endblock %}
community/comment_form.html
<form method="get" action="" class="hide my-form">
{% csrf_token %}
<div class="row">
{% for field in comment %}
<div class="col-sm-10">
<div class="form-group">
{{ field }}
</div>
</div>
<div class="col-sm-1">
<button type="submit" class="btn btn-primary btn-lg">Add Comment</button>
</div>
{% endfor %}
</div>
</form>
community/urls.py
from . import views
from django.urls import path
app_name = 'community'
urlpatterns = [
path('', views.user_questions, name='user_questions'),
path('ask-question/', views.user_asking, name='user_asking'),
path('ask-question/question-view/<int:user_id>/', views.question_view, name='question_view'),
]

django, does not display the avatar in the comments

I extended standart django user model by one-to-one field. Made news block, and added comments there. In comments i cant display user avatar from UserProfile model, cause dont understand how correctly ask database for it D;. Here my code:
main/models.py
from django.db import models
from django.utils import timezone
from django.contrib import auth
from django.contrib.auth.forms import User
from django.shortcuts import render, redirect
from profiles.models import UserProfile
# Create your models here.
class News(models.Model):
news_title = models.CharField(max_length=250)
news_body = models.TextField(max_length=2000, blank=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
image = models.FileField()
published_date = models.DateTimeField(blank=True, null=True)
def publish(self, request):
self.published_date = timezone.now()
self.save()
return redirect('index')
def __str__(self):
return self.news_title
class Comment(models.Model):
news = models.ForeignKey('main.News', related_name='comments',
on_delete=models.CASCADE)
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
profiles/models.py
class UserProfile(models.Model):
JEW_CHOICE = (
('Да', 'Да'),
('Нет', 'Нет'),
)
MF_CHOICE = (
('М', 'М'),
('Ж', 'Ж')
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=100, default='', blank=True)
city = models.CharField(max_length=100, default='', blank=True)
description = models.CharField(max_length=500, default='', blank=True)
website = models.URLField(default='', blank=True)
avatar = models.ImageField(default='', blank=True)
gender = models.CharField(max_length=100, choices = MF_CHOICE, default = 'М', blank=True)
jew = models.CharField(max_length=100, choices = JEW_CHOICE, default = 'Да', blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
#property
def avatar_url(self):
if self.avatar and hasattr(self.avatar, 'url'):
return self.avatar.url
main/views.py (meme_detail is the view, where should be comments with user info)
def meme_detail(request, pk):
news = get_object_or_404(News, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.news = news
comment.save()
return redirect('main:meme_detail', pk=news.pk)
else:
form = CommentForm()
return render(request, 'main/meme_detail.html', {'news': news, 'form': form,})
meme_detail.html (news template with comments)
{% extends 'main/base.html' %}
{% block body %}
<h2>{{news.news_title}}</h2>
<img src='{{news.image.url}}' name='image' width='500px;'><br>
{{news.news_body}} <br><br>
<div class="row">
<div class="col">
<b>{{news.author}}</b>
</div>
<div class="col">
<i>{{news.published_date}}</i>
</div>
</div>
<div class="underline"></div>
<h3>Комментарии:</h3><br>
{% for comment in news.comments.all %}
<div class="row">
<div class="col-"><img src="{{ userprofile.avatar.url }}" alt="user-avatar" width="100px" height="100px"></div>
<div class="col">{{ comment.text }}</div>
</div>
<div class="row">
<div class="col"><strong>{{ comment.author }}</strong></div>
<div class="col">{{ comment.created_date}}</div>
</div>
<div class="underline"></div>
<br>
{% empty %}
<p>Пока ещё нет комментариев :(</p>
{% endfor %}
{% if request.user.is_authenticated %}
<div class="row">
<form method="POST">
{% csrf_token %}
{{form.text}}<br><br>
<a class="btn btn-success" href="{% url 'main:meme_detail' pk=news.pk %}"><button class='btn btn-success'>Добавить коммент! </button></a>
</form>
</div>
{% else %}
<i>Вы не можете писать комментарии, необходимо зарегистрироваться!</i>
{% endif %}
{% endblock %}
So, in this template, where "userprofile.avatar.url" should be object reference on User avatar. I tryed a lot of things, but it always the same:not displaying
You should do:
<img src="{{ comment.author.userprofile.avatar.url }}" alt="user-avatar" width="100px" height="100px">
Your comment has a foreign key to User (author), and User has a one to one field to UserProfile, which is the one that has the avatar attribute.
Also another tip:
You shouldn't really reduce the image in CSS (width: 100px; height: 100px;), but instead use a tool that allows you to create thumbnails of images. I use sorl-thumbnail and can't recommend it enough.
The reason is that if every user uploads a 1000x1000 image, you are downloading those big images that you don't really need, hence your site will be slower.
Maybe you should try accesing the User object in the template, not the Userprofile.
<img src="{{ user.userprofile.avatar.url }}" ...

Categories