Django Class Based Views and Queries - python

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>
&nbsp
</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()

Related

i need to show some data in table but those data's are not in a same table ,how to show that data in one table in django

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>

Django Form POST problem in a Bootstrap Modal

I'm searching for this issue for days... And, unfortunately, couldn't find the answer.
I have a view (Buildings) and I want to add/edit a Building with a modal. With my current code, I can add new Building. However, because I can't pass the id (pk) of an existing Building, I can't update it.
I've two views: one for the table, other for the form. I noticed that, when I POST, my Building view posts, not the newBuilding view.
I tried to get pk from kwargs in newBuilding view, but I can't get it in the post method.
The only thing left is to update..
Let me share my code.
Thanks in advance!
urls.py
path('app/buildings/', login_required(views.Buildings.as_view()), name='buildings'),
path('app/buildings/<int:pk>', login_required(views.NewBuilding.as_view()), name='buildings-pk'),
models.py
class Buildings(TemplateView):
template_name = 'main_app/buildings.html'
model = models.Building
def get_context_data(self, **kwargs):
context = super(Buildings, self).get_context_data(**kwargs)
# Get selected site from cache
active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = active_site
filtered_buildings = models.Building.objects
context['buildings'] = filtered_buildings.all()
return context
def get_form_kwargs(self):
kwargs = super(Buildings, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'), 'edited_building_id': None})
return kwargs
def post(self, request, *args, **kwargs):
if request.method == 'POST':
NewBuilding.post(self, request=request, slug=None)
return HttpResponseRedirect(reverse_lazy('main_app:buildings'))
else:
print("error")
...
class NewBuilding(FormView):
template_name = 'main_app/new/new_building.html'
form_class = forms.NewBuildingForm
active_site = None
def get_context_data(self, **kwargs):
context = super(NewBuilding, self).get_context_data(**kwargs)
# Get selected site from cache
self.active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = self.active_site
context['edited_building_id'] = self.kwargs['pk']
return context
def get_form_kwargs(self):
kwargs = super(NewBuilding, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'),
'edited_building_id': self.kwargs['pk']})
return kwargs
def post(self, request, slug=None, *args, **kwargs):
if request.method == 'POST':
# HERE, I need to assign the building to be edited.
# if kwargs['edited_building_id']:
# new_building = models.Building.objects.get(id=self.kwargs['edited_building'])
# else:
new_building = models.Building()
new_building.site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
if new_building.name != request.POST.get('name'):
new_building.name = request.POST.get('name')
if new_building.address != request.POST.get('address'):
new_building.address = request.POST.get('address')
new_building.save()
else:
print("error")
buildings.html
<div class="portlet box blue">
<div class="portlet-title">
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
</div>
</div>
<div class="portlet-body">
<div class="table-toolbar">
<div class="row">
<div class="col-md-12">
<div class="btn-group pull-right">
<button id="sample_editable_1_new" class="btn green" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=0%}">
Add New <i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
{# modal for new and edited entry#}
<div id="full-width" class="modal container fade" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Add Building</h4>
</div>
<div class="modal-body">
{# modal body#}
</div>
</div>
<table class="table table-striped table-hover table-bordered" id="sample_editable_1">
<thead>
<tr>
<th class="text-center">
Name
</th>
<th class="text-center">
Address
</th>
<th class="text-center">
Type
</th>
<th class="text-center">
Edit
</th>
</tr>
</thead>
<tbody>
{% for building in buildings %}
<tr>
<td>
{{ building.name }}
</td>
<td>
{{ building.address }}
</td>
<td>
{{ building.type | default_if_none:"-" }}
</td>
<td>
<a class="edit" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=building.id%}">
Edit </a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
new_building.html
<form class="form-horizontal" method="POST">
{% csrf_token %}
<div class="form-body">
<div class="form-group last">
<label class="col-md-3 control-label">Site</label>
<div class="col-md-4">
<span class="form-control-static">{{ active_site.name }}</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-4">
{{ form.name }}
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn blue">Submit</button>
<button type="button" class="btn default" data-dismiss="modal">Cancel</button>
</div>
</form>
forms.py
class NewBuildingForm(forms.ModelForm):
active_site = None
edited_building_id = 0
class Meta:
model = models.Building
fields = ["name", "address", "type", "site", "public_area",
"electricity_utility_meter", "water_utility_meter", "gas_utility_meter", "hot_water_utility_meter"]
def __init__(self, *args, **kwargs):
self.active_site = kwargs.pop('active_site')
self.edited_building_id = kwargs.pop('edited_building_id')
super(NewBuildingForm, self).__init__(*args, **kwargs)
edited_building = models.Building.objects.filter(id=self.edited_building_id)
self.fields['name'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control input-circle'}))
self.fields['address'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control input-circle'}),
required=False)
if edited_building:
self.fields['name'].initial = edited_building.get().name
self.fields['address'].initial = edited_building.get().address
I try to update kwargs on FormView (because I can get edited_building_id there), but I can't access kwargs on POST https://imgur.com/G7UcmLo

I want to filter the clients of every agent individually. Django

I'm creating a view where I can show all the clients of specific agents via there PK.
I am not having error when I use Client.objects.all() as the queryset and it gets to show all of the clients. however I don't know how to filter clients via select pk for Url.
Please help.
Here's my Views.py
class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
template_name = "agents/agent_client_list.html"
context_object_name ="clients"
def get_queryset(self):
user= Agent.objects.get(pk=id)
queryset = Client.objects.filter(user=user, agent__isnull=False).order_by('company_name')
return queryset
My Urls.py:
from django.urls import path
from .views import AgentListView, AgentCreateView, AgentDetailView, AgentUpdateView, AgentDeleteView, AgentClientListView
app_name = 'agents'
urlpatterns = [
path('', AgentListView.as_view(), name='agent-list'),
path('<int:pk>/', AgentDetailView.as_view(), name='agent-detail'),
path('<int:pk>/update/', AgentUpdateView.as_view(), name='agent-update'),
path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'),
path('<int:pk>/agent_client_list', AgentClientListView.as_view(), name='agent_client_list'),
path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'),
path('create/', AgentCreateView.as_view(), name='agent-create'),
]
Here's the Client Model
class Client(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=20)
mobile_number = models.CharField(max_length=12)
email = models.EmailField(null=True, blank=True)
organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE)
agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL)
category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL)
company_name = models.CharField(max_length=50 , default=None)
street_address = models.CharField(max_length=50 , default=None)
baranggay = models.CharField(max_length=50 , default=None)
city = models.CharField(max_length=50 , default=None)
region = models.CharField(max_length=50 , default=None)
date_added = models.DateTimeField(auto_now_add=True)
phoned = models.BooleanField(default=False)
special_files = models.FileField(blank=True , null=True)
def __str__(self):
return self.company_name
And HTML:
{% extends "base.html" %}
{% block content %}
<section class="text-gray-600 body-font overflow-hidden">
<div class="container px-5 py-24 mx-auto">
<div class="lg:w-4/5 mx-auto flex flex-wrap">
<div class="lg:w-1/2 w-full mx-auto">
<h2 class="text-sm title-font text-gray-500 tracking-widest">AGENT</h2>
<h1 class="text-gray-900 text-3xl title-font font-medium mb-4">{{ agent.user.first_name }} {{ agent.user.last_name }}</h1>
<div class="flex mb-4">
<a href="#" class="flex-grow text-blue-500 border-b-2 border-blue-500 py-2 text-lg px-1">
Description
</a>
</a>
<a href="#" class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1">
Update
</a>
</div>
<div class="flex flex-col w-full">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">Client Name</th>
<th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Point Person</th>
<th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Date Added</th>
<th class="text-2xl px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Client Status</th>
</thead>
{% for client in clients %}
<tbody>
<tr>
<div>
<td class="mt-3">{{ client.company_name }}</td>
<td class="mt-3">{{ client.first_name }} {{ client.last_name }}</td>
<td class="mt-3">{{ client.date_added }}</td>
<td class="mt-3 px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> {{ client.category }}</td>
</div>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock content %}
However I get this error:
TypeError at /agents/7/agent_client_list
Field 'id' expected a number but got <built-in function id>.
Request Method: GET
Request URL: https://techcrm.herokuapp.com/agents/7/agent_client_list
Django Version: 3.1.4
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got <built-in function id>.
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/models/fields/__init__.py, line 1776, in get_prep_value
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.9.2
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python39.zip',
'/app/.heroku/python/lib/python3.9',
'/app/.heroku/python/lib/python3.9/lib-dynload',
'/app/.heroku/python/lib/python3.9/site-packages']
Server time: Mon, 31 May 2021 15:22:53 +0800
Thank you very much in advance!
You can not use id in the get_queryset, since this refers to the builtin id function, not the primary key of the object.
You can obtain the URL parameters with self.kwargs:
class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
template_name = 'agents/agent_client_list.html'
context_object_name ='clients'
def get_queryset(self):
agent = Agent.objects.get(pk=self.kwargs['pk'])
return Client.objects.filter(agent=agent, agent__isnull=False).order_by('company_name')
It might be better to directly filter on the primary key however, and thus work with one query instead of two:
class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView):
template_name = 'agents/agent_client_list.html'
context_object_name ='clients'
def get_queryset(self):
return Client.objects.filter(agent_id=self.kwargs['pk'], agent__isnull=False).order_by('company_name')

