Django wont display my comments on template - django

I've tried to implement the comments within the html page after creating them in my models and I have migrated them but they still wont appear within the page although when I add a comment from the admin side of the website the add comment button I added in before the else statement in the html disappears, which means that it isn't empty but the comments still wont show?
Models.py
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
class Comment(models.Model):
user = models.ForeignKey(UserProfile, related_name="profile", on_delete=models.CASCADE)
photo = models.ForeignKey(Photo, related_name="comments", on_delete=models.CASCADE)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.user.username + ': ' + self.text
and then here is the Html portion
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible" content="IE-edge'>
<title>Photo</title>
<meta name='viewport' content='width-device-width, initial-scale=1'>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body class="m-5">
<div class="container">
<div class="row justify-content-center">
<div class="col">
Go Back
<div style="height: 90vh;">
<img style="max-width: 100%; max-height: 100%;"
src="{{photo.image.url}}">
<p>
{{photo.description}}
</p>
<h4>Comments...</h4>
{% if not photo.comments.all %}
No Comments Yet...<a href="#">
add one
</a>
{% else %}
{% for comment in photo.comment.all %}
<strong>
{{ comment.date }}
</strong>
<br/>
{{ comment.text }}
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
</body>

Related

How to implement a base form in multiple views in Django?

So I have a base.html file where all the components that are common in all the other templates are present. I'm trying to implement Newsletter form functionality in my django project. This form should be displayed on all the pages(in the top navbar).
But the problem here is that this form only shows up on base.html and not the other template pages which extend this file.
base.html
{% load static %}
<html lang="en">
<body>
<div id="overlay">
<div class="overlay-body form-group">
<h2>Subscribe to our newsletter</h2>
<form method="post">
{% csrf_token %}
{{form}}
<button type="reset" onclick="off()">Cancel</button>
<button type="submit" value="submit">Submit</button>
</form>
</div>
</div>
<div class="container">
<header>
<div>
<div class="col-4 "><a id="blog-side" onclick="on()">Subscribe</a></div>
<div class="col-4 ">
<img src="{% static 'img/logo.png' %}" alt="Logo">
Blog
</div>
<div class="col-4 ">About</div>
</div>
</header>
{% block content %}
{% endblock content %}
</div>
</body>
</html>
Here's the Newsletter form from models.py
class Newsletter(models.Model):
email = models.EmailField()
entered_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.email
forms.py
class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ('email', )
Any idea as to how to setup this form in the other templates?
The thing here is that you will need to make sure you send in the form in every single view you create. Can I see your views.py file please?

How to insert a second model into my ListView

