Nothing is happened when I put comment button - python

Nothing is happened when I put comment button.I wanna make a page which is shown comment&recomment.I wrote codes in views.py
class DetailView(generic.DetailView):
model = POST
template_name = 'detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_form'] = CommentCreateForm()
context['recomment_form'] = ReCommentCreateForm()
return context
class CommentCreateView(generic.View):
def post(self, request, *args, **kwargs):
form = CommentCreateForm(request.POST)
post = POST.objects.get(pk=kwargs['post_pk'])
if form.is_valid():
obj = form.save(commit=False)
obj.target = post
obj.save()
return redirect('detail', pk=post.pk)
class ReCommentCreateView(generic.View):
def post(self, request, *args, **kwargs):
form = ReCommentCreateForm(request.POST)
comment = Comment.objects.get(pk=kwargs['comment_pk'])
if form.is_valid():
obj = form.save(commit=False)
obj.target = comment
obj.save()
return redirect('detail', pk=comment.target.pk)
in urls.py
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'),
path('comment/<int:post_pk>/',views.CommentCreateView.as_view(), name='comment'),
path('recomment/<int:comment_pk>/', views.ReCommentCreateView.as_view(), name='recomment'),
]
in detail.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DETAIL</title>
</head>
<body>
<div id="comment-area">
{% for comment in post.comment.all %}
<div class="media m-3">
<div class="media-body">
<h5 class="mt-0">
<span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span>
{{ comment.name }}
<span class="lead text-muted">{{ comment.created_at }}</span>
Recomment
</h5>
{{ comment.text | linebreaksbr }}
{% for recomment in comment.recomment.all %}
<div class="media m-3">
<div class="media-body">
<h5 class="mt-0">
{{ recomment.name }}
<span class="lead text-muted">{{ recomment.created_at }}</span>
</h5>
{{ recomment.text | linebreaksbr }}
</div>
</div>
{% endfor %}
<form action="{% url 'recomment' comment_pk=comment.id %}" method="post">
{{recomment_form}}
{% csrf_token %}
<input class="btn btn-primary" type="submit" value="re-comment">
</form>
</div>
</div>
{% endfor %}
<form action="{% url 'comment' post_pk=post.id %}" method="post">
{{comment_form}}
{% csrf_token %}
<input class="btn btn-primary" type="submit" value="comment">
</form>
</div>
</body>
</html>
in models.py
class Comment(models.Model):
name = models.CharField(max_length=100, blank=True)
text = models.TextField()
target = models.ForeignKey(POST, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
When I put comment button, no error happens but same page which is form's content is blank is shown.I wanna show {% for comment in post.comment.all %} ~ {% endfor %},so I really cannot understand why I cannot do it.I think values are not in model, so I print out print(obj) in CommentCreateView's class, and correctly value is shown in terminal.What is wrong in my code?How should I fix this?

Do you have the objects actually created in the DB? There's some info missing in the post (like the Form itself, etc), anyway:
If you didn't set the related_name argument on the foreign key, the correct access to post's comments is via post.comment_set.all(), see:
https://docs.djangoproject.com/en/2.0/topics/db/queries/#following-relationships-backward
May I point out that you're doing a lot of work, that Django's generic views can do for you (guess it's OK if you're learning, otherwise, it's just more code to maintain).
Things like CreateView, UpdateView, and DeleteView from django.views.generic.edit. For more info see:
https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#model-forms

Related

in Django : Why nothing happens when I try to Create new note with the html form in the notes.html page

I've just started my first app with Django by following a video on YouTube.
The app is a students dashboard with 8 tools and features to help the student to make note, search for help, save books, etc.
When I follow the steps I get stuck in the creation of a new note but note from the admin side but from the actual notes template that has a crispy form and a create button.
The program is supposed for writing a title and description (the content of the note) and then press the create button. When I try to click, nothing is happening.
#This is the view.py page in the dashboard app :
from django.shortcuts import render
from . forms import *
from django.contrib import messages
# Create your views here.
def home(request):
return render(request, 'dashboard/home.html')
def notes(request):
if request.method == "POST":
form = NotesForm(request.POST)
if form.is_valid():
notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description'])
notes.save()
messages.success(request,f"Notes Added from {request.user.username} Successfully")
else:
form = NotesForm()
notes = Notes.objects.filter(user=request.user)
context = {'notes':notes,'form':form}
return render(request,'dashboard/notes.html',context)
and this is the notes.html page in the dashboard app > template folder > dashboard folder :
{% extends 'dashboard/base.html' %}
<!-- Load the static files here -->
{% load static %} {% load crispy_forms_tags %}
<!-- loading the crispy files must be here so now i write anything to
create some space and lines here we go baby lets add more -->
{% block content %}
<div class="container">
<div class="row">
{% for note in notes %}
<div class="col-md-3">
<a href="#">
<div class="card">
<div class="card-header">{{note.title}}</div>
<div class="card-body">{{note.description|slice:"0:100"}}</div>
<div class="card-footer mt-auto">
<i class="fa fa-trash fa-2x"></i>
</div>
</div>
</a>
</div>
{% endfor %}
<br /><br />
</div>
</div>
<br /><br />
<div class="container">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Notes</legend>
</fieldset>
{% crispy form %}
<div class="form-group">
<button href="" class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
</div>
{% endblock content %}
so, this the models.py file too
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Notes(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
class Meta:
verbose_name = "notes"
verbose_name_plural = "notes"
in case the problem is not here, please take a look on the inside this forms.py
from dataclasses import fields
from django import forms
from . models import *
class NotesForm(forms.ModelForm):
class Meta:
model = Notes
fields = ['title', 'description']
and .. urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home, name='home'),
path('notes',views.notes, name="notes")
]
There are many minor mistakes in the code:
It is {{form|crispy}} to display the form not {% crispy form %}.
You are also not using HttpResponseRedirect[django-doc] for redirecting, after saving form from POST data, you should always return an HttpResponse, its a good practice.
Try below code:
Notes.html
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
{% for note in notes %}
<div class="col-md-3">
<a href="#">
<div class="card">
<div class="card-header">{{note.title}}</div>
<div class="card-body">{{note.description|slice:"0:100"}}</div>
<div class="card-footer mt-auto">
<i class="fa fa-trash fa-2x"></i>
</div>
</div>
</a>
</div>
{% endfor %}
<br /><br />
</div>
</div>
<br /><br />
<div class="container">
<form method="POST" action="{% url 'notes' %}" novalidate>
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Notes</legend>
</fieldset>
{{form|crispy}}
<input type="submit" value="Create">
</form>
</div>
{% endblock content %}
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import render
from . forms import *
from django.contrib import messages
from django.urls import reverse
def home(request):
return render(request, 'dashboard/home.html')
def notes(request):
if request.method == "POST":
form = NotesForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
descrip = form.cleaned_data['description']
notes = Notes(
user=request.user, title=title, description=descrip)
notes.save()
messages.success(
request, f"Notes Added from {request.user.username} Successfully")
return HttpResponseRedirect(reverse('thanks'))
else:
form = NotesForm()
notes = Notes.objects.filter(user=request.user)
context = {'notes': notes, 'form': form}
return render(request, 'dashboard/notes.html', context)
def thanks(request):
return render(request, 'dashboard/thanks.html')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('notes/', views.notes, name="notes"),
path('thanks/', views.thanks, name='thanks')
]
thanks.html
<body>
<h2>The form successfully submitted</h2>
</body>
Your forms.py can be remain same as it is.

