I m trying to request table_id from table_base.html and is not returning anything.
This my table_base.html
<div class="container">
<div class="jumbotron">
<h1> {{ table_name }} List</h1>
{% if list_tables %}
<table class="table table-bordered sortable">
<thead>
<th>Id</th>
<th>Name</a></th>
<th>Date</a></th>
<th>Search Button</th>
</thead>
{% for list in list_tables %}
<tr>
<td><a href="#" >{{ list.id }}</a></td>
<td>
{{ list.name }}
</td>
<td>{{ list.date }}</td>
<td>Search</td>
</tr>
{% endfor %}
</table>
{% else %}
<p> No Records Found</p>
{% endif %}
</div>
</div>
This is my tables/urls.py
urlpatterns = [
url(r'^$', views.table_base, name='tables'),
url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='details'),
url(r'^(?P<table_id>\d+)/details$', views.addview, name='addview')
]
This is my tables/views.py
def table_base(request):
table_name = Crawledtables._meta.db_table
list_tables = Crawledtables.objects.order_by('id')
return render(request, 'tables/table_base.html', {'table_name': table_name,
'list_tables': list_tables})
class AboutDetail(DetailView):
model = Crawledtables
pk_url_kwarg = 'table_id'
template_name = 'tables/table_list.html'
def __init__(self, **kwargs):
super(AboutDetail, self).__init__(**kwargs)
def get_object(self, **kwargs):
if 'table_id' not in self.kwargs:
return Crawledtables.objects.get(id=1)
else:
return Crawledtables.objects.get(id=self.kwargs['table_id'])
def addview(request, table_id):
q = request.GET.get('table_id')
print q
table_name = Crawledtables.objects.get(id=q)
print table_name
AllTables._meta.db_table = table_name.name
tbl_detail = AllTables.objects.order_by('id')
return render(request, 'tables/table_list.html', {'details': tbl_detail})
It works 1 time. When I select the first table (table with id 1) it gives me all the info. When I try to select another table it gives me this error:
InternalError: (1054, u"Unknown column 'table_name.id' in 'field list'")
I use print to print me everything. And it shows good response. But in the end it just hits me with error 1054. I can only see 1 table details at a time. If I want to see another table. I have to restart the server.
It seems that you don't run this command
python manage.py makemigrations <app_name>
python manage.py migrate
your table is not created yet
Related
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 !
I am new to Django and I am working on a project. In my project an admin will have the power to assign the project to a manager. So I want to render the name of all the managers from the database so that it will be displayed to the admin.
here is my .html file where I want to render the name of the manager in:
<div class="body table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>ASSIGN TEAM</th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<form id="form_id" method="POST" action = "{% url 'accept' %}">
{% csrf_token %}
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>
<select name="manager">
{% for manager in managers %}
<option value ="{{manager.id}}">{{manager.name}}</option>
{% endfor %}
</select>
<!-- </div> -->
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for manager:
class manager(models.Model):
name = models.CharField(max_length= 500)
designation = models.CharField(max_length= 500)
class Meta:
permissions = [
("edit_task", "can edit the task"),
]
def __str__(self):
return self.name
Here is my views.py;
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj})
In the admins page, I want to display all the names of the managers. I have added the image of the admin page.
I think you forgot to include the managers queryset in the context variable
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
managers = manager.objects.all()
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj, "managers": managers})
I'm trying to show user group permissions in Django and show them in a "Drupal" style like a matrix. It works, but it takes too long to make the query and paint it in the template. Is there some way to improve my code?
view img
up(accomplished),down(views and template.html)
views :
def GroupPermissionsView(request):
title = "Groups Permissions"
groups = Group.objects.all()
permissions = Permission.objects.all()
context = Context({
'title': title,
'groups': groups,
'permissions': permissions,
})
return render(
request,
'forms_permissions.html',
context
)
template:
<table class="table table-striped table-inverse table-responsive table-bordered">
<thead>
<tr>
<th>Permission</th>
{% for group in groups %}
<th>{{ group.name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for permission in permissions %}
<tr>
<td><b>{{permission.name}}<b></td>
{% for group in groups %}
{% if permission in group.permissions.all %}
<td><input type="checkbox" name="" checked="checked"></input></td>
{% else %}
<td><input type="checkbox" ></input></td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Your problem was that you run more than 4 * 200 queries, one query for every combination or rows and columns (permissions and groups). It is useful to get them all by one query. It is however not easy because the intermediate model of ManyToMany relationship between Permission and Group models is not explicit in django.contrib.auth.models. You can get that model by Model._meta API:
>>> GroupPermissions = Permission._meta.get_field('group').through
>>> GroupPermissions
<class 'django.contrib.auth.models.Group_permissions'>
>>> GroupPermissions._meta.db_table # the table that you use in the raw query
'auth_group_permissions'
Put it all together. Prefer a longer view and simple template:
update the view:
from collections import OrderedDict
GroupPermissions = Permission._meta.get_field('group').through
groups = Group.objects.all()
permissions = Permission.objects.all()
permission_group_set = set()
for x in GroupPermissions.objects.all():
permission_group_set.add((x.permission_id, x.group_id))
# row title and cells for every permission
permission_group_table = OrderedDict([
(permission, [(permission.id, group.id) in permission_group_set for group in groups])
for permission in permissions
])
context = Context({
'title': title,
'groups': groups,
'permission_group_table': permission_group_table,
})
update the template
{% for permission, cells in permission_group_table.items %}
<tr><td><b>{{permission.name}}<b></td>
{% for cell in cells %}
{% if cell %}
<td><input type="checkbox" name="" checked="checked"></input></td>
{% else %}
<td><input type="checkbox" ></input></td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
I hope this is possible.
Is there a way to pass back a returned element from a db query as an argument to a url_for?
It is being marked up by jinja template, but it is not a form element.
#app.route('/matcher/', methods=['GET', 'POST'])
def show_entries():
#global account_id
global load_file_id
if request.method == 'GET':
option = str(request.args.get('button'))
load_file_id = int(request.args.get('a'))
if option == 'All':
sql = """SELECT *
FROM TABLE WHERE LOAD_FILE_ID = :load_file_id"""
c = g.db.cursor()
c.execute(sql, load_file_id=load_file_id)
rows = c.fetchall()
for row in rows:
entries = [dict(title=row[0], text=row[1], text1=row[2], text2=row[3], text3=row[4], text4=row[5], text5=row[6], text6=row[7])]
media = row[8]
account_id = int(row[0])
c.execute("""UPDATE TABLE SET STATUS = 'PENDING' WHERE ACCOUNT_ID = :account_id""", account_id=account_id)
g.db.commit()
outs = mediapod(account_id)
return render_template('show_entries.html', entries=entries, media=media, outs=outs, src=src)
c.close()
elif:
############DOESN'T MATTER#############
and then
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
{% for entry in entries %}
<div class=entry>
<form action="{{ url_for('next') }}" method=get
class=validate>
<h2 name=id>{{ entry.title }}</h2>
<div class=subentry>
<div class=titles>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br></div>
<div class=elements>
${{ entry.text|string }}<br>
{{ entry.text1|string }}<br>
{{entry.text2|string }}<br>
{{ entry.text3|string }}<br>
{{ entry.text4|string }}<br>
{{ entry.text5|string }}<br>
{{ entry.text6|string }}<br></div>
<div class=mediatable>
<table>
<tr>
<th>Type</th>
<th>Date</th>
<th>Status</th>
<th>Doc ID</th>
<th>Scan Date</th>
</tr>
{% for put in outs %}
<tr>
<td>{{ put.media_type|safe }}</td>
<td>{{ put.statement_date|safe }}</td>
<td>{{ put.media_status|safe }}</td>
<td>{{ put.doc_id|safe }}</td>
<td>{{ put.scan_date|safe }}</td>
</tr>
{% endfor %}
</table>
</div>
<div class=buttons>
<input type=radio name=box value=match>Match
<input type=radio name=box value=nomatch>No Match
<input type=radio name=box value=fup>Follow-Up
<input type=radio name=box value=nomedia>No Media
<input type=submit class=next name=submit value=Next>
</div>
</div>
</form>
</div>
{% else %}
<em>stuff</em>
{% endfor %}
{% endif %}
{% endblock %}
and then I have a route after that that needs to take the account_id from show_entries()
#Next Button
#app.route('/next', methods=['GET'])
def next():
status = request.args.get('box')
c = g.db.cursor()
c.execute("""UPDATE TABLE
SET STATUS = :status
WHERE ACCOUNT_ID = :account_id""",
{"status" : str(status),
"account_id" : account_id
})
g.db.commit()
return redirect(url_for('nextnext'))
Take a peak back at the url_for docs:
It accepts the name of the function as first argument and a number of keyword arguments, each corresponding to the variable part of the URL rule.
url_for can be used in your Python source:
from flask import url_for
url_for('index')
and in your templates:
If you want your next method to receive a value as part of the URL, then you can change the method definition to
#app.route('/next/<int:account_id>', methods=['GET'])
def next(account_id):
# ...
then you can pass the variable through the url_for call, either from the Python source or from your templates:
url_for('next', account_id=account_id)
If you need your show_entries view to have that value in the template, then pass the value with the render_template call:
return render_template('show_entries.html', entries=entries, media=media, outs=outs, src=src, account_id=account_id)
I'd like to display a row with a label, a textfield and a checkbox for each item in a database. I've managed to do this except for the checkbox that's on a new line. I wan't:
<tr>
<td>Label</td>
<td>Input</td>
<td>Checkbox</td>
<tr>
But all I get is:
<tr>
<td>Label</td>
<td>Input</td>
</tr>
<tr>
<td>Checkbox</td>
</tr>
Anyone knows how to do this?
EDIT:
To generate the form I do:
forms.py
class AttributeForm(forms.Form):
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(AttributeForm, self).__init__(*args, **kwargs)
for key in extra:
self.fields[key] = forms.CharField(label=key, initial=extra[key], required=False)
self.fields['delete_'+key] = forms.BooleanField(label='', required=False)
views.py
attribute_form = AttributeForm(extra=user)
return render_to_response('user.html', {'username': username, 'attribute_form': attribute_form})
template (user.html)
<form action="" method="post">
<table>{{ attribute_form.as_table }}</table>
<input type="submit" value="Save attributes">
</form>
EDIT 2:
My template ended up like this:
<form action="" method="post">
<table>
<tr>
{% for field in attribute_form %}
{% cycle '<th>' '' %}{% cycle field.label_tag '' %}{% cycle '</th>' '' %}
<td>{{ field }}{{ attribute_form.field.errors }}</td>
{% if not forloop.last %}{% cycle '' '</tr><tr>' %}{% endif %}
{% endfor %}
</tr>
</table>
<input type="submit" value="Save attributes">
</form>
.as_table renders each form field in seperate table row. You should render the form manually.