I am trying to add some functionality that would allow a reply to the comment and display that reply underneath the comment but after trying everything I am unable to see the
reply being displayed to the comment. There are no errors showing so I can't really figure it out. I am guessing something is not right in the template? Please find the codes below. Hope that is all it requires to get me some help.
MODELS: comment model & reply model
class Comment(models.Model):
"""comments for Post model"""
comment_post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name='comment_for_post', null=True, default='')
comment_text = models.TextField(null=True)
date_posted = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
"""Reverse the Comment to the url once action
has been taken with primary key to direct back to details page"""
return reverse('posts:post_details', kwargs={'pk': self.pk})
def __str__(self):
return self.comment_text
class Reply(models.Model):
"""add reply to commnets"""
reply_comment = models.ForeignKey(
Comment, on_delete=models.CASCADE, null=True, default='', related_name='comment_reply')
reply_text = models.TextField()
date_posted = models.DateTimeField(auto_now=True)
def __str__(self):
return self.reply_text
VIEWS: reply to comment view
#login_required
def reply_to_comment(request, pk):
comment = get_object_or_404(models.Comment, pk=pk)
if request.method == 'POST':
form = forms.ReplyCommentForm(request.POST)
if form.is_valid():
reply = form.save(commit=False)
reply.reply_comment = comment
reply.save()
return redirect('posts:post_details', pk=comment.pk)
else:
form = forms.ReplyCommentForm()
return render(request, 'posts/reply_comment_form.html', context={'form': form})
URLS:
urlpatterns = [
path('post_list/', views.PostListView.as_view(), name='post_list'),
path('user/<str:username>/', views.UserPostListView.as_view(), name='user_posts'),
path('create/', views.PostCreateView.as_view(), name='create'),
path('details/<int:pk>/', views.PostDetailView.as_view(), name='post_details'),
path('delete/<int:pk>/', views.PostDeleteView.as_view(), name='post_delete'),
path('update/<int:pk>/', views.PostUpdateView.as_view(), name='post_update'),
path('<str:category>/', views.CategoryPostListView.as_view(),
name='category_posts'),
path('posts/<int:pk>/comment', views.add_comment_to_post,
name='post_comment_list'),
path('delete_comment/<int:pk>/',
views.CommentDeleteView.as_view(), name='delete_comment'),
path('comment/<int:pk>/reply/', views.reply_to_comment, name='reply'),
TEMPLATE:
<div class='container'>
{% for reply in comment.comment_reply.all %}
<br>
{% if object.author == user %}
<div class="">
<ul>
<li>
<p >{{reply.reply_text}}</p>
<p class='text-capitalize'>From {{user.username}} on {{comment.date_posted|date:'d-M-y'}}.</p>
</li>
</ul>
</div>
{%else %}
<div class="">
<ul>
<li>
<p >{{reply.reply_text|safe}}</p>
<p class='text-capitalize'>From {{user.username}} on {{comment.date_posted|date:'d-M-y'}}.</p>
</li>
</ul>
{% endif %}
{% endfor %}
</div>
Try to add the code below:
context={'form': form, 'comment': comment}
Related
I ran into a problem I have questions that are related to items_buy_id , there are also choices that are related to question_id questions
Questions items_buy_id It turns out to connect
And with the choice you will not contact as it should
My models.py
from django.db import models
from datetime import datetime
from phonenumber_field.modelfields import PhoneNumberField
from django_resized import ResizedImageField
from email.policy import default
from django.utils.translation import gettext_lazy
class Items_buy(models.Model):
class Meta:
db_table = 'items_buy'
verbose_name = 'Телефон который покупаем'
verbose_name_plural = 'Телефоны которые покупаем'
image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона')
model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ')
text = models.TextField(max_length=500, verbose_name='Текст')
max_prise_iphone = models.FloatField(verbose_name='Максимальная цена telefoha')
image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy')
def __str__(self):
return self.model_produkt
class Question(models.Model):
class Meta:
db_table = 'question'
verbose_name = 'Вопрос к телефону'
verbose_name_plural = 'Вопросы к телефону'
items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
title = models.CharField(max_length=150,verbose_name='Заголовок вопросa')
question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text')
max_prise_qustion = models.FloatField(verbose_name='Максимальная цена')
def __str__(self):
return self.title
class Choice(models.Model):
class Meta:
db_table = 'choice'
verbose_name = 'Выбор ответа'
verbose_name_plural = 'Выбор ответов'
#items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
question_id = models.ForeignKey(Question, on_delete=models.RESTRICT)
title = models.CharField(max_length=1000, verbose_name='Заголовок выбора')
points = models.FloatField(verbose_name='Цена ответа')
#lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа')
def __str__(self):
return self.title
My urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('',views.home, name ='home'),
path('sell_iphone/', views.sell_iphone, name = 'sell_iphone'),
path('sell_iphone_page/<int:pk>/', views.sell_iphone_page, name= 'sell_iphone_page'),
path("getqestion/<int:pk>/", views.getqestion, name = 'getqestion'),
]
My html
{% load static %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/qestion.css' %}" type="text/css">
</head>
<body>
{% include 'navbar.html' %}
<div class="bar">
{% for question in test %}
<div class="bar_infor_bar">
<div class="bar_infor_bar_title">{{question.title}} </div>
<div class="wraper_sell_in_line_img_class2_qestion_text">{{question.question_text}}</div>
{% for choiceses in choice %}
<div class="bar_infor_button_nav">
<button class="bar_infor_button">{{choiceses.title}}</button>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</body>
{% endblock %}
My views.py
from django.shortcuts import render, redirect
from .models import Items_buy, Question, Choice, Answer, Orders
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def home(request):
return render(request, 'home.html')
def sell_iphone(request):
limit = request.GET.get('limit')
if limit == None:
limit = 40
limit = int(limit)
iphone = Items_buy.objects.filter()
count = iphone.count()
page = request.GET.get('page')
paginator = Paginator(iphone, 1)
try:
iphone = paginator.page(page)
except PageNotAnInteger:
page = 1
iphone = paginator.page(page)
except EmptyPage:
page = paginator.num_pages
iphone = paginator.page(page)
#pages = list(range(1, (paginator.num_pages + 1)))
iphone = Items_buy.objects.all()
#iphone = iphone[0:limit]
context = {'iphone':iphone, 'count':count, 'paginator':paginator, }
return render(request, 'sell_iphone.html', context)
def sell_iphone_page(request,pk ):
iphones = Items_buy.objects.filter(id=pk)
#question = Question.objects.all()
context = {'iphones':iphones, }
return render(request, 'sell_iphone_page.html', context)
`def getqestion( request, pk):
test = Question.objects.filter(items_buy_id = pk)
choice = Choice.objects.filter(question_id = pk)
context = {'test':test,'choice':choice}
return render(request, 'getqestion.html', context)`
I'm having a problem with the def getqestion function. I linked the question to the product, but the answer to the question didn't work at all
When using select choice = Choice.objects.filter(question_id = pk)
enter image description here
When using select choice = Choice.objects.all()
enter image description here
When using select choice = Choice.objects.filter(id = pk)
enter image description here
And you need 1.test1 to include: da, net, HY TAKOE
And 1.test2 included: 2,1,3
Thanks in advance to anyone who can suggest how to do this!!!
In my case it helped
views.py
class getqestion(generic.DetailView):
model = Items_buy
template_name = 'getqestion.html'
context_object_name = 'testing'
html
<div>
{% for testings in testing.question_set.all %}
<h1>{{testings.titles}}</h1>
<h3>{{testings.question_text}}</h3>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% csrf_token %}
<form action="{% url 'vote' testings.id%}" method="post">
{% for choice in testings.choice_set.all %}
<input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{choice.title}}</label>
{% endfor %}
{% endfor %}
</div>
<input type="submit" value="vote">
</form>
I am trying to display a username's profile picture in a blog/social media app when some user clicks on some other user's username but it is currently not working.
In my template: (I think my issue is I don't have access to post?)
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<img class="img-thumbnail account-img mt-3 " src="{{ username.profile.image.url }}">
</article>
<h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
<div class="infinite-container">
{% for post in posts %}
<div class="infinite-item">
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<!-- profile (model in user ).image (attribute) -->
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
</div>
{% endfor %}
</div>
My users\models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
In my blog/models.py:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
I can retrieve some user's username by {{ view.kwargs.username }}, how can I do this with profile pictures?
my blog\views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.db.models import Q
from .models import Post #from the model file in the current package import the Post class
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
def home(request):
context = {
'posts': Post.objects.all(), # querying the database
}
return render(request, 'blog/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
# it will get that user form that database if it exist, if user doesn't exist return 404,
# we are also using the User model, so need to import it
# 2nd parameter means that we are getting the username from the url
user = get_object_or_404(User, username=self.kwargs.get('username'))
# showing the posts by that specific user only
return Post.objects.filter(author=user).order_by('-date_posted')
# Looking at individual post
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
def search(request):
if request.method == "POST":
searched = request.POST['searched']
posts = Post.objects.filter(
Q(title__icontains=searched) |
Q(author__username__icontains=searched))
usernames = []
for post in posts:
usernames.append(post.author)
# remove duplicates of username
usernames = list(set(usernames))
context = {'searched': searched, 'posts': posts, 'usernames': usernames}
return render(request, 'blog/search.html', context)
else:
return render(request, 'blog/search.html', {})
Use ForeignKey instead of OneToOneField. Add a related_name:
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile")
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
in html:
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
You can write a custom method also.
e.g:
class Post(models.Model):
...
author = models.ForeignKey(User, on_delete=models.CASCADE)
...
def get_owner_pp(self):
return self.author.profile.image.url
in html:
<img class="rounded-circle article-img" src="{{ post.get_owner_pp }}">
trying to display all the ingredients that are associated to a recipe, however:
my models:
class IngredientList(models.Model):
name = models.CharField(max_length=100)
class RecipeList(models.Model):
name = models.CharField(max_length=100)
ingredients = models.ManyToManyField('IngredientList')
instructions = models.TextField(max_length=400)
amount = models.IntegerField()
my views:
from django.shortcuts import render
from .models import IngredientList, RecipeList
def index(request):
ing = RecipeList.objects.all()
context = {'ing': ing}
return render(request, 'myrecipes/home.html', context)
my template:
<div class="card-body">
<h4>{{ details.name}} <span class="badge badge-info">{{details.cuisine}}</span></h4>
<p class="card-text">Ingredients: {{details.ingredients}}</p>
<p class="card-text">Instructions: {{details.instructions}}</p>
<p class="card-text">This makes {{ details.amount}} meals</p>
</div>
my output is "myrecipes.IngredientList.None"
You need to access the queryset of the ingredients, so details.ingredients.all, furthermore you need to iterate over these ingredients, so you work with:
{% for ingredient in details.ingredients.all %}
{{ ingredient }}
{% endfor %}
In the view you can load all the related Ingredients with one extra query with:
def index(request):
ing = RecipeList.objects.prefetch_related('ingredients')
return render(request, 'myrecipes/home.html', {'ing': ing})
This will avoid making an extra query per RecipeList.
I am trying to show the related field of the user on the webpage using Django.
I have models:
Models.py
class Companies(models.Model):
company_name = models.TextField()
company_email = models.EmailField()
company_owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.company_name
class Cars(models.Model):
company = models.ForeignKey('Companies', on_delete=models.CASCADE)
car_model = models.TextField()
views.py:
class UserCompanyCars(ListView):
model = Cars
template_name = 'home/company_cars.html'
context_object_name = 'cars'
slug_field ="username"
paginate_by = 100
def get_queryset(self):
company_n = get_object_or_404(Companies, company_owner=self.request.user)
return Cars.objects.filter(company=company_n)
and my html is:
{% extends 'home/base.html' %}
{% block content %}
<h1 class="mb-3"> Cars of {{user.Companies.company_name}}</h1>
{% for car in cars %}
<div class="media-body">
<div class = "article-metadata">
<p class="article-content">{{car.company}}</p>
{{car.car_model}}
<p class="article-content">{{car.car_carry }}</p>
</div>
</div>
{% endfor %}
{% endblock content %}
What I am trying to achieve is to write out "Cars of TestCompany (26)" on the webpage, but I cannot figure out how to get the Company_Name which is owned by the user. I have been trying all those Companies.objects... variations but none of them seem to work.
Try this (sample code taken from my project):
category = get_object_or_404(Category, pk=self.kwargs['pk'])
context['allcategories'] = MyPosts.objects.filter(category=category)
return context
This will filter all posts in the database based on certain categories. You can apply the same solution to your code.
If this solution does not work, please try to give more details about the problem.
I used the modelformset_factory method for multiple photo uploads. But when I want to update the post, I don't know how to do this, I tried something, but this only serves to re-upload photos and upload the uploaded photos again. How can I update or delete a previously uploaded photo? Also, I cannot access the photos in formset as {{formset.image}}. How can I access this?
Views.py
def post_update(request, slug):
post = get_object_or_404(Post, slug=slug)
if not request.user.is_authenticated and not request.user == post.seller or not request.user.is_admin:
raise Http404
ImageFormSet = modelformset_factory(PostImage, form=PostImageForm, extra=5, can_delete = True)
form = PostForm(data=request.POST or None, instance = post, files = request.FILES or None)
formset = ImageFormSet(data=request.POST or None, files= request.FILES or None, queryset=PostImage.objects.filter(post__slug=slug))
if form.is_valid():
if formset.is_valid():
for forms in formset.cleaned_data:
if forms:
image = forms['image']
print(forms['image'])
photo = PostImage(post=post, image=image)
photo.save()
form.save(commit=True)
messages.success(request,"Success")
return HttpResponseRedirect(reverse('gayrimenkul:detail',kwargs={'slug':form.instance.slug}))
return render(request,'post_update.html',{'form':form,'formset':formset,'slug':slug})
post_update.html
{% extends "main_page.html" %}
{% load static %}
{% block icerik %}
{% load crispy_forms_tags %}
<div class="row">
<div class="container">
<h2 class="page_header">İlan Ver</h2>
<hr>
{% if form.errors %}
{{form.errors}}
{% endif %}
<div class="col-md-12">
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{form.media}}
{{form|crispy}}
<div class="row">
<div class="col-md-6">
{{formset}}
</div>
<div class="col-md-6">
<button type="submit" id="inp" class="btn btn-outline-primary" style="float:right;">Kaydet</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
Creating posts works successfully.
def post_create(request):
if not request.user.is_authenticated:
raise Http404
ImageFormSet = modelformset_factory(PostImage, form=PostImageForm, extra=5)
if request.method == 'POST':
post_form = PostForm(request.POST, request.FILES)
formset = ImageFormSet(request.POST, request.FILES, queryset=PostImage.objects.none())
if post_form.is_valid():
created_post = post_form.save(commit=False)
created_post.seller = request.user
created_post.save()
for form in formset.cleaned_data:
if form:
image = form['image']
photo = PostImage(post=created_post, image=image)
photo.save()
messages.success(request,'Success')
return HttpResponseRedirect(reverse('gayrimenkul:detail',kwargs={'slug':created_post.get_slug()}))
else:
post_form = PostForm()
formset = ImageFormSet(queryset = PostImage.objects.none())
return render(request,'post_create.html',{'form':post_form,'formset':formset})
Before checking if the form is valid just filter the model of the formset
data = PostImage.objects.filter(post=post)
Give index of the item for a formset item starting form 0 and (f)the item itself and if the item of the id is not changed than save previous item itself else change the database image with the new image you have updated.
if formset.is_valid():
for index, f in enumerate(formset):
if f.cleaned_data:
if f.cleaned_data['id'] is None:
pic = PostImage(post=post, image=f.cleaned_data.get('image'))
pic.save()
elif f.cleaned.data['image'] is False:
pic = PostImage.objects.get(id = request.POST.get('form-' + str(index) + '-id'))
pic.delete()
else:
pic = PostImage(post=post, image=f.cleaned_data.get('image'))
d = PostImage.objects.get(id=data[index].id) #get slide id which was uploaded
d.image = pic.image # changing the database title with new title
d.save()
This might work for you or get you some idea.