views.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView
)
from django.template import context
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('post__date_posted')[:5],
'posts': Post.objects.all()
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_posted')[:5]
title_posts.html
{% extends "main/base.html" %}
{% load static %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'main/title_posts.css' %}">
{% endblock styles %}
{% block content %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
<hr>
{% for post in posts %}
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
{% endblock content %}
models.py
class Post(models.Model):
article_title = models.CharField(max_length=60, default="Article Title Place Holder")
content = HTMLField(default="Article Content Pace Holder")
date_posted = models.DateTimeField(default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png')
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
Edit: I have a page that displays posts/articles for a certain video game. Currently my query returns the posts from the Post model for that video game. However, I am unsure of how to also display the video games description and images on that same page. The {{game.cover.url}}, ((game.description}}, and {{game.cover_display.url}} do not show up when I load the page because I am unsure how to also get that specific games objects from the Game model.
{% for post in posts %}
{% with post.game.set.all|first as game %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300 black">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
{% endwith %}
<hr>
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
You are using ForeignKey. So use like this in loop
{% with post.game_set.all|first as game %}
<img src="{{ game.url }}" />
{% endwith %}
As you are already filtering by game then only add the game in your get_context_data() method
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context

Django form not submitting or providing error messages

When I submit my form, it doesn't post the form data and just reloads the form.
It was working beforehand but I'm not sure what I've changed that doesn't make it work anymore. Posting the data through the admin still works fine.
The only 'error' message I can see is in the terminal:
which can be seen here
It sends a get request instead of a post request as well. I've also tested it with removing the JS and bootstrap CDNs but the issue is still the same.
My code is below:
Here is my views.py
def create(request):
if request.method == 'POST':
form = EventCreateForm(request.POST, request.FILES)
if form.is_valid():.
instance = form.save(commit=False)
instance.author = request.user
instance.save()
instance.save_m2m()
return redirect('event:home')
else:
form = EventCreateForm()
return render(request, 'event/create.html', {'form': form})
create.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{{ form.media }}
<div class="container-fluid">
<div class="col-md-4">
<div class="page-header">
<p> Create an event!</p>
</div>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form | crispy}}
<button type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
{% endblock %}
Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'event/css/custom.css' %}">
<title>Django Project</title>
</br>
<div class="container-fluid" style='font-family:arial'>
<center>
<h2> Welcome to the django website!</h2>
</center>
</div>
{{ form.media }}
</head>
<!-- body of the text -->
<body>
{% if messages %}
{% for messages in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% if user.is_authenticated %}
<nav class="navbar navbar-expand-md navbar-dark bg-dark sticky-top">
<div class="navbar-nav">
<a class="nav item nav-link active" href="{% url 'event:home' %}">Home</a>
<a class="nav item nav-link" href="{% url 'profiles:profile' %}">Profile</a>
<a class="nav item nav-link" href="{% url 'profiles:edit' %}">Edit profile</a>
<a class="nav item nav-link" href="{% url 'event:create' %}">Create</a>
<a class="nav item nav-link" href="{% url 'profiles:logout' %}">Logout</a>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-success" type="submit">Search</button>
</div>
{% else %}
Login
Register
{% endif %}
</nav>
{% block content %}
{% endblock %}
</body>
</html>
Models.py
class Event(models.Model):
title = models.CharField(max_length=100)
link = models.TextField()
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
image = models.ImageField(default='default.jpg', upload_to='event_images')
image_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(100, 100)],
format='JPEG',
options={'quality': 60})
start = models.DateField(blank=True, null=True)
start_time = models.TimeField(blank=True, null=True)
end = models.DateField(blank=True, null=True)
end_time = models.TimeField(blank=True, null= True)
description = HTMLField('description')
tags = models.ManyToManyField(Tags)
subject = models.ManyToManyField(Subject)
attendees = models.ManyToManyField(User, related_name = 'attendees', blank=True)
def __str__(self):
return f'{self.title}'
def get_absolute_url(self):
return reverse('event:detail', kwargs={'pk': self.pk})
Thanks everyone in advance,
All help will be greatly appreciated!
You may have deleted your action. Try adding the url back?
<form method="post" action="{% url "event:create" %}" enctype="multipart/form-data">
I had a problem like this too. I solved it by getting rid of a div tag containing a bootstrap class (<div class="form-group>" to be more precise) located around my form.
same problem existed for me also , the silly mistake you have done is the button thing in your create.html file , replace that with input tap with type submit and class btn , button doesn't submit request
Try this :
<input type="submit" class="btn btn-primary" value="Submit">
i know its bit late but this may seem helpful

Django - Bootstrap4 - DateRangePicker - django-bootstrap-datepicker-plus

