I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page.
Could anyone help me? (I'm using django 1.10)
models.py
class Tags(models.Model):
tag_name = models.CharField(max_length=250)
tag_chip_type = models.CharField(max_length=250)
tag_size = models.CharField(max_length=250)
tag_frequency = models.CharField(max_length=250)
tag_standards = models.CharField(max_length=250, null=True, blank=True)
tag_memory = models.CharField(max_length=250)
tag_reading_distance = models.CharField(max_length=250)
tag_environment = models.CharField(max_length=250)
tag_mounting_method = models.CharField(max_length=250)
tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True)
tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True)
tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True)
tag_image = models.FileField()
def __unicode__(self):
return self.tag_name + ' ' + self.tag_image.url
def get_absolute_url(self):
return reverse('tag:index')
views.py
def selected(request):
tags = request.GET.getlist('selected')
return render(request, 'tag/selected.html', {'all_tags':tags})
urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
index.html
<form action="{% url 'tag:selected' %}" method="get">
<table id="selected" class="white-table table-bordered table-hover" style="width:95%; margin: 3% auto;">
<thead>
<tr>
<th style="text-align:center;"><input type="checkbox" onClick="toggle(this)"></th>
<th></th>
<th style="text-align:center;">Name</th>
<th style="text-align:center;">Chip Type</th>
<th style="text-align:center;">Size</th>
<th style="text-align:center;">Frequency</th>
<th style="text-align:center;">Memory</th>
<th style="text-align:center;">Reading distance</th>
<th class="null" style="text-align:center;">Environment</th>
<th class="null" style="text-align:center;">Mounting method</th>
</tr>
</thead>
<tbody>
{% for tags in all_tags %}
<tr>
<td style="text-align:center;"><input type="checkbox" name="selected" value="{{ tags.tag_image.url }}"></td>
<td> <img src="{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> </td>
<td style="text-align:center;"> {{ tags.tag_name }} </td>
<td style="text-align:center;"> {{ tags.tag_chip_type }} </td>
<td style="text-align:center;"> {{ tags.tag_size }} </td>
<td style="text-align:center;"> {{ tags.tag_frequency }} </td>
<td style="text-align:center;"> {{ tags.tag_memory }} </td>
<td style="text-align:center;"> {{ tags.tag_reading_distance }} </td>
<td class="null" style="text-align:center;"> {{ tags.tag_environment }} </td>
<td class="null" style="text-align:center;"> {{ tags.tag_mounting_method }} </td>
</tr>
{% endfor %}
</tbody>
</table>
<input class="btn-primary" style="float:right; margin-right:2.5%; margin-bottom:3%;" type="submit" value="Submit">
</form>
{% endblock %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
selected.html
{% block body %}
{% for tags in all_tags %}
<div class=" col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<img src=" '/media/'{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />
</div>
</div>
</div>
{% endfor %}
{% endblock %}
First you have to make sure your pictures can be displayed, with http: //xxxxxxx/xxx/you.jpg in the browser test
You have to add url pattern :
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
Views.py
def meterstatistics(request):
varr = Meters_table.objects.all()
vark = Meter_Data_table.objects.all()
Lastkwh = Meter_Data_table.objects.last()
Lasttime = Meter_Data_table.objects.last()
d = {
'Lastkwh': Lastkwh, 'Lasttime': Lasttime, 'vark': vark, 'varr': varr
}
return render(request, 'meterstatistics.html', d)
models.py
class Meters_table(models.Model):
Meter_id = models.AutoField(unique=True, editable=False, primary_key=True)
Account_id = models.CharField(max_length=128)
Location_id = models.CharField(max_length=150, help_text="(ID of the locations table)")
RR_No = models.CharField(max_length=128)
Meter_type = models.CharField(max_length=150, help_text="(Industry,Residential &
Transformer)")
Meter_make = models.CharField(max_length=150)
Meter_model = models.CharField(max_length=150)
Usage_type = models.CharField(
max_length=150, help_text="(Industry,Residential & Transformer)")
def __str__(self):
return self.Usage_type
class Meter_Data_table(models.Model):
id = models.AutoField(unique=True, editable=False, primary_key=True)
Meter_id = models.CharField(max_length=150)
IMEI_Number = models.CharField(max_length=150)
KWH = models.CharField(max_length=128)
KVAH = models.CharField(max_length=150)
PF = models.CharField(max_length=150)
BMD = models.CharField(max_length=128)
Meter_time_stamp = models.DateTimeField(max_length=150)
Receive_time_stamp = models.DateTimeField(max_length=150)
def __str__(self):
return self.Meter_id
HTML
<table id="table">
<thead class="thead-light bg-primary">
<tr>
<th scope="col">Meter_id</th>
<th scope="col">DCU IMEI</th>
<th scope="col">RR No</th>
<th scope="col">Last KWH</th>
<th scope="col">PF</th>
<th scope="col">Last Meter Time Stamp</th>
<th scope="col">Location</th>
<th scope="col">Frequency</th>
<th scope="col">Relay</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
{% for i in vark %}
<td>{{i.Meter_id}}</td>
<td>{{i.IMEI_Number}}</td>
<td>{{i.RR_No}}</td>
<td>{{i.KWH }}</td>
<td>{{i.PF}}</td>
<td>{{i.Meter_time_stamp }}</td>
<td></td>
<td></td>
<td><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></td>
<td>
<a href="{% url 'graph' %}"><i style="font-size: 30px;" class="fa fa-eye"
aria-hidden="true"></i> </a>
<a href="metertableedit/{{i.Meter_id}}"><i style="font-size: 30px;"
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<!-- <a href="delmetertable/{{i.Meter_id}}"><i style="font-size: 30px;"
class="fa fa-trash" aria-hidden="true"></i></a> -->
<!-- </button> -->
</td>
</tr>
</tbody>
{% endfor %}
</tbody>
</table>
I need to show this all data's in web page but those data's not in a single table those are different table data using for loop only one table is possible
and how to join that table AND how to show the data in the webpage table
without using for loop inside for loop.
Than you ....!
I would add a ForeignKey from the Meter table to the Meter_Data table
class Meter_Data_table(models.Model):
meter = models.ForeignKey(Meters_table, on_delete=models.CASCADE)
In views.py select all the needed data, using "select_related" to include the meter data in the data DB query.
vark = Meter_Data_table.objects.select_related('meter').all().order_by('meter')
This way, meter data can be accessed through the ForeignKey, using a single query:
for i in vark:
print(i.meter.Location_id)
In the template example:
{{i.meter.Location_id}}
template.html
<tr>
{% for i in vark %}
<td>{{i.Meter_id}}</td>
<td>{{i.IMEI_Number}}</td>
<td>{{i.RR_No}}</td>
<td>{{i.KWH }}</td>
<td>{{i.PF}}</td>
<td>{{i.Meter_time_stamp }}</td>
<td>{{i.meter.Location_id}}</td>
<td></td>
<td><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></td>
<td>
<a href="{% url 'graph' %}"><i style="font-size: 30px;" class="fa fa-eye"
aria-hidden="true"></i> </a>
<a href="metertableedit/{{i.Meter_id}}"><i style="font-size: 30px;"
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<!-- <a href="delmetertable/{{i.Meter_id}}"><i style="font-size: 30px;"
class="fa fa-trash" aria-hidden="true"></i></a> -->
<!-- </button> -->
</td>
</tr>
Complete Error
I have a model which has two foreign keys as below
class BatPerformance(models.Model):
country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='country')
player = models.ForeignKey('PlayerStructure', on_delete=models.CASCADE, related_name = 'playerbatperf')
# Batting Performance Fields
batting_Matches = models.IntegerField(default=0)
batting_innings = models.IntegerField(default=0)
batting_notouts = models.IntegerField(default=0)
batting_Runs = models.IntegerField(default=0)
batting_HS = models.IntegerField(default=0)
batting_avg = models.FloatField(default=0.0)
batting_ballsfaced = models.IntegerField(default=0)
batting_strikerate = models.FloatField(default=0)
batting_hundreds = models.IntegerField(default=0)
batting_fifty = models.IntegerField(default=0)
batting_twohundreds = models.IntegerField(default=0)
batting_fours = models.IntegerField(default=0)
batting_sixes = models.IntegerField(default=0)
def __str__(self):
return str(self.player) + ': ' + str(self.match)
I created a form for the same with all the fields.
my views.py as Below.
class BatStatistics(FormView):
template_name = 'form.html'
form_class = NewPlayerBatStatistics
success_url = '.'
def form_valid(self, form):
# Form is Valid
new_team = form.save(commit=True)
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form):
# Form is Invalid
print(form.errors)
return self.render_to_response(self.get_context_data(form=form))
urls.py
urlpatterns = [
path('', test),
path('homepage/', Index.as_view(), name = 'index'),
path('teamdetails/', Teams.as_view(), name = 'teamlist'),
path('fixtures/',Fixtures.as_view(), name='fixtures'),
path('teamdetails/newteam', NewTeam.as_view(), name='newteam'),
path('teamdetails/<int:pk>/', PlayerDetailView.as_view(), name='teamname'),
path('teamdetails/newplayers/', NewPlayer.as_view(), name='newplayer'),
path('teamdetails/<int:player_details_pk>/<int:pk>/', PlayerStatistics.as_view(), name= 'playerdetails'),
path('teamdetails/<int:player_details_pk>/<int:pk>/batstatistics', BatStatistics.as_view(), name= 'batstatistics'),
path('teamdetails/<int:player_details_pk>/<int:pk>/bowlstatistics', BowlStatistics.as_view(), name= 'bowlstatistics'),
]
In the form fields, the first two fields are the country and player name.SO whenever I select the dropdown of the country I don't want to see all the country players in the player names dropdown field.
For eg: If I select England I need to see only England players in the player dropdown.
so as per the urls.py
path('teamdetails/', Teams.as_view(), name = 'teamlist'), Gives me the list of all the team names.
path('teamdetails/<int:pk>/', PlayerDetailView.as_view(), name='teamname'), Gives me the first country name players list and so on..
path('teamdetails/<int:player_details_pk>/<int:pk>/', PlayerStatistics.as_view(), name= 'playerdetails') Gives me the players statistics details
path('teamdetails/<int:player_details_pk>/<int:PlayerStructure_details_pk>/batstatistics', BatStatistics.as_view(), name= 'batstatistics') Gives me to update the statistics of the player which is a form.
So in this form, I see all the country lists and player lists in the dropdown when I give
path('teamdetails/batstatistics'
which i dont need. so i have formed a url with all the primary keys linked URL but I see the above error.
url Link given on the button click in playerdetails.html
{% extends 'base.html' %}
<!DOCTYPE html>
<html>
{% block content %}
<head>
<meta charset="utf-8"> {% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/details.css' %}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="btn pull-right">
Batting Statistics Update
Bowling Statistics Update
</div>
</div>
</div>
<div>
<div class="cb-col cb-col-100 cb-bg-white">
<div class="cb-col cb-col-20 cb-col-rt"><img height="200" width="270" title="profile image" src="{{PlayerStructure_details.imageUri.url}}"></div>
<div class="cb-col cb-col-80 cb-player-name-wrap">
<h1 itemprop="name" class="cb-font-40">{{PlayerStructure_details.firstname}} {{PlayerStructure_details.lastname}}</h1>
<h3 class="cb-font-18 text-gray">{{PlayerStructure_details.country}}</h3></div>
</div>
<div class="cb-col cb-col-100 cb-bg-grey">
<div class="cb-col cb-col-33 text-black">
<div class="cb-hm-rght">
<div class="cb-font-16 text-bold"> Personal Information</div>
<div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Born</div>
<div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BirthDate}} </div>
<div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Birth Place</div>
<div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BirthPlace}} </div>
<div class="cb-col cb-col-40 text-bold">Jersey No</div>
<div class="cb-col cb-col-60"> {{PlayerStructure_details.JerseyNumber}} </div>
<div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Role</div>
<div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.Role}} </div>
<div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Batting Style</div>
<div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BattingStyle}}t </div>
<div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Bowling Style</div>
<div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BowlingStyle}} </div>
</div>
</div>
<div class="cb-col cb-col-67 cb-bg-white cb-plyr-rt-col">
<div class="cb-hm-rght cb-player-bio">
<div>
{% for players in PlayerStructure_details.playerbatperf.all %}
<div class="cb-plyr-tbl">
<div class="cb-font-16 text-bold cb-lst-dom">Batting Career Summary</div>
<table class="table cb-col-30 cb-plyr-thead">
<thead>
<tr class="cb-bg-grey cb-font-12">
<th></th>
<th class="cb-plyr-th text-right" title="Matches Played">M</th>
<th class="text-right" title="No of Innings Batted">Inn</th>
<th class="text-right" title="No of Not Outs">NO</th>
<th class="text-right" title="No of Runs Scored">Runs</th>
<th class="text-right" title="Highest Score">HS</th>
<th class="text-right" title="Batting Average">Avg</th>
<th class="text-right" title="No of Balls Faced">BF</th>
<th class="text-right" title="Batting Strike Rate">SR</th>
<th class="text-right" title="No of 100s Scored">100</th>
<th class="text-right" title="No of 200s Scored">200</th>
<th class="text-right" title="No of 50s Scored">50</th>
<th class="text-right" title="No of fours hit">4s</th>
<th class="text-right" title="No of sixes hit">6s</th>
</tr>
</thead>
<tbody>
<tr>
<td class="cb-col-8"><strong>ODI</strong></td>
<td class="cb-plyr-tbody text-right">{{players.batting_atches}}</td>
<td class="text-right">{{players.batting_innings}}</td>
<td class="text-right">{{players.batting_notouts}}</td>
<td class="text-right">{{players.batting_Runs}}</td>
<td class="text-right">{{players.batting_HS}}</td>
<td class="text-right">{{players.batting_avg}}</td>
<td class="text-right">{{players.batting_ballsfaced}}</td>
<td class="text-right">{{players.batting_strikerate}}</td>
<td class="text-right">{{players.batting_hundreds}}</td>
<td class="text-right">{{players.batting_fifty}}</td>
<td class="text-right">{{players.batting_twohundreds}}</td>
<td class="text-right">{{players.batting_fours}}</td>
<td class="text-right">{{players.batting_sixes}}</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endfor %}
</div>
<div>
{% for players in PlayerStructure_details.playerbowlperf.all %}
<div class="cb-plyr-tbl">
<div class="cb-font-16 text-bold cb-lst-dom">Bowling Career Summary</div>
<table class="table cb-col-30 cb-plyr-thead">
<thead>
<tr class="cb-bg-grey cb-font-12">
<th></th>
<th class="cb-plyr-th text-right" title="Matches Played">M</th>
<th class="text-right" title="No of Innings Bowled">Inn</th>
<th class="text-right" title="No of Balls Bowled">B</th>
<th class="text-right" title="No of Runs Conceded">Runs</th>
<th class="text-right" title="Wickets">Wkts</th>
<th class="text-right" title="Best Bowling in Innings">BBI</th>
<th class="text-right" title="Best Bowling in Match">BBM</th>
<th class="text-right" title="Economy">Econ</th>
<th class="text-right" title="Bowling Average">Avg</th>
<th class="text-right" title="Bowling Strike Rate">SR</th>
<th class="text-right" title="Five Wickets in an Innings">5W</th>
<th class="text-right cb-plyr-stump" title="Ten Wickets in an Match">10W</th>
</tr>
</thead>
<tbody>
<tr>
<td class="cb-col-8"><strong>ODI</strong></td>
<td class="cb-plyr-tbody text-right">{{players.bowl_matches}}</td>
<td class="text-right">{{players.bowl_innings}}</td>
<td class="text-right">{{players.bowl_noofballs}}</td>
<td class="text-right">{{players.bowl_runs}}</td>
<td class="text-right">{{players.bowl_wkts}}</td>
<td class="text-right">{{players.bowl_wickets_lbw}}</td>
<td class="text-right">{{players.bowl_wickets_economy}}</td>
<td class="text-right">{{players.bowl_wickets_stumped}}</td>
<td class="text-right">{{players.bowl_wickets_avgt}}</td>
<td class="text-right">{{players.bowl_wickets_SR}}</td>
<td class="text-right">{{players.bowl_five_wickets}}</td>
<td class="text-right">{{players.bowl_ten_wickets}}</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
</body>
</html>
Hope this makes sense. Thanks
Update :
Playerstatistics View:
class PlayerStatistics(DetailView):
context_object_name = 'PlayerStructure_details'
model = models.PlayerStructure
template_name = 'CricketDetails/playerstatistics_details.html'
Models
class PlayerStructure(models.Model):
clubstate = models.ForeignKey('Clubstate', on_delete=models.CASCADE, related_name='clubstate')
country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='identifier1')
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
imageUri = models.ImageField(upload_to='images/', verbose_name='image')
JerseyNumber = models.IntegerField()
BirthPlace = models.CharField(max_length=10)
BirthDate = models.CharField(max_length=30)
Role = models.CharField(max_length= 20)
BattingStyle = models.CharField(max_length= 20)
BowlingStyle = models.CharField(max_length= 20)
def __str__(self):
return self.firstname + self.lastname
I have pasted the html for this.
I have links (which are list of the countries) when I click (for example) "USA" I get list of the cities from other countries too. But I only want the list of the cities in the USA.
Here is my github link. You are welcome to clone and play with it.
https://github.com/ualmaz/post
I tried to filter that like this. queryset = Post.objects.all().values_list(
'city', flat=True).distinct()
But it did not work.
This is my views.py
def cities(request):
queryset = Post.objects.all().values_list(
'city', flat=True).distinct()
context = {
'cities': queryset
}
return render(request, 'users/cities.html', context)
my models.py
class User(AbstractUser):
first_name = models.CharField(verbose_name="First name", max_length=255)
last_name = models.CharField(verbose_name="First name", max_length=255)
country = models.CharField(verbose_name="Country name", max_length=255)
city = models.CharField(verbose_name="City name", max_length=255)
email = models.EmailField(verbose_name="Email", max_length=255)
def __str__(self):
return self.username
class Post(models.Model):
title = models.CharField(max_length=255)
country = models.CharField(max_length=255)
city = models.CharField(max_length=255)
address = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
phone = models.CharField(max_length=255)
website = models.URLField(max_length=255)
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('users:blog')
my countries.html (it contains countries list)
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% block content %}
<div class="content-section p-5 mt-5 pl-4">
<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<th>No: </th>
<th>Countries: </th>
</tr>
</tbody>
</table>
{% for post in posts %}
<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<td>{{ post.id }}</td>
<td>{{ post.country }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
</div>
This is my cities.html (This is where I am having the problem)
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% block content %}
<div class="content-section p-5 mt-5 pl-4">
<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<th style="width: 200px;">No: </th>
<th> Cities: </th>
</tr>
</tbody>
</table>
{% for city in cities %}
<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<td style="width: 200px;">{{ post.pk }}</td>
<td>{{ city }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
</div>
Your problem is that you are not filtering by the country that you clicked on. In your view, you should pass country in as a parameter. You can then do Post.objects.filter(country=country).values_list('city', flat=True).distinct(), which filters posts by country instead of getting all of the posts.
I'm trying to create an if else condition using jinja2 where only table row with the status pending_approval or scheduled will display a delete button beside it. But I'm having trouble figuring it out because all the data in the table is displayed in a for loop so if the condition is true and all row have the delete button and vice versa.
Any help is much appreciated
Below is my code :
model.py
class Leave(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+')
type = models.ForeignKey(LeavesType, on_delete=models.CASCADE, related_name='+')
status = (('cancelled', 'Cancelled'),
('taken', 'Taken'),
('pending_approval', 'Pending Approval'),
('scheduled', 'Scheduled'),
('weekend', 'Week End'),
('public_holiday', 'Public holiday'),
)
status = models.CharField(max_length=50, choices=status, default='pending_approval')
view.py
def my_leaves_view(request):
leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id)
context = {'leaves_log': leaves_log}
return render(request, 'hrm/employee/details/my_leaves.html', context)
html
<table id="Log" class="display table table-hover table-responsive leaves-table">
<thead>
<tr>
<th class="small text-muted text-uppercase"><strong>Leave Type</strong></th>
<th class="small text-muted text-uppercase"><strong>Status</strong></th>
<th class="small text-muted text-uppercase"><strong></strong></th>
</tr>
</thead>
<tbody>
{% for field in leaves_log %}
<tr>
<td>{{field.type}}</td>
<td><img class="media-object img-circle status-icon-size" src="/media/dashboard/ui/file_status/{{field.status}}.png" style="display: inline-block; height: 24px; margin-right: 10px;">{{field.status}}</td>
<td><div class="btn-group">
{% if field.status == 'pending_approval' or 'scheduled'%}
<button type="button" class="btn btn-default btn-xs dropdown-toggle active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right">
<li onclick="delete_leaves();">
<a href="/hrm/employee/{{field.id}}/delete/" onclick="return confirm('Are you sure you want to delete this item?');">
<i class="fa fa-fw fa-trash text-gray-lighter m-r-1"></i>Withdraw
</a>
</li>
</ul>
</div>
</td>
{% else %}
<td></td>
{% endif %}
</tr>
</tbody>
You are not using the or operator correctly. It is used to separate two boolean values, so you can imagine
{% if field.status == 'pending_approval' or 'scheduled' %}
being interpreted as
{% if bool(field.status == 'pending_approval') or bool('scheduled') %}
and bool('any non-empty string') is always True
The correct syntax is
{% if field.status == 'pending_approval' or field.status == 'scheduled' %}
or
{% if field.status in ['pending_approval', 'scheduled'] %}
I am attempting to filter for a single object, more specifically, today's entry. I then want to take that query and display the result within the template. No matter what I do I can't seem to get the filter to display anything in the template. I am not sure whether I need the query to be written within the view, the model, or both. My familiarity with Django querying is pretty light. A great resource on this topic would be extremely helpful as well.
I'm semi-new to Django, so any help you can provide would be much appreciated.
models.py
class Entry(models.Model):
date = models.DateField(blank=True, null=True,)
euros = models.CharField(max_length=500, blank=True, null=True)
comments = models.CharField(max_length=900, blank=True, null=True)
euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
def get_absolute_url(self):
return reverse('argent:detail', kwargs={'pk': self.pk})
views.py:
class IndexView(generic.ListView):
template_name = 'argent/index.html'
context_object_name = 'object_list'
queryset = Entry.objects.all()
filter = Entry.objects.filter(date=today_date)
print(filter)
class DetailView(generic.DetailView):
model = Entry
template_name = 'argent/detail.html'
class EntryCreate(CreateView):
form_class = EntryForm
template_name = 'argent/entry_form.html'
def form_valid(self, form):
return super(EntryCreate, self).form_valid(form)
class EntryUpdate(UpdateView):
model = Entry
form_class = EntryForm
template_name = 'argent/entry_form.html'
def form_valid(self, form):
return super(EntryUpdate, self).form_valid(form)
Note1: When I print "filter =" I get the correct object returned in the console.
Note2: I am using my "queryset =" further down my template and it works
perfectly fine.
template(index.html):
<div class="container" style="font-family: 'Dosis', serif;">
<div class="jumbotron" style="background: #ebebeb">
{% for Entry in filter %}
<h1>Today's Spending</h1>
<div class="container container-fluid" style="margin-left: 30px; margin-right: 30px; font-family: 'Dosis', serif; color: white;">
<div class="container container-fluid">
<table class="table">
<thead>
<tr>
<th colspan="2" style="font-size: large; color: #337ab7; font-weight: bold">{{ first.date }}</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left" style="color: #337ab7; font-weight: bold">Receipts:</td>
<td style="color: #FF6F18;"> {{ first.euros }} </td>
</tr>
<tr>
<td align="left" style="color: #337ab7; font-weight: bold">Total Euros Spent:</td>
<td style="color: #FF6F18;">€{{first.euros_sum}}</td>
</tr>
<tr>
<td align="left" style="color: #337ab7; font-weight: bold">Total Dollars Spent:</td>
<td style="color: #FF6F18;">${{first.dollars_sum}}</td>
</tr>
<tr>
<td align="left" style="color: #337ab7; font-weight: bold">Exchange Rate:</td>
<td style="color: #FF6F18;">{{ first.xrate }}</td>
</tr>
<tr>
<td align="left" style="color: #337ab7; font-weight: bold">Daily Savings:</td>
<td style="color: #FF6F18;">
{% if last.daily_savings_dollars > 0 %}
<div class="NegativeSavings" style="font-weight: bold">-
{% else %}
<div class="PositiveSavings" style="font-weight: bold">+
${{ first.daily_savings_dollars }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endfor %}
<div class="container container-fluid" style="font-family:'Dosis', serif">
<!-- Entry List -->
<div class="row" style="margin-left: 20px; margin-right: 20px">
<div>
 
</div>
{% if object_list %}
{% for Entry in object_list %}
<div class="col-sm-4 col-lg-3">
<div class="thumbnail" style="background: #ebebeb"; >
<a href="{% url 'argent:detail' Entry.id %}">
<h3 align="center" style="font-weight: bold">{{ Entry.date }}</h3>
</a>
<div class="caption">
<h4 align="center" style="color: #FF6F18">€{{ Entry.euros_sum }}
<!-- View Details -->
<a href="{% url 'argent:detail' Entry.id %}"><button type="button" class="btn btn-link btn-lg">
<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>
</button></a>
<!-- Update -->
<a href="{% url 'argent:entry-update' Entry.id %}"><button type="button" class="btn btn-link btn-lg" style="padding: 0%">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</button></a></h4>
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
</div>
Thanks in advance for your help!
You shouldn't do any db interaction at module level. You should override get_queryset (for what will be passed as object_list to the template) and get_context_data if you want additional stuff in your template context like the filtered queryset:
from django.utils import timezone
class IndexView(generic.ListView):
template_name = 'argent/index.html'
context_object_name = 'object_list'
def get_queryset(self):
return Entry.objects.all()
def get_context_data(self, **kwargs):
ctx = super(IndexView, self).get_context_data(**kwargs)
ctx['filter'] = Entry.objects.filter(date=timezone.datetime.today())
return ctx
The django documentation in general and its ListView section in particular are a good starting point. The django tutorial is worth completing, as well.
Modify your view to pass one of the querysets in as a context.
class IndexView(generic.ListView):
template_name = 'argent/index.html'
context_object_name = 'object_list'
#queryset = Entry.objects.all() use the get_queryset method to get this
#filter = Entry.objects.filter(date=today_date) add this using the get_context_data method
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'filter': Entry.objects.filter(date=today_date),
})
return context
def get_queryset(self):
return Entry.objects.all()