The 'header_image' attribute has no file associated with it

When I create a new post with an image, everything is fine, but if I edit it, I want to delete the image using the "clear" button, then this error appears, and if I change, then nothing changes, but there are no errors
here is models.py
`
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])`
here is views.py
`
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post
class BlogListView(ListView):
model = Post
template_name = 'home.html'
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None`
post_base.html
`{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
rel="stylesheet">
<link href="{% static 'css/base.css' %}" rel="stylesheet">
</head>
<body>
<div>
<header>
<div class="nav-left">
<h1>Django blog</h1>
<h2>Admin</h2>
</div>
<div class="nav-right">
+ New Blog Post
</div>
</header>
{% if user.is_authenticated %}
<p>Hi {{ user.username }}!</p>
{% else %}
<p>You are not logged in.</p>
Log In<br>
<p>Sign up</p>
{% endif %}
{% block content %}
{% endblock content %}
</div>
</body>
</html>`
post_detail.html
`
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'#' }}">
{{ post.body|safe }}
{% endblock content %}`
post_new.html
`
{% extends 'base.html' %}
{% block content %}
<h1>New post</h1>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
{% endblock content %}`
post_edit.html
`
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}`
enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server. So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded.
You forgot to add enctype='multipart/form-data' in your post_edit.html form and that's the reason your files aren't sent to Django. Following code should work.
post_edit.html
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post" enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}

