How to link a comment to a single post in django? - python

I have a problem which I want to help me solve.
I have a "Post" with comments included but, when I comment a "Post" the comment I made in "Post 1" appears in "Post 2" and in all "Posts" and I want to link the comment to a single post, I've been looking for solutions but I have not been able to make it work.
EDIT I ADDED MY post/models.py
class Post(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
autor = models.CharField(max_length=200)
description = models.TextField()
likes = models.PositiveIntegerField(default=0)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
files = models.FileField(upload_to=upload_location, validators=
[validate_file_extension])
post_type = models.CharField(max_length=100, choices=Book_Type_Choices)
tags = TaggableManager()
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='cooments')
user = models.ForeignKey(User, unique=False)
text = models.CharField(max_length=250)
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
views.py
#login_required
def add_comment_to_post(request, pk):
post= get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post= post
comment.user = request.user
comment.save()
return redirect('post_detail', slug=post.slug)
else:
form = CommentForm()
return render(request, 'comments/add_comment_to_post.html', {'form':form})
my add_comment.html, this code fragment is included on my post_detail.html
<form action="{% url 'add_comment_to_post' pk=post.pk %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-primary" value="Comentar">
</form>
my book_detail.html
<div class="container">
<div class="row">
<div class="col-md-6 comment" style="text-align: center;">
<!-- HERE IS WHERE I INCLUDE THE add_comment.html -->
{% include 'comments/add_comment_to_post.html' %}
</div>
{% for comment in comments %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="col-sm-6 col-sm-offset-1">
<div class="media-body">
<div class="well well-lg">
<div class="avatar">
<img src="{{comment.user.profile.pic.thumbnail.url}}" class="img-responsive img-circle" alt="">
</div>
<h4 class="media-heading text-uppercase reviews">{{comment.user.get_full_name}} </h4>
<ul class="media-date text-uppercase reviews list-inline">
<li>{{comment.created_date}}</li>
</ul>
<p class="media-comment">
{{comment.text}}
</p>
<a class="btn btn-info btn-circle text-uppercase" href="#" id="reply"><span class="glyphicon glyphicon-share-alt"></span> Reply</a>
<a class="btn btn-warning btn-circle text-uppercase" data-toggle="collapse" href="#replyOne"><span class="glyphicon glyphicon-comment"></span> 2 comments</a>
</div>
</div>
</div>
{% endif %}
{% empty %}
<p>No hay comentarios que mostrar :(</p>
{% endfor %}
</div>
</div>
Any idea how I can make comments work? Thanks!

In the comment model try to remove the unique=False
Change
class Comment(models.Model):
user = models.ForeignKey(User, unique=False)
to
class Comment(models.Model):
user = models.ForeignKey(User) # remove unique=False
Do the above and take it from there

Related

How to add "Edit Function" in django

I need to add an edit button to my django app but it only redirects me to the homepage and no edit is saved.
this is my views.py code, i think that's where the issue is coming from
def editPhoto (request, pk):
photo = Photo.objects.get(id=pk)
categories = Category.objects.all()
if request.method == 'POST':
description = request.FILES.get('description')
photo.save()
return redirect ('/')
context = {'categories': categories, 'photo': photo}
return render(request, 'photos/edit.html', context)`
models.py
class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class Photo(models.Model): category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField()
def __str__(self):
return self.description`
edit.html
<div class="container"> <div class="row justify-content-center"> <div class="col">
Go Back
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %}
<div style="height: 90vh;">
<img style="max-width: 100%; max-height: 100%;" src="{{photo.image.url}}" class="center" >
</div>
<div>
<input required name="description" class="input" value="{{photo.description}}" type="text" size="60"></input>
</div>
<div class="center">
<button type="submit" class="btn btn-primary m-3; center">Update</button>
</div>
</div>
</div>
</div>`
The problem is that you are not saving any changes in your model.
description = request.FILES.get('description')
photo.save()
this should be changed to
photo.description = request.POST.get('description')
photo.save()
The problem is You are not passing id of photo you want to edit from your html file.
in Edit.html in form action="{% url photo.id %} , and make changes if needed in urls.py file.
by doing so id would be passed to views.py which acts as pk.

Form not save with custom form fields

Good morning guys, I have a problem with a form.
My code:
models.py
class AnagraficaGenerale(models.Model):
ragionesociale = models.CharField(max_length=40, null=True, blank=True)
cf = models.CharField(max_length=40, null=True, blank=True)
piva = models.CharField(max_length=40, null=True, blank=True)
forms.py
class AnagraficaGeneraleForm(forms.ModelForm):
class Meta:
model = AnagraficaGenerale
fields = '__all__'
views.py
#login_required
def anagrafica_new(request):
if request.method == "POST":
form = AnagraficaGeneraleForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('anagrafica_list')
else:
form = AnagraficaGeneraleForm()
return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form})
html
{% extends 'FBIsystem/basenobar.html' %}
{%load staticfiles %}
{% block content %}
<div id="page-wrapper">
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
Nuova Anagrafica
</h3>
<form method="POST" class="form-horizontal bordered-row">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
<label class="col-sm-2 control-label" > Ragione Sociale:</label>
<div class="col-sm-6">
{{ form.ragionesociale }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</form>
</div>
</div>
</div>
{% endblock %}
Everything seems ok but not save, if I try with {{form.as_table}} it save.
I think there is a problem with custom field but I don't know how.
whats wrong?
TY

Link author name to author profile page in Python-Django

I am trying to go to the author profile if i press on his name. This is my HTML which do these:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
</div>
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Info</legend>
<p class="text-secondary"><h3>Contact Me Here: </h3>{{ user.email }}</p>
</fieldset>
</form>
</div>
{% endblock content %}
In my views.py i have this:
def author_profile(request):
user = Post.author
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'blog/author_profile.html', context)
Where UserUpdateForm and ProfileUpdateForm from the forms.py have this code:
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
Class for the Post:
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
If i press on the name it is getting me to the user profile, I tried to work with Post.author but didn't worked.
It's my first time with django.

How to populate the form with value from current page?

I am learning to build a Post-comment app on Django. I understand how and why the current user can be assigned as author in the Comment form. But I do not understand how the post_id can be assigned to connect the comment with a particular post.
Tried using various methods obtained from searching the web. I keep getting various errors- TypeError, KeyError, ValueError etc.
My models.py is set up like this:
class Post(models.Model):
pid = models.AutoField(primary_key=True)
title = models.CharField(max_length=1000)
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('blog-home')#, kwargs={'pk':self.pk})
class Comment(models.Model):
cid = models.AutoField(primary_key=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.TextField()
comment_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.comment
def get_absolute_url(self):
return reverse('blog-home')
def save(self, *args, **kwargs):
super(Comment, self).save(*args, **kwargs)
The views.py with the comment create view is as follows:
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['comment']
def form_valid(self, form,**kwargs):
form.instance.author = self.request.user
form.instance.post_id = self.kwargs['post_id']
# IS THE ABOVE LINE CORRECT?
return super().form_valid(form)
The Answer button is on the home page included in every post block. The html for the same with the url for it is as below:
{% extends "blog/base.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 mb-8">
<div class="article-metadata mb-4">
<a class="mr-4" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y P e" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.pid %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
<div class="border border-top-0">
<a class="btn float-right btn-info mb-0 mt-1" href="{% url 'comment-create' post.pid %}">Answer</a>
$$$$$ HERE IS THE URL FOR THE ANSWER BUTTON $$$$
</div>
</div>
</article>
{% endfor %}
{% endblock %}
I do not know how to pass the post_id or the id of the post on which the user clicks. Please help!!

Django display a photo from a model

I've tried several of methods on how to retrieve an image from a model with no luck, this is where I'm at so far. I'd like to have the image show and when the user clicks on it, it opens a modal showing a projects detail.
models.py
class Project(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
client = models.CharField(max_length=200)
date = models.DateField(timezone.now())
service = models.CharField(max_length=200)
info = models.TextField()
photo = models.ImageField(upload_to='ports/static/img/',
default='ports/static/img/port_photo.png',
height_field='photo_height',
width_field='photo_width',)
photo_height = models.PositiveIntegerField(blank=True, default=900)
photo_width = models.PositiveIntegerField(blank=True, default=650)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
index.html
<section id="portfolio">
{% for project in projects %}
<div class="row">
<div class="col-lg-12 text-center">
<h2>Portfolio</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-sm-4 portfolio-item">
<a href="#portfolioModal1" class="portfolio-link" data-toggle="modal">
<div class="caption">
<div class="caption-content">
<i class="fa fa-search-plus fa-3x"></i>
</div>
</div>
<img src="{{ projects.photo.url }}" class="img-responsive" alt="">
</a>
</div>
</div>
</div>
{% endfor %}
</section>
views.py
from django.shortcuts import render
from .forms import ContactForm
from django.utils import timezone
from .models import Project
# Create your views here.
def index(request):
form_class = ContactForm
projects = Project.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'ports/index.html', {'form': form_class, 'projects': projects})
Look at your img tag. In the src attribute, you are using {{ projects.photo.url }}. So, you cannot get image from a queryset, you can only do so from an object of Project model. Use {{ project.photo.url }}

Categories

Resources