Display data in a table only of the user logged in - python

Hello I want to display data of the user that is logged in form models into a table written in html
My views.py { I am displaying data from two different models in one table }
def managestugriev(request):
from_stugrievance = studentgriev.objects.all()
from_facgriev = facgrieve.objects.all()
return render(request,'manageGriev.html',
{"data_form_stu":from_stugrievance,"data_from_fac":from_facgriev})
template.html
<div>
<div>
<h2><center>Manage Your Grievances Here </h2>
<h3>Your Total Grievances: {{data|length}}</h3>
<h3></h3>
<table class="center">
<thead>
<tr text-align="justify">
<th>ID</th>
<th>Grievance</th>
<th>Date & Time</th>
<th>Status</th>
<th>Solution</th>
</tr>
</thead>
<tbody>
{% for i in data_form_stu %}
<tr text-align="justify">
<td padding:10px>{{forloop.counter}}</td>
<td>{{i.grievance}}</td>
<td>{{i.date_time}}</td>
<td>{{i.status}}</td>
{% for i in data_from_fac%}
<td>{{i.solution}}</td>
{% endfor %}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
models.py {Two models from which I am displaying the data}
class studentgriev(models.Model):
ch = (
("Solved","Solved"),("Pending","Pending"),("Not Solved","Not Solved")
)
name = models.CharField(max_length=30,default='',null=False)
contactnum = models.IntegerField(default='',null=False)
email = models.EmailField(max_length=50,default='',null=False)
grievance = models.TextField(default='',null=False)
date_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=100,choices=ch,default='')
def __str__(self):
return self.name + " "
class facgrieve(models.Model):
solution = models.TextField(default='',null=False)
def __str__(self):
return self.solution + " "
Please can anyone help !

Related

Django error value error: The view sub_categories.views.insert_sub_categories didn't return an HttpResponse object. It returned None instead

I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage
I also tried value = "{{c.category_name}}" as well in select dropdown as well
below are the models
class Categories(models.Model):
category_name = models.CharField(max_length=10)
category_description = models.CharField(max_length=10)
isactive = models.BooleanField(default=True)
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories,on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
show and insert function of sub_categories
def show_sub_categories(request):
showsubcategories = SUBCategories.objects.filter(isactive=True)
#print(showsubcategories)
serializer = SUBCategoriesSerializer(showsubcategories,many=True)
print(serializer.data)
return render(request,'polls/show_sub_categories.html',{"data":serializer.data})
def insert_sub_categories(request):
if request.method == "POST":
insertsubcategories = {}
insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name')
insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description')
form = SUBCategoriesSerializer(data=insertsubcategories)
if form.is_valid():
form.save()
print("hkjk",form.data)
messages.success(request,'Record Updated Successfully...!:)')
print(form.errors)
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
else:
insertsubcategories = {}
form = SUBCategoriesSerializer(data=insertsubcategories)
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict,many=True)
hm = {'context': category.data}
if form.is_valid():
print(form.errors)
return render(request,'polls/insert_sub_categories.html',hm)
html of the insert page and show page respectively
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
<tbody>
<tr>
<td><b>{{result.sub_categories_name}}</b></td>
<td><b>{{result.sub_categories_description}}</b></td>
<td style="position: relative;left:50px;">
<a href="sub_categories/edit_sub_categories/{{result.id}}">
<button class="btn btn-primary">
<i class="fa-solid fa-pen-to-square">EDIT</i>
</button>
</a>
</td>
<td>
<a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')">
<button class="btn btn-danger">
<i class="fa-solid fa-trash">DELETE</i>
</button>
</a>
</td>
</tr>
</tbody>
categories and sub categories serializer
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Categories
fields = "__all__"
extra_kwargs = {'category_name': {'required': False}}
class SUBCategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = SUBCategories
fields = "__all__"
where am I going wrong in the code?
Try this out and let me know, a few changes you'd require
def insert_sub_categories(request):
if request.method == "POST":
form = SUBCategoriesSerializer(data=request.POST)
if form.is_valid():
form.save()
messages.success(request, "Record Updated Successfully...!:)")
return redirect("sub_categories:show_sub_categories")
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict, many=True)
hm = {"context": category.data}
return render(request, "polls/insert_sub_categories.html", hm)
Form part
<form method="POST">
{% csrf_token %}
<table>
<thead>
<tr>
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>Active</td>
<td>
<input type="checkbox" name="isactive" value="true" checked>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
</tr>
</thead>
</table>
<button class="btn btn-success">Go To Home</button>
</form>
model
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.category_name.category_name
This error occurs because there is a chance in your function view, that it does not return proper Response or Redirect object. If you send POST request, but the form is not valid, then it will not return anything.
def insert_sub_categories(request):
if request.method == "POST":
...
if form.is_valid():
...
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
# HERE YOU MISS REDIRECT/RENDER
else:
...
return render(request,'polls/insert_sub_categories.html',hm)
Also you don't pass SUBCategories.category_name to your serializer. It's required field, so it will never be valid without it. You may try form = SUBCategoriesSerializer(request.POST) instead of adding values one by one.