Firstly, i am not an ultra expert about Django objects or structures, i learn with numerous and various curses and i try during the development of my website to reach the must clear and efficient code in my Django project.
Now i try to make a date range picker in bootstrap 4 (4.1.3)
I will obtain the same result as this tool django-bootstrap-datepicker-plus, i trying to follow the example code but i dont know how to add this tool on my django project.
For now i cant successfully render the daterangepicker on the template.
I share the files that concerns by this tool.
models.py
class Event(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateField()
end_date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
start_datetime = models.DateTimeField()
end_datetime = models.DateTimeField()
start_month = models.DateField()
end_month = models.DateField()
start_year = models.DateField()
end_year = models.DateField()
def __str__(self):
return self.name
forms.py
from bootstrap_datepicker_plus import DatePickerInput
from bootstrap_datepicker_plus import TimePickerInput
from bootstrap_datepicker_plus import DateTimePickerInput
from bootstrap_datepicker_plus import MonthPickerInput
from bootstrap_datepicker_plus import YearPickerInput
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = [
'start_date', 'end_date',
'start_time', 'end_time',
'start_datetime', 'end_datetime',
'start_month', 'end_month',
'start_year', 'end_year',
]
widgets = {
'start_date': DatePickerInput(options={'format': 'YYYY-MM-DD', 'debug': True}).start_of('event active days'),
'end_date': DatePickerInput(options={'format': 'MM/DD/YYYY'}).end_of('event active days'),
'start_datetime': DateTimePickerInput(options={'debug': True}).start_of('event active dtime'),
'end_datetime': DateTimePickerInput().end_of('event active dtime'),
'start_time': TimePickerInput(options={'debug': True}).start_of('event active time'),
'end_time': TimePickerInput().end_of('event active time'),
'start_month': MonthPickerInput().start_of('active month'),
'end_month': MonthPickerInput().end_of('active month'),
'start_year': YearPickerInput().start_of('active year'),
'end_year': YearPickerInput().end_of('active year'),
}
views.py
#login_required
def visual_general(request):
....
# get data for the table of django-tables2 and other stuff
....
# Get data
data = create_data_table_general(samples, references, strains, analyzepipelines, sts, id_access_list)
# Add data to the table
table = GeneralTable(data)
form_date_range = EventForm()
return render(request, 'visual/visual_general.html', {'table': table, 'form_date_range': form_date_range})
urls.py
# -*- coding: utf-8 -*-
# Library Django
from django.conf.urls import url
# Inner functions
from . import views
urlpatterns = [
url(r'^visual/General', views.visual_general, name="visual_general"),
]
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}MySite{% endblock %}</title>
{% load static %}
{% block head %}
<link rel="stylesheet" type="text/css" href="{% static 'css/menu.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}" />
{% endblock %}
{% block css %}
<!-- blueimp Gallery styles -->
<link rel="stylesheet" href="/static/css/blueimp-gallery.min.css">
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link rel="stylesheet" href="/static/css/jquery.fileupload-ui.css">
<!-- CSS adjustments for browsers with JavaScript disabled -->
<noscript><link rel="stylesheet" href="/static/css/jquery.fileupload-ui-noscript.css"></noscript>
{% endblock %}
{% block bootstrap_css %}
<link rel="stylesheet" href="{% static 'bootstrap-4.1.3/css/bootstrap.min.css' %}"/>
{% endblock %}
{% block bootstrap_js %}
<script src="{% static 'jquery/jquery3.min.js' %}"></script>
<script src="{% static 'js/popper.min.js' %}"></script>
<script src="{% static 'bootstrap-4.1.3/js/bootstrap.min.js' %}"></script>
{% endblock %}
</head>
<body>
<br />
<section id="content">
{% block content %}
<h1>No content set</h1>
{% endblock %}
</section>
</body>
</html>
visual_general.html
{% extends "base.html" %}
{% load django_tables2 %}
{% load static %}
{% block title %} Visual of data {% endblock%}
{% block content %}
<div id="form">
<form
id="test"
action="{% url 'visual_general' %}"
method="get">
{% csrf_token %}
<div
class="well"
style="margin: 2px; padding: 1px 20px 0 40px; position: relative; top: 0; background: #B8C1C8;">
<div class="row">
{{form_date_range.media}}
<div class="row">
<div class="form-group col-sm-8 col-md-6">
<center>
<input
class="button"
type="submit"
value="Filter" />
</center>
</div>
</div>
</div>
</div>
</form>
</div>
{% endblock %}
Thanks in advance for anyone can help me to add a date range picker or for any tips or comment on my code.

How to make an object slider in django?

I have written a simple article publishing site in Django 1.8.
Here is the model that I'd like to slide:
class Article(models.Model):
nid = models.IntegerField(default=0)
headimage = ImageWithThumbsField(upload_to='images', blank=True, sizes=((200,200),(400,400)))
title = models.CharField(max_length=100)
author = models.CharField(max_length=100, blank=True)
body = models.TextField()
teaser = models.TextField('teaser', blank=True)
created=models.DateTimeField(default=datetime.datetime.now)
pub_date=models.DateTimeField(default=datetime.datetime.now)
categories = models.ManyToManyField(Category, blank=True)
tags = TaggableManager()
Now I want to slide the article teasers on front page. I am new to both Django and JS so wondering how best to make such slider?
I have googled and looked at Django packages but could not find anything that can kick me to start. So appreciate your hints.
Update: here is the view that I'd like to connect it to the carousel slider:
def main(request):
"""Main listing."""
posts = Article.objects.all().order_by("-pub_date")[:5]
return render_to_response("article/list-articles.html",
dict(posts=posts, user=request.user))
An example using bootstrap's carousel:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Bootstrap 3 Carousel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<style type="text/css">
</style>
</head>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
<li data-target="#myCarousel" data-slide-to="4"></li>
<li data-target="#myCarousel" data-slide-to="5"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
{% for p in posts %}
{% if forloop.counter == 1 %}
<div class="item active">
{% else %}
<div class="item">
{% endif %}
<img src="{{ p.headimage.url }}" alt="Image" width="460" height="345">
<div class="carousel-caption">
<h3>{{ p.title }}</h3>
<p>{{ p.teaser }}</p>
</div>
</div>
{% endfor %}
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</html>
You didn't posted your js+html so here is an example library. Carousel
If you investigate, you see that you can link images in a single html. So if you want to do this in django way, you must pass your model to template and iterate items and create the html that you need.
Here is a start point example by using the linked javascript:
views.py ==>
def any_view(request):
retdict = {'articles': Article.objects.all(),}
return render_to_response("template.html", retdict, context_instance=RequestContext(request))
template.html ==>
<div id="owl-demo">
{%for article in articles%}
<div class="item"><img src="{{article.headimage}}" alt="Owl Image"></div>
{% endfor %}
</div>
javascript part ==>
$(document).ready(function() {
$("#owl-demo").owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 4,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
});
And next time remember that this is a Q&A site, please try something before asking a question and share this with us.