why the team names are not displaying in django html? - python

migrations.CreateModel(
name='BasketballScore',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('match_played', models.IntegerField(default='0')),
('lose', models.IntegerField(default='0')),
('win', models.IntegerField(default='0')),
('points', models.IntegerField(default='0')),
('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams_basketball', to='Schedule.Team')),
],
),
This is the portion from my migration folder, i think this is confirming that my BasketballScore model is migarted fine.
class BasketballScore(models.Model):
team = models.ForeignKey(Team, related_name='teams_basketball', on_delete=models.CASCADE)
match_played = models.IntegerField(default='0')
lose = models.IntegerField(default='0')
win = models.IntegerField(default='0')
points = models.IntegerField(default='0')
This is the actual model of BasketballScore.
class BasketballScoreView(generic.ListView):
context_object_name = 'matches'
template_name = 'Schedule/basketball_score.html'
queryset = BasketballScore.objects.all()
def get_queryset(self):
return BasketballScore.objects.all().order_by('-points')
This is the corresponding class BasketballScoreView in views.py.
{% extends 'Schedule/base.html' %}
{% block content %}
<div class="container">
<p><button onclick="window.location='{% url 'index' %}'" class="btn btn-default">Go Back</button></p>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<tr>
<th>Teams</th>
<th>Match</th>
<th>Win</th>
<th>Lose</th>
<th>Points</th>
</tr>
{% for match in matches %}
<tr>
<td>
<div style="width='100';height='20'"><img src="{{ match.team.image.url }}"></div>
{{match.team}}
</td>
<td><div class="text-center">{{match.match_played}}</div></td>
<td><div class="text-center">{{match.win}}</div></td>
<td><div class="text-center">{{match.lose}}</div></td>
<td><div class="text-center">{{match.points}}</div></td>
</tr>
{% endfor %}
</table>
</div>
</div>
{% endblock %}
Now this is the basketball_score.html page.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.horizontal { display: inline; background-color: lightgray; }
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Schedule</title>
{% load static %}
<!-- <link rel="stylesheet" href="{% static 'Schedule/css/bootstrap.css' %}" />
<link rel="stylesheet" href="{% static 'Schedule/css/style.css' %}" /> -->
{% block title %}
{% endblock %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
{% block content %}
{% endblock %}
</body>
<!-- <script src="{% static 'Schedule/js/calendar.js' %}"></script> -->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script>
var csrf_token = '{{ csrf_token }}'
</script>
</html>
Now the above code is base.html from which i have extended basketball_score.html. So when i am clicking on the Score Table button, which is taking me to the basketball_score.html page, except the table head that is th portion , nothing is displaying , that is no team name etc. Now i am adding the corresponding urls.py :
path('match/basketball_score/', views.BasketballScoreView.as_view(), name='basketball_score'),
Any help will be appreciated! :)

Make sure you actually have any BasketballScore objects in your database.

Related

Getting Image from image field to views.py model

I am making a social media site in Django. I have a page for making a new post. It has a form with a file field to take an image upload. I want to get the image in views.py to save in the database. In the image variable, a string is getting saved with the name of the image. Also, I don't want to use any external form like forms.py. Here I have also tried request.FILES["image"] but it returned an empty dict.
Views.py
def newpost(request):
if request.method == "POST":
image = request.POST.get("image")
caption = request.POST.get("caption")
post = Post(Image=image,Caption=caption,Owner=request.user.username)
post.save()
return redirect("/")
return render(request,"newpost.html")
newpost.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spark X- New Post</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}">
<script class="jsbin" src="{% static 'js/jquery.js' %}"></script>
<link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon">
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<div class="header">
<span class="topband">
<img src="{% static 'images/back icon.png'%}" class="topicon">
</span>
<div class="logoholder">
<p class="logotext">New Post</p>
</div>
</div>
<div class="mainarea">
<form action="" method="post">{% csrf_token %}
<input type="file" name="image" id="image" accept="image/*" class="imageUpload" onchange="readURL(this);"/>
<label for="image"><img src="{% static 'images/camera icon.png' %}" class="cameraIcon" id="blah"></label>
<input type="text" name="caption" placeholder="Caption... " class="caption">
<button type="submit" class="submit">Post</button>
</form>
</div>
</body>
</html>
models.py
class Post(models.Model):
Id = models.AutoField(primary_key=True)
Image = models.ImageField(upload_to="Posts")
date = models.DateTimeField(auto_now=True)
Caption = models.TextField()
Your help will really be appreciated.
I have figured it out. Just used request.FILES["image"] and added enctype="multipart/form-data" in form and it worked.