Attempting to set related model fields via parent function call(s)

I am writing a Compact Disk Library editing routine. The application allows you to enter a CD Artist Name, and CD Title and the total time of the CD. User can then enter track information. While entering track information I want the application to display Current run time including this track, and time remaining based on length of the CD. The models and functions are below
class Cd(models.Model):
artist_name = models.CharField(max_length=155)
cd_title = models.CharField(max_length=155)
cd_total_time = models.TimeField(default="00:00:00")
cd_total_time_delta = models.DurationField(default=timedelta)
cd_run_time = models.TimeField(default="00:00:00",blank=True)
cd_run_time_delta = models.DurationField(default=timedelta)
cd_remaining_time = models.TimeField(default="00:00:00",blank=True)
cd_remaining_time_delta = models.DurationField(default=timedelta)
def convert_to_delta(self,time_in):
hold_time = time_in.strftime("%H:%M:%S")
t = datetime.strptime(hold_time,"%H:%M:%S")
return(timedelta(hours=t.hour, minutes=t.minute, seconds=t.second))
def calculate_time(self):
cd_total_time_delta = self.convert_to_delta(self.cd_total_time)
cd_total_run_time_delta = timedelta(minutes=0)
for track in self.cd_tracks.all():
cd_total_run_time_delta += track.trk_length_time_delta
track.trk_run_time_delta += cd_total_run_time_delta
track.trk_run_time = f"{track.trk_run_time_delta}"
track.trk_remaining_time_delta = cd_total_time_delta - cd_total_run_time_delta
track.trk_remaining_time = f"{track.trk_remaining_time_delta}"
self.cd_run_time_delta = cd_total_run_time_delta
self.cd_run_time = f"{self.cd_run_time_delta}"
self.cd_remaining_time_delta = self.cd_total_time_delta - cd_total_run_time_delta
self.cd_remaining_time = f"{abs(self.cd_remaining_time_delta)}"
def save(self, *args, **kwargs):
self.calculate_time()
super().save(*args,**kwargs)
def __str__(self):
return f"{self.artist_name} : {self.cd_title}"
class Track(models.Model):
cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE,
related_name='cd_tracks',
)
track_title = models.CharField(max_length=50)
track_number = models.IntegerField()
trk_length_time = models.TimeField(null=True,default=None, blank=True)
trk_length_time_delta = models.DurationField(default=timedelta)
trk_run_time = models.TimeField(default="00:00:00",blank=True)
trk_run_time_delta = models.DurationField(default=timedelta)
trk_remaining_time = models.TimeField(default="00:00:00",blank=True)
trk_remaining_time_delta = models.DurationField(default=timedelta)
def calculate_track_delta(self):
self.trk_length_time_delta = self.cd_id.convert_to_delta(self.trk_length_time)
def save(self, *args, **kwargs):
self.calculate_track_delta()
super().save(*args,**kwargs)
self.cd_id.save()
def __str__(self):
return f"{self.track_title}"
When I attempt to update a track by entering in the track length time, name etc. and pressing submit, it should calculate all of the track data for each track. It DOES calculate the CD Total run time and remaining time, but the track values do not get updated. I am thinking my code isn't actually referencing the actual object correctly? Or the parent is not saving the child data...(how would I write that?).
Thanks
This is what the actual Parent Update Form looks like:
The Run Time I entered manually via admin, to see if that helped (it didn't). The time remaining should be the total time minus run time (run time increases of course for each track).
below is the template itself:
{% extends 'base.html' %}
{% load static %}
{% block title %} Update CD {% endblock title %}
{% block content %}
<h1>CD Update </h1>
{% if submitted %}
<p>
Your CD information was submitted successfully. Thank You.
</p>
{% else %}
<form action="" method="post" novalidate>
<table>
{{ form.as_table }}
{% if not cd.cd_tracks.all %}
No Tracks Added
{% else %}
<TABLE BORDER="0" TABLE_LAYOUT="fixed" WIDTH="100%">
<TR BGCOLOR="#B0B0FF">
<TD></TD>
<TD ALIGN="Center"> Track #</TD>
<TD ALIGN="Center"> Cut Title</TD>
<TD ALIGN="Center">Track Length</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Run Time</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Time Remaining</TD>
</TR>
{% for tracks in cd.cd_tracks.all %}
<TR>
<TD ALIGN="Center" rowspan="1" height="33" width="33">
<!-- Turning Off anchor No mix view yet
<A href=" url 'cd_mixed_view' cd.pk tracks.pk ">
-->
<IMG SRC="{% static 'images/edit.gif' %}">
</A>
</TD>
<TD ALIGN="Left" VALIGN="Top" WIDTH="10"> {{ tracks.track_number }}</TD>
<TD ALIGN="Left" VALIGN="Top"> {{ tracks.track_title }}</TD>
<TD ALIGN="Left" VALIGN="Top">{{ tracks.trk_length_time|time:"H:i:s" }}</TD>
<TD ALIGN="Left" VALIGN="Top">{{ tracks.trk_run_time|time:"H:i:s" }}</TD>
{% if tracks.trk_remaining_time_delta < "00:00:00" %}
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> (-{{ tracks.trk_remaining_time|time:"H:i:s" }})</TD>
{% else %}
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> {{ tracks.trk_remaining_time|time:"H:i:s" }}</TD>
{% endif %}
</TR>
{% endfor %}
</TABLE>
{% endif %}
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
{% csrf_token %}
</form>
{% endif %}
{% endblock content %}
The code was close. The most major problem was I was not saving the child model in the parent correctly (or at all really).
Uddate model is :
class Cd(models.Model):
artist_name = models.CharField(max_length=155)
cd_title = models.CharField(max_length=155)
cd_total_time = models.TimeField(default="00:00:00")
cd_total_time_delta = models.DurationField(default=timedelta)
cd_run_time = models.TimeField(default="00:00:00",blank=True)
cd_run_time_delta = models.DurationField(default=timedelta)
cd_remaining_time = models.TimeField(default="00:00:00",blank=True)
cd_remaining_time_delta = models.DurationField(default=timedelta)
def convert_to_delta(self,time_in):
hold_time = time_in.strftime("%H:%M:%S")
t = datetime.strptime(hold_time,"%H:%M:%S")
return(timedelta(hours=t.hour, minutes=t.minute, seconds=t.second))
def calculate_time(self):
cd_total_time_delta = self.convert_to_delta(self.cd_total_time)
cd_total_run_time_delta = timedelta(minutes=0)
for track in self.cd_tracks.all():
cd_total_run_time_delta += track.trk_length_time_delta
track.trk_run_time_delta = cd_total_run_time_delta
track.trk_run_time = f"{track.trk_run_time_delta}"
track.trk_remaining_time_delta = cd_total_time_delta - cd_total_run_time_delta
track.trk_remaining_time = f"{abs(track.trk_remaining_time_delta)}"
super(Track,track).save()
self.cd_run_time_delta = cd_total_run_time_delta
self.cd_run_time = f"{self.cd_run_time_delta}"
self.cd_remaining_time_delta = self.cd_total_time_delta - cd_total_run_time_delta
self.cd_remaining_time = f"{abs(self.cd_remaining_time_delta)}"
def save(self, *args, **kwargs):
self.calculate_time()
super().save(*args,**kwargs)

User Ability to Search Django Database

I am looking to create a very simple form with several drop down fields allowing users to query a database of restaurants I have created (I would like to use the fields 'food', 'city' and 'average rating'). Whilst I have found an approach to do this using separate html pages (Django form to query database (models)) I would like to implement this on one page (restaurants.html).
I am using Python 3.1.0, Django 2.0.1 and Bootstrap 4.0.
Appreciate all your help.
My models.pyis as follows:
from django.db import models
import numpy as np
# Create your models here.
class Restaurant(models.Model):
name = models.CharField(max_length=100, null=False)
desc = models.CharField(max_length=100)
web = models.CharField(max_length=100)
phone = models.CharField(max_length=40)
address = models.CharField(max_length=100)
post_code = models.CharField(max_length=20)
picture = models.ImageField(upload_to='images/restaurants', null=True)
map = models.ImageField(upload_to='images/restaurants', null=True)
FOOD = ((1,'English'),
(2,'French'),
(3,'American'),
(4,'Indian'),
(5, 'Undefined'))
food = models.IntegerField(choices=FOOD, default=5)
CITY = ((1,'London'),
(2,'Paris'))
city = models.IntegerField(choices=CITY, default=1)
STARS = ((1,'One'),
(2,'Two'),
(3,'Three'),
(4,'Four'),)
CB_rating = models.IntegerField(choices=STARS, default=4)
def average_rating(self):
all_ratings = map(lambda x: x.rating, self.review_set.all())
return np.mean(all_ratings)
def __str__(self):
return self.name
views.py:
from django.shortcuts import get_object_or_404, render
from .models import Review, Restaurant
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .forms import ReviewForm
import datetime
def review_list(request):
latest_review_list = Review.objects.order_by('-pub_date')[:9]
context = {'latest_review_list':latest_review_list}
return render(request, 'review_list.html', context)
def review_detail(request, review_id):
review = get_object_or_404(Review, pk=review_id)
return render(request, 'review_detail.html', {'review': review})
def restaurant_list(request):
restaurant_list = Restaurant.objects.order_by('-name')
context = {'restaurant_list':restaurant_list}
return render(request, 'restaurants.html', context)
def restaurant_detail(request, restaurant_id):
restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
return render(request, 'restaurant_detail.html', 'restaurant':restaurant})
def user_review_list(request, username=None):
if not username:
username = request.user.username
latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
context = {'latest_review_list':latest_review_list, 'username':username}
return render(request, 'user_review_list.html', context)
restaurants.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Criteria</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<form method="get" action="/search/">
Search Restaurants:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Results</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
{% if restaurant_list %}
<div class="container">
<div class="table-responsive">
<table class="table table-bordered table-hover" style="text-align: center;">
<caption class="text-center">A list of restaurants based on your search criteria above.</caption>
<thead>
<th class="col-xs-2">Name</th>
<th class="col-xs-6">Description</th>
<th class="col-xs-1" style="text-align: center">Food Type</th>
</thead>
<tbody>
{% for restaurant in restaurant_list %}
<tr>
<td style="text-align: left;"><strong>{{ restaurant.name }}</strong></td>
<td style="text-align: left;">{{ restaurant.desc }}</td>
<td style="text-align: center;">{{ restaurant.food }}</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% else %}
<h3>No restaurants match your search criteria.</h3>
{% endif %}
</div>
</div>
</div>
{% endblock %}

