I'm very new to Django. I'm trying to add a CSS style to a table when
{% render_table table %}
is being run.
The code looks as following:
views.py:
def myTable(request):
table = myDataTable.objects.all()
filter = request.GET.get('q')
startDate = request.GET.get('sd')
endDate = request.GET.get('ed')
if mail:
table = table.filter(Q(filter__icontains=filter) &
Q(evaluation_date__range=[startDate, endDate])).distinct()
else:
table = table.filter(Q(evaluation_date__range=[startDate, endDate])).distinct()
table = TableView(table)
RequestConfig(request).configure(table)
return render(request, 'myapp/myTable.html', {'table': table})
tables.py:
class TableView(tables.Table):
class Meta:
model = myDataTable
template = 'django_tables2/bootstrap.html'
myApp.html
{% load staticfiles %}
{% load render_table from django_tables2 %}
....
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
....
<body>
{% render_table table %}
In project/static/css/ I have a custom style file customstyle.css, but there is no way to make the rendered table use that style.
Could you please help me?
I struggled to get the correct style for a table I was also rendering via:
{% render_table table %}
In your tables.py file you can do as follows to set attributes of the table itself (such as its' class):
class TableView(tables.Table):
class Meta:
attrs = {'class': 'table table-striped table-hover'}
Styling a table generated by django-tables2 is explained in the documentation. You can use the default class attributes, or specify custom ones.
In order to use your custom style sheet customstyle.css (using the classes mentioned above), you must include it into your template. django-tables2 doesn't do that for you, but you can learn how to do that from the django tutorial part 6:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
You have to adjust names and paths according to the location in your project.
Related
I am building a Django listing app. to use it, a template should looks like this :
{% load django_listing %}
<html>
<head>
...
{% include "django_listing/header.html" %}
...
</head>
<body>
...
{% render_listing data some_parameters %}
...
{% include "django_listing/footer.html" %}
</body>
</html>
This template is directly used in a TemplateView. It is important to know that the user can define all parameters in the template, the listing is created on-the-fly in the custom render_listing tag thus some_parameters is only known in template side (not known at TemplateView side). The user only gives the data in the TemplateView context.
I want to dynamically declare some CSS and JS depending on the some_parameters values. I succeded to do that for JS in {% include "django_listing/footer.html" %}, but not for CSS because when rendering {% include "django_listing/header.html" %} the listing object has not been created yet.
Do you have an idea how to dynamically declare some CSS depending on the some_parameters ?
May be there is a way to postpone {% include "django_listing/header.html" %} rendering ?
Finally, the solution was to create a template tag for the header that renders the remaining before itself :
class ListingHeaderNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
remaining_output = self.nodelist.render(context)
tpl = template.loader.get_template('django_listing/header.html')
tpl_output = tpl.render(context.flatten())
return f'{tpl_output}\n{remaining_output}'
#register.tag(name="render_listing_header")
def do_listing_header(parser, token):
nodelist = parser.parse()
return ListingHeaderNode(nodelist)
Then I can use it instead of the include :
{% load django_listing %}
<html>
<head>
...
{% render_listing_header %}
...
</head>
<body>
...
{% render_listing data some_parameters %}
...
{% render_listing_footer %}
</body>
</html>
For almost 5h I can't make detail view.
My app name -movies
My views:
"
def actor_view(request):
actor_list = Actor.objects.all()
context = {'actor_list': actor_list}
return render(request,'movies/actor.html',context)
def actor_detail_view(request,id):
actorrr=get_object_or_404(Actor,id=id)
context={
'actorrr':actorrr,
}
return render(request,"movies/actor_detail_view.html",context)
My model
class Actor(models.Model):
name = models.CharField(max_length=50)
date_of_birth = models.DateField()
age=models.IntegerField( null=True)
net_worth = models.TextField(max_length=140, null=True)
picture=models.URLField(default = '')
children =models.TextField(max_length=140, null=True)
marital_status=models.TextField(max_length=140, null=True)
My actor html:
{% load static %}
{% block mainbody %}
{% for actor in actor_list %}
<!DOCTYPE html>
<html>
<head>
<title>List of actors we have</title>
<link rel="stylesheet" href="{% static 'css/style_actor.css' %}">
</head>
<body>
<div class="card" >
<div class="card-image">
<img src="{{ actor.picture }}" alt="No poster in datebase" width="289" height="345">
</div>
<div class="card-text">
<h2>
{{ actor.name }}
</h2>
<p>{{movie.pilot}}</p>
</div>
<div class="card-imdb-score">
<p
>Age: {{ actor.age }}
</p>
</div>
</div>
</body>
</html>
{% endfor %}
{% endblock %}
My actor_detail html
<h6>TEST</h6>
movies url:
path('actor_detail_view/<int:id>',views.actor_detail_view,name='actor_detail_view'),
and the main url:
path('<int:id>/',views.actor_detail_view,name="actor_detail_view")
So I have no idea how to make urls and what to place in actor.html in href url.I've made many tutorials and still couldn't do it.
First of all, I recommends to you set the name of variable actorrr correctly.
If you're using Pycharm IDEA, the idea helps you to avoid problems with names of variables or spaces, following PEP08.
Some tips:
verify your urls.py file, to see if exists "/movies/actor_detail/{{actor.id }}
Probably, you have to add django template structure to appear the data of actor detail HTML, without for looping, because it's just one data.
your link to the actor detail page must be like this :
<a href={% url 'actor_detail_view' actor.id %}
also it's better to use django generic views to get detailed models.
I recommend you use CBVs, in this case, DetailView, I had same project and I put code here to use:
class DetailedActor(DetailView):
template_name = 'your_template'
model = models.YourModel
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
return context
then in your template, you have an instance of your model whit a specific actor! just don't forget to pass the id when you render to the URL assigned to this view
I want to create different templates, but both of them share almost the same attributes. For example, both the blog page and the movie page have the model 'Post' that allows users to add new Articles/Movies to the Website.
Also, I assume that the 'Movie - Post' model would need different fields than the 'Article - Post' model, but they still share many of them.
Someone can help me how to implement that out?
There are two possible ways to do this.
1. Make an outer file and insert all your code into the inner file. This uses extends.
The outer file, base.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
</head>
<body>
<p> You can also put anything else you want on every page here.</p>
<main role="main" class="container">
{% block content %}
{% endblock %}
</main>
</div>
</body>
</html>
The inner file, page.html
{% extends 'base.html' %}
{% block content %}
<p>This is the stuff you want to be unique to the page. </p>
{% endblock %}
The disadvantage of this method is that you are essentially putting one page inside another and it is a little less flexible.
2. Include the chunk of code inside an HTML file. This uses include.
The page you want to add the header to, page.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
</head>
<style>
body { padding-top: 70px;
font-family: Poppins;
}
</style>
<body>
{% include "header.html" %}
<main role="main" class="container">
<p> Whatever you want on your page</p>
</main>
</div>
</body>
</html>
The actual code for your header, header.html
<div class="header">
<p>My supercool header</p>
</div>
Include will insert that block of HTML code right where you put the include statement.
With regard to the models with common elements, you can do something like this:
from django.db import models
class CommonInfo(models.Model):
#common fields go here
post = models.CharField(max_length=100)
class Meta:
abstract = True
class Blog(CommonInfo):
#fields unique to blog go here
name = models.CharField(max_length=5)
class Movie(CommonInfo):
#fields unique to movie go here
name = models.CharField(max_length=5)
I have followed the official documentation of django tables 2 but it is not working I dont know why
views.py
from django.shortcuts import render
from django_tables2 import RequestConfig
from django.template.response import TemplateResponse
from .models import Customer
from .tables import CustomerTable
from .tables import TableView
from django_tables2.export.export import TableExport
def user_profile(request):
table= CustomerTable(Customer.objects.all())
RequestConfig(request,paginate={'per_page':15}).configure(table)
return render(request, 'home.html', {'table': table})
def TableView(request):
table = CustomerTable(Customer.objects.all())
RequestConfig(request).configure(table)
export_format = request.GET.get('_export', None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response('table.{}'.format(export_format))
return render(request, 'table.html', {
'table': table
})
my html template
{% extends 'base.html' %}
{% block content %}
{% load render_table from django_tables2 %}
{% load querystring from django_tables2 %}
<!doctype html>
<html>
<head>
<title>List of Customers</title>
</head>
<body>
{% querystring '_export'='csv' %}home
{% for format in table.export_formats %}
<a href="{% querystring '_export'=format %}">
download <code>.{{ format }}</code>
</a>
{% endfor %}
<p margin-bottom:500px;> </p>
<div style="width: 2500px; height: 600px; overflow-y: scroll;">
<div id ="users">
<input class="search" placeholder="Search" />
{% render_table table %}
{% endblock %}
</div>
</div>
</body>
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', user_profile, name="user_profile"),
url(r'^$', TableView, name="TableView"),
]
tables.py
import django_tables2 as tables
from .models import Customer
from django_tables2.export.views import ExportMixin
from .models import Customer
class CustomerTable(tables.Table):
class Meta:
model = Customer
template = 'django_tables2/bootstrap.html'
class TableView(ExportMixin, tables.SingleTableView):
table_class = CustomerTable
model = Customer
template_name = 'django_tables2/bootstrap.html'
I have a feeling something is wrong with the way I have defined urls.py but i cannot figure out what is wrong
There is a note in the documentation on exporting saying:
This example assumes you define a list of possible export formats on your table instance in attribute export_formats.
So you need to add the desired export formats to a list on your table like this:
class CustomerTable(tables.Table):
export_formats = ['csv', 'xls']
class Meta:
model = Customer
template = 'django_tables2/bootstrap.html'
You an also define the list in a context variable for your template, if you prefer that. There is no 'right' in this.
So I also banged my head against the wall a little bit on this, and then in a moment of clarity it hit me, you need wrap the query string tag like this in the template file
download as csv
I'm trying to make a query which orders the objects and then returns the first 100.
Orders.objects.order_by('date', 'time')[:100]
However I get this error.
Cannot reorder a query once a slice has been taken.
How would I make this query?
Edit:
Context
from django.shortcuts import render
from django_tables2 import RequestConfig
from .models import Order
from .tables import OrderTable
def order(request):
table = OrdersTable(Orders.objects.order_by('date', 'time')[:100])
RequestConfig(request).configure(table)
return render(request, 'view_orders/index.html', {'table': table})
# app/tables.py
import django_tables2 as tables
from .models import Order
class OrderTable(tables.Table):
class Meta:
model = Order
attrs = {'class': 'table', 'id': 'Order'}
Django-tables2 is giving this error, it needs to call order on the query however you are passing a already sliced list instead. A work around is explained in this reported issue. You can also use the render portion only as in example provided in doc:
from django.shortcuts import render
def people(request):
return render(request, 'people.html', {'people': Person.objects.all()})
for the template:
{# tutorial/templates/people.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" />
</head>
<body>
{% render_table people %}
</body>
</html>