How to add comments functionality to a django web app?

I want to add the functionality of adding comments in the same html page with post details starting from this class based view.
I also have left below the model and the html template that I want to use.
Please help me
The class based view that I want to use as a starting point :
class PostDetailView(DetailView):
model = Post
The model:
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.content
The html template:
<div id="comments">
<h3>{{ comments.total }}</h3>
<ol class="commentlist">
{% for comment in comments %}
<li class="depth-1">
<div class="avatar">
<img width="50" height="50" alt=""
src="{{ comment.user.profile.image.url }}"
class="avatar">
</div>
<div class="comment-content">
<div class="comment-info">
<cite>{{ comment.user }}</cite>
<div class="comment-meta">
<time datetime="2014-07-12T23:05"
class="comment-time">{{ comment.date_added|date:"F d, Y" }}</time>
</div>
</div>
<div class="comment-text">
<p>{{ comment.content }}</p>
</div>
</div>
</li>
{% endfor %}
</ol> <!-- /commentlist -->
<!-- respond -->
<div class="respond">
<h3>Leave a Comment</h3>
<!-- form -->
<form action="" method="POST">
{% csrf_token %}
<fieldset>
<div class="group">
{{ form|crispy }}
<button class="submit full-width" type="submit">Add Comment</button>
</div>
</fieldset>
</form> <!-- /contactForm -->
</div> <!-- /respond -->
</div> <!-- /comments -->
Override DetailView's get_context_data method to transfer comments through context. add this method in your class PostDetailView.
def get_context_data(self, **kwargs):
context = {}
if self.object:
context['object'] = self.object
context['comments']=Comments.objects.all() #modify this queryset according to how you want to display comments
context.update(kwargs)
return super().get_context_data(**context)
than in template you can include this piece of code
{% for comment in comments%}
<div>
{{comment}}
</div>
{% endfor %}
and to get comments, In forms.py
from django import forms
from .models import Comments
class CommentForm(forms.Form):
class Meta:
model = Comments
fields = [] #mention fields of comments u want to render in form
you have to extend FormView along with DetailView as DetailView dosent have post method to override.
So in views.py:
from .forms imoprt CommentForm
from django.views.generic.edit import FormView
class PostDetailView(DetailView, FormView):
model = Post
form_class = CommentForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
#do what you want with data
I suggest you go through the Methods of the classes to override them.FormView

Not being able to display comments in template