can't add values from field into database Django

I would like to add data filled into database and output it. But i have no idea where is wrong because my data was't saved into database at all. In views.py, Scholarship is just one scholarship object, LScholarship is displaying all the data in Scholarship. I have similar code for other models and views but i have no idea what i did wrong in here, making the data can't be saved into database. Could anyone please advice me where am i wrong
add_remove_scholarship.html
<div align="center" >
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
<p>Upload File: {{scholarship.doc}} <input id="doc" type="text" name="doc"> </p>
<p>Faculty: {{scholarship.faculty}} <input id="faculty" type="text" name="faculty"> </p>
<p>Opening date: {{scholarship.openDate}} <input id="odate" type="date" name="openDate"> </p>
<p>Closing date: {{scholarship.closeDate}} <input id="edate" type="text" name="closeDate"> </p>
<input type="submit" name="AddScholarship" value="Add Scholarship" >
</form>
</div>
<br></br>
<button id="button" type="button">Delete Selected Scholarship</button>
<br></br>
<form method="POST" action="">
{% csrf_token %}
<table id="example" class="display" cellspacing="0" width="100%" border="1.5px">
<tr align="center">
<th> Scholarship </th>
<th> Faculty </th>
<th> Open Date </th>
<th> Close Date </th>
</tr>
{% for item in query_results %}
<tr align="center">
<td>{{item.doc}}</td>
<td>{{item.faculty}}</td>
<td>{{item.openDate}}</td>
<td>{{item.closeDate}}</td>
</tr>
{% endfor %}
</table>
</form>
models.py
#consists of all the details of the scholarship under the 'Add/Remove
Scholarship'
class Scholarship(models.Model):
doc = models.TextField("Doc", max_length=1000)
faculty = models.TextField("Faculty", max_length=1000)
openDate = models.DateField("Opening Date", max_length=8)
closeDate = models.TextField("CLosing Date", max_length=18)
def __str__(self):
return self.doc
#consists of all the details of the scholarship under the 'Add/Remove
Scholarship'
class LScholarship(models.Model):
scholarship = models.ForeignKey(Scholarship, on_delete=models.CASCADE)
views.py
def scholarship(request):
if request.method == "POST":
form = ScholarshipForm(request.POST)
if form.is_valid():
scholarship = form.save(commit=False)
scholarship.save()
else:
form = ScholarshipForm()
return render(request, 'hrfinance/add_remove_scholarship.html', {'form': form})
def lscholarship(request):
query_results = Scholarship.objects.all()
data={'query_results':query_results}
return render(request, 'hrfinance/add_remove_scholarship.html', data)
class ScholarshipForm(forms.ModelForm):
class Meta:
model = Scholarship
fields = '__all__'
You are using two views to render a single template.
You can merge your views into a single one and maybe reduce the logic.
If I have understood your problem correctly you could use your view more like this,
def scholarship(request, id=None):
query_results = []
if request.method == "POST":
form = ScholarshipForm(request.POST)
if form.is_valid():
scholarship = form.save(commit=False)
scholarship.save()
else:
form = ScholarshipForm()
id = request.GET.get('scholarship')
query_results = Scholarship.objects.all()
data = {
'query_results':query_results,
'form': form,
}
return render(request, 'hrfinance/add_remove_scholarship.html', data)
In your template,
<div align="center" >
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
<p>Upload File: {{ form.doc }}</p>
<p>Faculty: {{ form.faculty }} </p>
<p>Opening date: {{ form.startDate }} </p>
<p>Closing date: {{ closeDate }} </p>
<button type="submit" name="AddUser" value="Add Scholarship" onclick="add()" >Add Scholarship</button>
</form>
</div>
<table id="example" class="display" cellspacing="0" width="100%" border="1.5px">
<tr align="center">
<th> Scholarship </th>
<th> Faculty </th>
<th> Open Date </th>
<th> Close Date </th>
</tr>
{% for item in query_results %}
<tr align="center">
<td>{{item.doc}}</td>
<td>{{item.faculty}}</td>
<td>{{item.openDate}}</td>
<td>{{item.closeDate}}</td>
</tr>
{% endfor %}
</table>