NoReverseMatch at / | Error during template rendering

Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[^/]+)/$']
This is the error,
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[^/]+)/$']
Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.5
Python Path:
['C:\Users\user\Downloads\Git Project\firstwebsite',
'C:\Users\user\AppData\Local\Programs\Python\Python39\python39.zip',
'C:\Users\user\AppData\Local\Programs\Python\Python39\DLLs',
'C:\Users\user\AppData\Local\Programs\Python\Python39\lib',
'C:\Users\user\AppData\Local\Programs\Python\Python39',
'C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages']
Server time: Wed, 09 Jun 2021 06:20:15 +0000
This is code
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.dashboard, name="dashboard"),
path('customer/<str:pk>/', views.customer, name="customer"),
path('product/', views.product, name="product"),
]
this is models.py
from django.db import models
# Create your models here.
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.FloatField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY = (
('Indoor', 'Indoor'),
('Outdoor', 'Outdoor')
)
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
tag = models.ManyToManyField(Tag)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
#we create a dropbox like this
STATUS = (
('Pending', 'Pending'),
('Out Of Deliery', 'Out Of Delivery'),
('Deliverder', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
date_crated = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200,null=True, choices=STATUS)
def __str__(self):
return self.status
This is views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Customer, Order, Product
# Create your views here.
def dashboard(request):
customer = Customer.objects.all()
orders = Order.objects.all()
total_customer = customer.count()
total_orders = orders.count()
delivered = orders.filter(status='delivered').count()
pending = orders.filter(status='pending').count()
context = {'orders':orders, 'total_orders':total_orders, 'total_customer':total_customer, 'pending':pending,'delivered':delivered, 'customer':customer}
return render(request, "accounts/dashboard.html", context)
def product(request):
products = Product.objects.all()
return render(request,'accounts/products.html' ,{'products':products})
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.order_set.all()
order_count = orders.count()
context = {'customer':customer, 'orders':orders, 'order_count':order_count}
return render(request, 'accounte/contact.html', context)
Templates Dashboard.html (html file)
{% extends 'accounts/main.html' %}
{% block content %}
{% load static %}
<div class="center" style="display: block; margin-left: auto; margin-right: auto; width: 50%; ">
<img src="{% static 'images/welcome.png' %}" class="img-fluid" alt="">
</div>
<br>
<br>
<br>
<br>
<div class=" justify-content-center" style="padding: 20; width: 60%; margin-right: auto; margin-left: auto;">
<h1 class="display-1 " style="text-align: center; font-style: italic;">This is my first website</h1>
<div style="padding-top: 50;">
<img src="{% static 'images/186.png' %}" alt="" style="display: block; margin-left: auto; margin-right: auto; width: 50%; ">
</div>
</div>
<br>
<div class="row">
<div class="col-md-5">
<h5>Customers</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm-btn-block" href="">Create Customers</a>
<table class="table table-sm">
<tr>
<th>Customers: </th>
<th>Phone no: </th>
</tr>
{% for customers in customer %}
<tr>
<th><a class="btn btn-sm btn-info" href="{% url 'customer' customer.id %}">view</a></th>
<td>{{customers.name}}</td>
<td>{{customers.phone}} </td>
</tr>
{% endfor %}
</table>
</div>
</div>
<div class="col-md-7">
<h5>Last 5 orders</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm btn-block" href="">Create Orders</a>
<table class="table table-sm">
<tr>
<th>Product</th>
<th>category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for i in orders %}
<tr>
<td>{{i.product}} </td>
<td>{{i.product.category}} </td>
<td>{{i.date_crated}} </td>
<td>{{ i.status }} </td>
<td>Update</td>
<td>Delete</td>
</tr>
{% endfor %}
</table>
</div>
</div>
{% include 'accounts/status.html' %}
</div>
{% endblock %}**
idk why I am getting error. Help me out!

Python/Django displaying images

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)

Categories