Html is not recognizing block, endblock arguments. Django query

*I am having trouble in my index.html file. {% extends 'base.html' %} works. But everything b/w
{% block content %}{% endblock content %} doesn't execute. Here are my files.
views.py:-*
from django.shortcuts import render
def index(request):
return render(request, 'main/index.html')
base.html:-
<!doctype html>
{%load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<title>To Do App</title>
</head>
<body>
<div>
<nav class=" navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="/">To Do App</a>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
</div>
</body>
</html>
index.html:-
{% extends 'base.html'%}
{% block content %}
<div class="row">
<div class="col">
<h2>Add Item</h2>
</div>
</div>
{% endblock content %}
All it shows is a navbar of dark color saying To Do App
I also tried adding advanced things like form but it didn't work so then i added this heading saying Add Item. And guess what it doesn't work
When I inspect elements in browser I can see your Heading "Add Item". The only problem was that the whole <div class="container">...</div> was hidden behind nav bar. And the reason was CSS.
Adding something like margin-top: 56px to .container may solve the problem.
Based on documentation you must use only 'endblock' tag when you are closing tag.So you must replace {% endblock content %} with {% endblock %}.

How to add a datepicker into Django ModelFrom?

These are my scripts -
models.py
from django.db import models
class Leave(models.Model):
...
from_date = models.DateField()
to_date = models.DateField()
def __str__(self):
return self.name
I wanted to have datepickers for the above DateField(s).
This is my form template:-
{% extends "base.html" %}
{% block content %}
<div class="container">
<h3> Fill out the form please! </h3>
<h4>
<form action="." role="form", method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type = "submit">Submit</button>
</form>
</h4>
</div>
{% endblock %}
So far, what i have done -
I have included this in my base.html.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
In my forms.py as I'm using ModelForms, I have included this code -
class LeaveRequestForm(ModelForm):
class Meta:
fields = ("from_date", "to_date")
model = Leave
widgets = {
'from_date' : DateInput(attrs={'class': 'datepicker'}),
'to_date' : DateInput(attrs={'class': 'datepicker'}),
}
But no datepicker is being reflected in my html template. I have read many other question related to this but couldn't understand. Hope, anyone explains me in detail.
base.html
...
<html>
<head>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
...
</head>
I think your code is correct. However, from your comment it looks like you're using Bootstrap. You need to import Jquery BEFORE bootstrap.min.js and not after. If you have a javascript error in your page, it will prevent the datepicker from working.

Unable to store multiple images in django database

I am working on a hotel booking site , in which i give the user a option to upload their hotel in the site, In that i am interested in user to upload multiple images with out any particular limit, i wrote the model , the user successfully uploading the images but i am unable to store it in the database .
I got struck on this issue, i have searched everything on the web from the past one week , still not yet resolved, please help me on this issue .
Here is my model
hotel_rating_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)
class Hotel(models.Model):
Hotel_Name = models.CharField(max_length=50)
location = models.CharField(max_length=20)
no_of_rooms = models.IntegerField()
rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
hotel_img = models.FileField(upload_to='hotel_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Hotel_Name
Here is my form
class add_hotel(forms.ModelForm):
class Meta:
model = Hotel
fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'user','hotel_img', )
# exclude = ['id']
widgets = {
'hotel_img' : forms.ClearableFileInput(attrs={'multiple': True})
}
Here is my view
class BasicUploadView(CreateView):
template_name = 'photos/basic_upload/index.html'
model = Hotel
form_class = add_hotel
success_url = reverse_lazy('home')
def get(self, request, *args, **kwargs):
form = add_hotel
return render(
self.request,
template_name = self.template_name,
context={'form' : form}
)
def post(self, request, *args, **kwargs):
import ipdb
ipdb.set_trace()
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name':photo.hotel_img.name, 'url': photo.hotel_img.url}
return redirect('home')
else:
data = {'is_valid' : False}
return render(request, self.template_name, {'form': form})
Here is my template
{% load static from staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Euphoria booking</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="{% static 'css/icomoon.css' %}">
<!-- Theme style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<div style="margin-bottom: 20px;">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table id="gallery" class="table table-bordered">
<tbody>
{% csrf_token %}
{% for field in form %}
<tr>
{{ field.errors }}
<td> {{ field.label_tag }}</td>
<td>{{ field }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<b>For uploading of more hotel photos</b>
<div align="center">
<button type="button" class="btn btn-primary js-upload-photos">
Upload photos
</button>
<input id="fileupload" type="file" name="hotel_img" multiple
style="display: none;"
data-url="{% url 'basic_upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>
<input type="submit" value="Submit" style="margin-left: 37%;" />
</form>
</div>
<div class="modal fade" id="modal-progress" data-backdrop="static" data- keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0% </div>
</div>
</div>
</div>
</div>
</div>
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static '/js/progress-bar-upload.js' %}"></script>
{% endblock %}
</div>
</body>
</html>
Ignore the progress bar , css stuff, i want to know why i am unable to store multiple images
Reference

Django template {% include not working

I'm new to Django. I'm having problem including a sub-template in a main template. The directory structure of my project is attached in the snapshot. I removed the default views.py and created my own folder named "views" and put my views in it. Here is what I've done:
1. app/views/__init__.py
from .home import *
2. app/views/home.py
from django.shortcuts import render
def index(request):
return render(request, 'home.html')
3. app/templates/home.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Administrator Section
</title>
<link type="text/css" rel="stylesheet" href="{% static "css/common.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/theme/transdmin.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/login.css" %}"/>
<script type="text/javascript" src="{% static "js/jquery-1.10.2.js" %}"></script>
<script type="text/javascript" src="{% static "js/common.js" %}"></script>
<script type="text/javascript" src="{% static "js/login.js" %}"></script>
</head>
<body>
<div>
<div id="wrapper" class="ys-adminform">
{% include "includes.header_logo.html" %}
<form id="form-login" class="admin-section-form frm">
<div class="header">
<br/>
<h1>Login</h1>
<br/>
</div>
<div class="content">
<div class="form-row">
<input name="email" class="input" placeholder="Email" type="text"/>
<div class="user-icon"></div>
</div>
<div class="form-row">
<input name="password" class="input password" placeholder="Password" type="password"/>
<div class="pass-icon"></div>
</div>
</div>
<div class="footerlogin">
<input class="button" name="btn-login" value="Authenticate" type="button"/>
<div class="message" style="font-weight: bold; padding-top:16px;"> </div>
</div>
</form>
</div>
</div>
{% include "includes.footer.html" %}
</body>
</html>
The problem is include is not adding content from the sub-views.
I understand it could be a path problem but I tried various options like:
{% include "includes.header_logo.html" %}
{% include includes.header_logo.html %}
{% include "includes/header_logo.html" %}
{% include "templates.includes.header_logo.html" %}
{% include "app.templates.includes.header_logo.html" %}
etc.
You have to use directory slashes (/), not dots (.)
For example:
{% include "includes.footer.html" %}
becomes this:
{% include "includes/footer.html" %}
As suggested by Leistungsabfall, "includes/footer.html" works. The header was not working because it had:
This line must be crashing and because of which header was not working.
Simply add template folder with slash .... like
{% include "blog/footer.html" %}

Categories