I'm making a Post and Comment model by taking reference from internet. i created and Post and Comment model and it looks ok in django admin panel. i can add post and also a comment to any particular post. but getting trouble when I'm trying to display the comment under the post in templates(under post detail views). PLEASE HELP
models.py
class Post(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = RichTextField()
tags = models.CharField(max_length=50,blank=True,null=True)
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE)
author = models.ForeignKey(User,max_length=50,on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('discuss')
views.py
class PostDetailView(DetailView):
model = Post
def add_comment_to_post(request,pk):
return 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.save()
return redirect('post-detail',pk=post.pk)
else:
form = CommentForm()
return render(request, 'discuss/comment_form.html',{'form':form})
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post-detail', pk=post_pk)
post_detail.html
{% extends 'index.html' %}
{% block content %}
<article class="media content-section">
<div class="medaia-body">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="image not found">
<div class="article-metedata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{object.author}}</a>
<small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<img class="query-img" src="{{ object.image.url }}" alt="image not found">
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div class="post-update-delete">
<button class="btn btn-outline-primary">Edit Post</button>
<button class="btn btn-outline-primary">Delete Post</button>
</div>
{% endif %}
<hr>
<a class="btn btn-primary btn-comment" href="{% url 'add_comment_to_post' pk=post.pk %}">Add Comment</a>
<!-- ############################### ABOVE CODE IS WORKING ############################# -->
<!-- ########################## GETTING PROBLEM IN BELLOW CODE ######################### -->
{% for comment in object.comments.all %}
{% if user.is_authenticated %}
{{ comment.create_date }}
{{ comment.text|safe|linebreaks }}
{{ comment.author }}
{% endif %}
{% empty %}
<p>No Comment</p>
{% endfor %}
{% endblock %}
in post_deatil.html i also tried {% for comment in post.comments.all %} but it is also not working
Since you did not specify a related_name=… parameter [Django-doc], the related_name is by default comment_set, so you iterate over the comments with:
{% for comment in object.comment_set.all %}
…
{% endfor %}
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Django - Simple User Register not working [Not saving to DB]

I have simple user registration page, but its not saving to the database.
Issue: Register form displays, upon clicking submit button, doesn't do anything! Stays there (it should show a HttpResponse('User Registered') And save to db
I've know I'm missing something, but what? ideas please.
Views.py
from django.shortcuts import render
from django.views.generic import CreateView
from website.forms import RegisterUserForm
from django.http import HttpResponseForbidden
# Create your views here.
class RegisterUserView(CreateView):
form_class = RegisterUserForm
template_name = "account/register.html"
# Overide dispatch func - check if the user is authenticated or return forbidden
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseForbidden()
return super(RegisterUserView, self).dispatch(request, *args, **kwargs)
# Overide form valid method behaviour
def form_valid(self, form):
# False commit - don't save to db, locally cleaning users password first
user = form.save(commit=False)
user.set_password(form.cleaned_data['password'])
user.save();
# Change to redirect - later one!
return HttpResponse('User Registered')
def Home(request):
return render(request, 'account/home.html')
Register.html
{% extends 'base.html' %}
{% block title %}
Register
{% endblock %}
{% block head %}
{% load static %}
<link href="{% static 'forms.css' %}" rel="stylesheet">
{% endblock %}
{% block heading %}
<h1>Register</h1>
{% endblock %}
{% block body %}
<div class="bg-contact2" style="background-image: url('images/bg-01.jpg');">
<div class="container-contact2">
<div class="wrap-contact2">
<form class="contact2-form validate-form">
<span class="contact2-form-title">
<h2> Teacher's Register </h2>
</span>
{% csrf_token %}
{{ form.as_p }}
<div class="container-contact2-form-btn">
<div class="wrap-contact2-form-btn">
<div class="contact2-form-bgbtn"></div>
<button class="contact2-form-btn">
Send Your Message
</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!--
<h2>FORM</h2>
<form action="{% url 'register' %}" class="contact2-form validate-form" method="post ">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register">
</form> -->
{% endblock %}
forms.py
from django import forms
from django.contrib.auth.models import User
class RegisterUserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)
class Meta:
# Connect to the user model and select which fields we want input for user model
model = User
fields = ['username', 'email']
# Validate password matched / and clean them
def clean_password2(self):
cd = self.cleaned_data
if cd['password2'] != cd['password']:
raise ValidationError("Password don't match")
return cd['password2']
I think you are missing the type in your button tag:
<form method="POST">
<span class="contact2-form-title">
<h2> Teacher's Register </h2>
</span>
{% csrf_token %}
{{ form.as_p }}
<div class="container-contact2-form-btn">
<div class="wrap-contact2-form-btn">
<div class="contact2-form-bgbtn"></div>
<button type="submit" class="contact2-form-btn">
Send Your Message
</button>
</div>
</div>
</form>
form tag should have an attribute action to tell where to take the data of your form to. So in Register.html you should add
action="{% url 'nameofyourviewgiveninurls.py'%}"
in your form tag

Categories

Resources