How to print table using Jinja2 (without page refresh)

I use Pandas to get and transform some data from database and now I'd like to print the score dynamic, that is without page refresh. I've already tried: {{ mydata|safe}} and I get the whole information but everything is together not in table.
I use Pandas to create HTML table from dataframe mydata.to_html()) and I get something like that:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Part_number</th>
<th>Type_name</th>
<th>Short_desc</th>
<th>Price_1</th>
<th>Price_2</th>
<th>VAT</th>
<th>DB_source</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>565_MLNN7_101</td>
<td>AIR_FILTER</td>
<td>AIR_FILTER_GREEN</td>
<td>1.20</td>
<td>6.30</td>
<td>23%</td>
<td>Murexin</td>
</tr>
<tr>
<th>1</th>
<td>217_NE307_115</td>
<td>CABLE</td>
<td>CABLE_POWER_AC</td>
<td>0.84</td>
<td>3.20</td>
<td>23%</td>
<td>DB_1</td>
</tr>
</tr>
</tbody>
</table>
Do You know how print the table using Jinja2 ?
The jinja template that you need is something like this:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Part_number</th>
<th>Type_name</th>
<th>Short_desc</th>
<th>Price_1</th>
<th>Price_2</th>
<th>VAT</th>
<th>DB_source</th>
</tr>
</thead>
<tbody>
{% for row in mydata %}
<tr>
<th>{{loop.index0}}</th>
<td>{{row['Part_number']}}</td>
<td>{{row['Type_name']}}</td>
<td>{{row['Short_desc']}}</td>
<td>{{row['Price_1']}}</td>
<td>{{row['Price_2']}}</td>
<td>{{row['VAT']}}</td>
<td>{{row['DB_source']}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Check jinja2 documentation for more details
Sure
Here is my code for html template:
{% extends "header.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block content %}
<div class="container">
<form class="form-signin" method="POST" action="/search">
<div class="panel panel-default">
<div class="panel-heading">Service Part Inquiry</div>
<div class="panel-body">
{{ form.hidden_tag() }}
{{wtf.form_field(form.FGPN_Search)}}
{{wtf.form_field(form.AssyTypeName_Search)}}
{{wtf.form_field(form.Source_Search)}}
<button type="submit" class="btn btn-primary btn-xsy">Search</button>
</div>
</div>
</form>
</div> <!-- /container -->
{{data|safe}}
{% endblock %}
Code for function below. Actually I check condition only for "Source_Search": "Murexin", that why I deleted some codes (will be easier to understand for You :) I respect Your time):
#app.route('/search',methods=['GET', 'POST'])
def search():
form = SearchForm()
if request.method == 'POST':
FGPN_Search = form.FGPN_Search.data
AssyTypeName_Search = form.AssyTypeName_Search.data
Source_Search = form.Source_Search.data
(...)
elif Source_Search == 'Murexin':
if len(FGPN_Search)>1:
tablePLM=read_sql_query(select1 + "\'" + FGPN_Search + "\'" + select2 + "\'" + AssyTypeName_Search + "\'",CurDB_2)
tableSIC = read_sql_query(selectSIC + "\'" + FGPN_Search + "\'",CurDB_1)
mydata = pd.merge(tablePLM, tableSIC, on='PM_PARTNUMBER',how='outer')
mydata.to_html()
return render_template('search.html', form=form,data=mydata)
elif Source_Search == 'test':
return "<h1>test</h1>"
else:
flash("Please write anything.")
return render_template('search.html',form=form)
return render_template('search.html', form=form)

Categories

Resources