I have modeled my database using models.py within my django project, one of the fields is a JSONField and I can save json data into that field without any problem. My doubt comes in how I can show that information as an html table. At the moment I have been using ListView to show that information in a template but I don't know how to transform it into a table.
If you use object.json_field.items you can loop through them just like a normal dictonary / can also use .keys and .values
Example use in a table
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for k, v in object.json_field.items %}
<tr>
<th>{{k}}</th>
<th>{{v}}</th>
</tr>
{% endfor %}
</tbody>
</table>
Related
I am doing an ecommerce project for deployment in pythonanywhere.com, some error is coming
I would really appreciate if any one could help me to find out the problem as I am a basic learner
TIA
I have developed a online book store application with python and django,I have two MySQL tables for category and products , while running in local host it works perfectly, but the deployment in pythonanywhere only got problem in images field, also static path given
errorenter image description here
enter image description here
Need to Check image is not None with if condition
<table>
<thead>
<tr>
<th>First Name</th>
<th>last Name</th>
<th>Mobile</th>
<th>E-Mail</th>
<th>City</th>
</tr>
</thead>
<tbody>
{% for i in data %}
<tr>
<td>
{% if i.image %} # need to check image is not None, this if check if image then render it else not
{{i.image.url}}
{% endif %}
</td>
<td>{{i.first_name}}</td>
<td>{{i.lastname}}</td>
<td>{{i.mobile}}</td>
<td>{{i.email}}</td>
<td>{{i.city}}</td>
</tr>
{% endfor %}
</tbody>
</table>
I found that the problem was any of the image field was none, so I checked from the admin panel all the records and got one row with image attribute empty. So after adding image it works perfectly.
I have data in the following (simplified) format:
MetricData(models.Model) with following fields: id, metric, date, facility, value
Now I want to create a table with the following format (execute the script to get the indented output table):
<table style="width:100%">
<tr>
<th>Date</th>
<th>Facility 1</th>
<th>Facility 2</th>
<th>Facility 3</th>
</tr>
<tr>
<td>03/2019</td>
<td>1.0</td>
<td>1.5</td>
<td>2.5</td>
</tr>
<tr>
<td>04/2019</td>
<td>1.5</td>
<td>1.5</td>
<td>2.0</td>
</tr>
</table>
As you can see, the number of facilities which is dynamic (new ones can be added to the database), are the column headers. For each facility there will be metric data in the database.
All examples from django-datatables-view I find are basically using models directly and one model entry is converted to one table row.
You can override the QuerySet for your model to get a list of headers:
class MetricDataQuerySet(models.QuerySet):
#property
def headers(self):
return [getattr(instance, self.model.header_column) for instance in self]
class MetricData(models.Model):
header_column = 'facility'
...
objects = MetricDataQuerySet.as_manager()
Notice I added the header_column, instead of hard coding facility in the QuerySet. This allows you to reuse the QuerySet for different models if you end up needing to.
Now, in your view:
def some_view(request):
...
context = {
'objects': MetricData.objects.all()
}
return render(request, 'some_template.html', context)
Finally, on some_template.html, you can do this:
<table>
<tr>
{% for header in objects.headers %}
<th>{{ header }}</th>
{% endfor %}
</tr>
{% for object in objects %}
<tr>
<td>row.date</td>
<td>row.metric</td>
<td>row.value</td>
</tr>
{% endfor %}
</table>
There is a char field named json_field in Django Model. I am trying to iterate it from the view but it returns only one result as the return statement does. I am trying to figure it out how I can iterate json_field using yield.
the result that Model Object returns like:
id : 1
title : "Some Title"
json_field : [{"key":"value","key2":"value2"},{"key":"value","key2":"value2"}]
created : "Sat Oct 21 2017 14:00:53 GMT+0300 (+03)"
view.py
import json
def MyView(request):
model_query = MyModel.objects.all() or MyModel.objects.filter or exclude...
for item in model_query:
data_item = json.loads(item.json_field)
template = "template.html"
context = {"title":title, "data_item":data_item}
return render(request, template, context)
in template.html
{% for query_item in model_query %}
<table>
<thead>
<tr>
<th>{{ query_item.title }} - {{ query_item.created }}</th>
</tr>
</thead>
<tbody>
<tr>
<th>Some Heading </th>
<th>Some Heading </th>
</tr>
<!-- json data -->
{% for item in data_item %}
<tr>
<th>{{ item.key }}</th>
<td>{{ item.key2|floatformat:2 }}</td>
</tr>
{% endfor %}
<!-- json data -->
</thead>
</table><
{% endfor %}
Any help will be appreciated.
You can prepare dataset for you template.
# Fetch data from db as queryset of dicts
items = list(MyModel.objects.filter().values('title', 'created', 'json_field'))
# Decode json in-place
for item in items:
item['json_field'] = json.loads(item['json_field'])
context = {"title":title, "items": items}
Then interate through items inside your template:
{% for item in items %}
<table>
<thead>
<tr>
<th>{{ item.title }} - {{ item.created }}</th>
</tr>
</thead>
<tbody>
<tr>
<th>Some Heading </th>
<th>Some Heading </th>
</tr>
<!-- json data -->
{% for entry in item.json_field %}
<tr>
<th>{{ entry.key }}</th>
<td>{{ entry.key2|floatformat:2 }}</td>
</tr>
{% endfor %}
<!-- json data -->
</thead>
</table><
{% endfor %}
If you're using PostgreSQL, you can using JSONField. It uses the postgres's jsonb type, which is optimized for keeping a json serializable text.
If not, you still can use django-jsonfield. It almost gives the same functionality, even though some of the cool features of django's JSONField are not available (like this kind of lookups).
If none of these work for you, you can also implement your own JSONField by inheriting from CharField or TextField, and overriding some of the functions. This way, you won't need any of the logics of your field in your views.
Edit:
If you find changing your field hard or don't wanna do it for whatever reason, you can do this in your view:
for item in model_query:
item.loaded_json = json.loads(item.json_field)
then you can use it like a normal field in your template:
{% for query_item in model_query %}
{% for item in query_item.loaded_json %}
<span>{{ item.key }}</spam>
{% endfor %}
{% endfor %}
Hello!
The solution depends on your purposes.
Use comprehensions if you want to construct a list of json arrays:
data_items = [json.loads(item.json_field) for item in model_query]
... or generator of json array:
data_items = (json.loads(item.json_field) for item in model_query)
If you want to have a single array of json objects try this:
data_items = []
for item in model_query:
data_items.extend(json.loads(item.json_field))
Then you can use data_items as a template context.
A little tip: You can utilize JSONField at ORM level if you use PostgreSQL or MySQL. Consider this approach if you plan to make any filter queries on this field. As additional benefit JSON encoding/decoding will be out of box.
Thanks for updating your code!
Now I would restructure the json.load() list of dicts so you can use it. That is better style than mangling in the template.
concatenation is done by:
my_dict = dict()
for d in data_item
my_dict.update( d )
if you want to merge, check this thread:
How to merge two dictionaries in a single expression?
I just want to write a table in HTML in Django, where the data is not from Database. It seems django-tables2 is a good package that I can use in Django. However, my data is not from Database, so maybe it's not necessary to use Django model. Here comes my code of view.py and HTML page:
def device_manager_submit(request):
'''Switch manager page'''
ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
return HttpResponse(ret) #return data to HTML
I can use for loop in HTML to display this data but I'm not clearly about how to show them:
<tbody>
{% for item in xx %} //I'm not sure
<tr>
<td>111</td> //how to display?
</tr>
{% endfor %}
Does anyone has any example that I can follow to display the data from view.py in HTML page
You don't need to return Django objects to create templates, you can use any data. The render() function allows you to combine context with the regular HttpResponse. You pass it the request which was given to the view calling it, the name of the template you want to render, and then a dictionary of data to provide to the template.
def device_manager_submit(request):
'''Switch manager page'''
ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
return render(request, 'some_template.html', {'devices': ret}) #return data to HTML
Assuming that ret contains some objects with a name and description, we can loop through devices like so:
<tbody>
{% for device in devices %}
<tr>
<td>{{ device.name }}</td>
<td>{{ device.description }}</td>
</tr>
{% endfor %}
One way would be to use pandas to load the data, and then use the DataFrame.to_html() to output the data into an html table. See the example below:
import pandas as pd
data = [{'column1': 1, 'column2': 2}]
df = pd.DataFrame(data)
html = df.to_html()
Html will result in:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>column1</th>
<th>column2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
In a Django view this would be:
#api_view(['GET'])
def showData(request):
data = [{'column1': 1, 'column2': 2}]
df = pd.DataFrame(data)
html = df.to_html()
return HttpResponse(html)
Goal: {% for loop %} over a list (using Jinja2) and then print out results {{print}} in a HTML table using Bootstrap.
Problem: List is not printing in the template.
In the view_config, I used query .all() to return a list of all the assessment_results objects. They are returning... I confirmed this via terminal/print debugging. However, the for loop is not returning the values needed to populate a table; as read in Jinja2 tutorial. I don't think I need to use a for loop in the view_config as I have seen others do (see here), but I am new to this and am trying to figure out how these two programs (SQLALCHEMY and Jinja2) interact.
An example from the printout after using .all() mentioned above:
[<Assessment_Result(owner='<User(username ='baseball', firstname ='Jen', lastname ='See', email='girl#aol.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>]
view_config code:
views.py
#view_config(route_name='assessment_results', request_method='GET', renderer='templates/assessment_results.jinja2')
def all_assessment_results(request):
with transaction.manager: # < --- THIS WAS THE ISSUE !
assessment_results = api.retrieve_assessment_results()
if not assessment_results:
raise HTTPNotFound()
return {'assessment_results': assessment_results}
Corresponding Jinja2 template using Bootstrap:
assessment_results.jinja2
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<td> Assessment ID </td>
<td> Assessment </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<tr>
{% for x in assessment_results %}
<td>{{ x.assessments|e }}</td>
<td>{{ x.owners|e}}</td>
{% else %}
<td><em>no users found</em></td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
You should look at the documentation
http://jinja.pocoo.org/docs/dev/templates/#for
You want to iterate over a dict, so consider using iteritems, itervalues or what ever you want.
Also note that your query will not return a dict, it will return a list or rows that matched.
I am also not sure if the for-else works in jinja. But you should avoid using that anyways.