Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
who to get (" placeholder ") attribute of input tag using POST request?
I want to get my placeholder attr, when user submit the form. I want the placeholder data. how can it be possible in django framework? -
How to implement multiple forms for one template
I'm new to Django. I have multiple forms for different calculations (etc Form1, Form2, Form3, ...) on my blog page. Each blog post (post/1) will have a button at the page with a link to open specific form template (post_form.html) for that post (e.g. post/1/form/) with a form in it. (Post1 - Form1, Post2 - Form 2, etc..) Could someone help with the logic of implementation of this? How to better set up urls, models and forms? models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category , on_delete=models.CASCADE, default='Concrete') author = models.ForeignKey(User , on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='calc_pics') formId = models.IntegerField() class L_section_prop_calc(models.Model): name = models.CharField(max_length=100, unique=True) tf = models.DecimalField(max_digits=5, decimal_places=3) tw = models.DecimalField(max_digits=5, decimal_places=3) height = models.DecimalField(max_digits=5, decimal_places=3) urls.py path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), forms.py class Calc_L_Section_Prop_Form(forms.ModelForm): class Meta: model = L_section_prop_calc fields = ['tw','tf','height'] I'm do not know if I need to create a model for each form. Is there a better way? Thx -
TypeError: unsupported type for timedelta seconds component: list
I am setting up a CAS(Central Authentication Server) via https://github.com/jbittel/django-mama-cas and getting an error when it tries to create the ticket due to stderr: TypeError: unsupported type for timedelta seconds component: list I've searched on how to convert a django model object value to integer for timedelta() function with no luck on figuring it out myself. def create_ticket(self, ticket=None, **kwargs): """ Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``. """ if not ticket: ticket = self.create_ticket_str() if 'service' in kwargs: kwargs['service'] = clean_service_url(kwargs['service']) if 'expires' not in kwargs: expires = now() + timedelta(seconds=self.model.TICKET_EXPIRE) kwargs['expires'] = expires t = self.create(ticket=ticket, **kwargs) logger.debug("Created %s %s" % (t.name, t.ticket)) return t Expected results: CAS logs me in and redirects me back to CAS enabled app. Actual Results: Internal Server Error (500) App 29175 stderr: [ pid=29175, time=2019-10-03 19:08:25,610 ]: Internal Server Error: /login App 29175 stderr: Traceback (most recent call last): App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner App 29175 stderr: response = get_response(request) App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response App 29175 stderr: response = self.process_exception_by_middleware(e, request) App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response App 29175 stderr: … -
How to return result celery to template django
I've a task that have many querys in my database, some consults require time > 30s , and my server heroku , can't. I would like to query and return to template. my code View: `` ` class sales_filter(LoginRequiredMixin, View): def get(self, request): data = {} task = searching.delay() return render(request, 'sales/sales_filter.html', data) `` ` Task: `` ` @shared_task def searching(): data['cod_parceiros'] = mapa.objects.values('cod_parceiro').distinct().\ filter(mes_referencia__icontains=ano).order_by('cod_parceiro') return render(request, 'sales/sales_filter.html', data) `` ` I tried this, but doesn't work. -
Field error for invalid user and Value error for new user registration in DJANGO
Many questions are there with the same keywords, but none of the answers helped. The issue is when an user other than the default user(admin) tries to login, Field error message is shown. When the same user is tried to register Value error is thrown. Hope someone could point out the mistake. Code : form1.py from django import forms from django.contrib.auth.models import User from django.contrib.auth import ( authenticate, get_user_model ) User=get_user_model() class UserLoginForm(forms.Form): username=forms.CharField(required=True) password=forms.CharField(required=True,max_length=120,widget=forms.PasswordInput) def clean(self, *args,**kwargs): username=self.cleaned_data.get('username') password=self.cleaned_data.get('password') if username and password: user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("user does not exists") if not user.check_password(password): raise forms.ValidationError('Incorrect Password') return super(UserLoginForm, self).clean(*args,**kwargs) class UserRegisterForm(forms.ModelForm): username=forms.CharField(required=True) password=forms.CharField(required=True,max_length=120,widget=forms.PasswordInput) email=forms.EmailField(required=True) class meta: model = User fields=[ 'username' 'email' 'password' ] def clean_email(self): username=self.Cleaned_data.get('username') email=self.Cleaned_data.get('email') password=self.Cleaned_data.get('password') email_qs=user.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email is already being used") return email code: views.py from __future__ import unicode_literals from django.shortcuts import render,redirect from django.core.mail import send_mail from django.conf import settings from .form1 import UserLoginForm,UserRegisterForm from django.contrib.auth import( authenticate, get_user_model, login, logout ) def login_view(request): next=request.GET.get('next') print("the following is being returned") title='Login' form= UserLoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) login(request,user) if next: return redirect(next) return redirect('/contact') templates="login.html" context={'title':title,'form':form,} return render(request,templates,context) def register_view(request): next=request.GET.get('next') title='Register' form= UserRegisterForm(request.POST or None) … -
Django import_export decode ascii code on submit?
Im trying to upload and import data into models from a csv file that contains special ASCII characters, for example "Big Fish Äö√Ñ√¥s", the django import_export would give me an error that reads: Imported file has a wrong encoding: 'utf-8' codec can't decode byte 0x80 in position 511: invalid start byte. This error would show when I select the file and click submit. The feature Im trying to implement would take a csv file that contains thousands of row of data, I was wondering if there is a way that I can go through each row level and clean the data line by line. I have tried implmenting the before_import_row method, but it doesn't seems to be called. my admin.py: '''ptyhon from django.contrib import admin from import_export.admin import ExportActionModelAdmin, enter code hereImportExportMixin, ImportMixin from import_export.resources import ModelResource from .forms import CustomConfirmImportForm, CustomImportForm from .models import Author, Book, Category, Child, EBook class ChildAdmin(ImportMixin, admin.ModelAdmin): pass class BookResource(ModelResource): class Meta: model = Book def for_delete(self, row, instance): return self.fields['name'].clean(row) == '' class BookAdmin(ImportExportMixin, admin.ModelAdmin): list_filter = ['categories', 'author'] resource_class = BookResource class CategoryAdmin(ExportActionModelAdmin): pass class AuthorAdmin(ImportMixin, admin.ModelAdmin): pass admin.site.register(Book, BookAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(Author, AuthorAdmin) ''' my models.py '''python [![import random import string … -
Python Dictionary should return a value rather than None
I have a csv file which consists a,b 2,3 4,5 4,7 4,7 (where a,b is a column values) Below i have two functions where the first function will read the csv and assign 'a' as key and 'b' as value in a dictionary Second function i will pass 'a' value as an argument and it returns b as a value when i use that function.If there is no value for 'a' i get None. def x (id): dict1= {} with open(file, 'r', encoding='utf') as f: for i in csv.DictReader(f, skipinitialspace= True) dict1[i['a']] = row['b'] print('im happy now' ) def getx (a): return dict1.get(a, None) It works perfectly. Now I have a csv file with four column values a,b,c,d 1,2,r,4 2,g,4,6 3,d,4,6 For this i have written a code like def x (): dict1= {} with open(file, 'r', encoding='utf') as f: for i in csv.DictReader(f, skipinitialspace= True) dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d'])) print('im happy now' ) def getx (a): return dict1.get(dict1['a']['b']['c'], None) My logic is to show dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d'])) as dict1 :{ 'a':{ 'b':{ 'c':2, 'c':4, 'c':4 } } } I'm not sure if what i have written above is right. I need to … -
Django: displaying foreign key model in parent model's detail view template
I have the following two models: class SpecimenImage(models.Model): image = ImageField(upload_to='images/') usi_image = models.ForeignKey('SpecimenRecord', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Unique Specimen Identifier') ... class SpecimenRecord(models.Model): usi = models.CharField(primary_key=True, max_length=20, verbose_name='Unique Specimen Identifier') species = models.ForeignKey(Species, on_delete=models.SET_NULL, null=True, blank=True) locality = models.ForeignKey(Locality, on_delete=models.SET_NULL, null=True, blank=True) date = models.DateField(null=True, blank=True) collector = models.ManyToManyField(Collector, verbose_name='Collector(s)', null=True, blank=True) ... I have a generic detail view for SpecimenRecord: ... class SpecimenDetailView(generic.DetailView): model = SpecimenRecord Here is the urls.py: ... urlpatterns = [ ... path('specimen/<str:pk>', views.SpecimenDetailView.as_view(), name='specimen-detail'), ] My question is, how do I display and loop through all of the SpecimenImage instances associated with a single SpecimenRecord object in the html template? I can easily display the information for each SpecimenRecord by using {{ specimenrecord.usi }}, etc., but I cannot figure out how to display each image. I've tried using the information on the MDN website for generic detail views (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views): {% for copy in book.bookinstance_set.all %} <!-- code to iterate across each copy/instance of a book --> {% endfor %} Here is the code I tried in my template specimenrecord_detail.html: {% extends "base.html" %} {% load thumbnail %} {% block content %} ... {% for copy in specimenrecord.specimenimage_set.all %} <div class="gallery"> <img src="{% thumbnail copy.image '1920' … -
Displaying value in the Frontend (React component) which is a foreign key in django models
I am learning django rest framework. I want to get author full name in JSON and not id, Below is GET request, is there a way if any? Created the Articles from admin site. I am trying to get the value in the Frontend with article.author [ { "id": 1, "article_title": "Premier League", "description": "The Premier League is the top level of the English football league system. Contested by 20 clubs, it operates on a system of promotion and relegation with the English Football League. The Premier League is a corporation in which the member clubs act as shareholders.", "created_at": "2019-10-02T08:59:24.883450Z", "author": 1 }, { "id": 2, "article_title": "Cricket in England", "description": "Cricket is one of the most popular sports in England, and has been played since the 16th century. Marylebone Cricket Club, based at Lord's, developed the modern rules of play and conduct.", "created_at": "2019-10-02T08:59:57.075912Z", "author": 2 }, ] Render function of a react component. article.author_id gives blank and article.author_id displays the author id as an integer. What should i return to display author full name? render() { return ( <Fragment> <h2>Articles</h2> <div > { this.props.articles.map(article => ( <div className="card" key={article.id}> <div className="card-body"> <div className="card-title"> <b>{article.article_title}</b></div> <div className="card-text"> {article.description}</div> … -
Image name get changed automatically for my Django project on Heroku
I had deployed my Django project on Heroku but when I am adding data to database then It changes my image to some other name but I don't know why it is happening. For ex. image name is img.jpg then after upload the new image name will be img_c34f.jpg ... some extra name is added automatically and due to this my image is not displaying on heroku website. My website is https://kharidarikaro.herokuapp.com/shop Please help..... -
Caching model properties in Django
In my Django app, I have a very repetitive query calling for item in self.schemaitem_set.all() very often. I feel this code is vastly inefficient. I am looking for a way to cash the query. Do you guys know how I could make the code below better? @property def gross(self): gross_sum = Decimal('0') for item in self.schemaitem_set.all(): gross_sum += item.gross return gross_sum @property def net(self): net_sum = Decimal('0') for item in self.schemaitem_set.all(): net_sum += item.net return net_sum @property def deposit(self): deposit_sum = Decimal('0') for item in self.schemaitem_set.all(): deposit_sum += item.deposit return deposit_sum @property def service_cost(self): service_cost = Decimal('0') if self.net > Decimal('150'): pass else: service_cost += Decimal('9.99') return service_cost @property def service_cost_vat(self): service_cost_vat = Decimal('0') if self.net > Decimal('150'): pass else: service_cost_vat += Decimal(f'{9.99*0,19}') return service_cost_vat @property def vat(self): vat = Decimal('0') for item in self.schemaitem_set.all(): vat += item.vat return vat -
How to solve "Account_user" not found in Django
I recently joined with an ongoing project which has done using the Django framework. When I run the following command it didn't create any migration file. py manage.py makemigrations --settings=hopster.settings.local When I run the following command as described in the readme file in the project. py manage.py migrate --settings=hopster.settings.local I receive the following error "django.db.utils.ProgrammingError: relation "Account_user" does not exist" It has local.py, dev.py, prod.py files base.py files instead of settings.py file. enter image description here enter image description here -
Link that does not exist
When I create new project in Django I have link from previous project. (I do not have "catalog" in new project... I create new db, may be it is problem with Chrome?) -
Looping through two arrays and adding the collection of each into new array without dups
I have two arrays that I want to loop through. Array A and Array B. I want to add the elements of both array into a new Array that contains the collection of all elements in that array without any duplication. This will be written in python. For Example A = [1,2,3,4] B = [1,5,6,7] Collection = [1,2,3,4,5,6,7] I was wondering if there's a faster and more efficient to do it without looping through each indexes and comparing it and then storing it. Because that's what I'm planning to do but I think it will take really long time given that I have about a couple thousand elements in each array. -
Image won't load to template in Django, but is stored to Media file
I'm trying to get a posted image to display on a Listview Blog application. Models.py from django.db import models class Post(models.Model): image = models.ImageField(upload_to='Post_images',null=True) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) success_url = "post-detail" template_name = 'post_form.html' urls.py from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) home.html {% extends "blog/blogbase.html" %} {% block content %} {% for post in posts %} {% if Post.image %} <img src="{{ post.image.url }}" class="img-responsive"> {% else %} <span class="text-muted">No cover</span> {% endif %} {% endfor %} I see "No cover printed" on all of the posts indicatign that Post.image is not registering. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '/media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, '/static') STATIC_URL = '/static/' I think it has to do with the media root, because when I upload the image it saves to the media file. I think the html/urls/settings connection is messed up. -
Python / Django / channels.exception.ChannelFull() error
We constantly get a channels.exception.ChannelFull() error when we run our setup. Traceback Our setup consists of: Server Computer Client Computer The Client connects via websocket to the Server. It sends and receives to the Server over this link. The Server runs Django with Redis (channels-redis) and Channels2 in ASGI mode. When a client connects, the specific.channel_id is stored in our database. When a client disconnects, it is removed from our database. We run a BackgroundScheduler Job at 5 second intervals. This Job gets the clients in the DB and sends each one (via specific.channel_id) a message. The Client receives this message over websocket, processes it, and sends the requested data back to the Server where it is processed through a WebsocketConsumer. When developing, we ran short tests (<2 min). It wasn't until later when we were running longer tests (2+ mins) that we started to encounter this error. What might we have missed? -
Django Model matching query does not exist on newly created instances
So I been seeing the same question posted in different scenarios and I am unable to get mine to work. Basically trying to find a model instance if it already exists and create a new one if it doesn't - based on if the instance have the same field as the user's username I tried get_object_or_404 and even changing the primary key to a field in the model class. this is the models.py class Cart(models.Model): user = models.CharField(max_length=30) @classmethod def create(cls, user): user = cls(user=user) return user def __str__(self): """String for representing the Model object.""" return f'{self.id} {self.user}' this is the views.py def cart(request, pk): try: pizza = PizzaInstance.objects.get(id=pk) # get the topping(s) topping_1 = int(request.POST["topping1"]) topping = PizzaTopping.objects.get(pk=topping_1) # get the username user = request.user.username # check if the user already has an order try: order = Cart.objects.get(user=user) except KeyError: order = Cart.create([user]) order.save() I expected to see the order being saved and a new instance being created or even new instances added to the cart. error is get is - Cart matching query does not exist. Thank you! -
Django Rest Framework custom Permission Class with ManyToManyField
I am trying to write a permission class for django rest api view. this is my models from django.db import models from django.contrib.auth.models import User class Profile(models.Model): name = models.CharField(max_length=50) auth_user = models.OneToOneField(User, on_delete=models.CASCADE) class Group(models.Model): admin = models.ManyToManyField(Profile, related_name='g_admin') members = models.ManyToManyField(Profile, related_name='g_mess') I want only group admin can perform an action in particular pages, for this i am writing a permission class: class IsGroupAdmin(BasePermission): """ Allows access only to Group Admin. """ def has_permission(self, request, view): # return bool() do something here I am going through trouble to write the permission class to check if group admin or not. i am facing issue coz, this is many to many field. can anyone help me to write this? -
Datatables: How to show a message while data is exported (Excel, PDF, etc)?
I use DataTables buttons plugin to export my data to Excel, PDF, etc. But when many rows of data have to be exported the process sometimes takes a lot of time while the file is created, I like to show a message that indicates the download is in progress until the 'save as' window appears. I only have implemented the standard buttons configuration in the inicialization of datatable. Many thanks in advance for any idea or suggestion. -
Model field to hold any number of possible values from a finite list of choices
Say I have an abstract Product model with 'shipping' field on it, and I want that field to hold any number of possible values from a finite list of choices. So, if my choices list is: [ ('fedex', 'FedEx'), ('company2', 'Company 2'), ('company3', 'Company 3'), ... ] ...the model field should be able to hold one or more (or all) values from the list. What field should I use and how should I design my model? -
Django Student-Teacher ManyToMany relationship
I'm trying to model a Many to Many Teacher/Student relationship. Both the teachers and the students are objects of class Users (I edited out some unrelated fields). I'm having problems in understanding how the relationship should work. Basically, I want to be able to do something like u1 = User.objects.get(pk=<student pk>) u1.teachers.all() u2 = User.objects.get(pk=<teacher pk>) u2.students.all() After reading some docs and tutorials, this is how I defined the User class and the StudentTeacher relationship: class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) teachers = models.ManyToManyField('self', through="StudentTeacher", through_fields=('student', 'teacher'), symmetrical=False) students = models.ManyToManyField('self', through="StudentTeacher", through_fields=('teacher', 'student'), symmetrical=False) class StudentTeacher(models.Model): teacher = models.ForeignKey(User, related_name='students', on_delete=models.CASCADE, limit_choices_to={'is_teacher': True}) student = models.ForeignKey(User, related_name='teachers', on_delete=models.CASCADE, limit_choices_to={'is_student': True}) This is what happens when I try to generate migrations (wiscom is the name of my application): wiscom.StudentTeacher.student: (fields.E302) Reverse accessor for 'StudentTeacher.student' clashes with field name 'User.teachers'. HINT: Rename field 'User.teachers', or add/change a related_name argument to the definition for field 'StudentTeacher.student'. wiscom.StudentTeacher.student: (fields.E303) Reverse query name for 'StudentTeacher.student' clashes with field name 'User.teachers'. HINT: Rename field 'User.teachers', or add/change a related_name argument to the definition for field 'StudentTeacher.student'. wiscom.StudentTeacher.teacher: (fields.E302) Reverse accessor for 'StudentTeacher.teacher' clashes with field name 'User.students'. HINT: Rename … -
User defined template Django
Is there a way to enable application users to create their own template within the django app? One example would be how MailChimp enables users to create their own custom email template. Currently i'm thinking of creating a model that captures information the user wants to display. that model can point to a template and populate it with the information the user wants to display. But is there a better way? -
Can't start gunicorn.service on VirtualBox with CentOS 8, Nginx and Django-Rest-Framework
Trying to deploy django application using gunicorn and nginx on CentOS. Following DigitalOcean tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 But I have CentOS 8. I can run my application localy from virtualenv using: python manage.py runserver gunicorn --bind 0.0.0.0:8000 app.wsgi:application but then I try to run gunicorn.service I have status - failed. inside of systemctl status gunicorn.service I have started gunicorn deamon gunicorn.service: main process exited, code=exited, status=203/EXEC gunicorn.service: failed with result 'exit-code' Without this file I can't bind app.sock file as it not being created. My gunicorn.service looks like this app - is fictional application name :) admin - is a real user of this system [Unit] Description=gunicorn daemon After=network.target [Service] User=admin Group=nginx WorkingDirectory=/home/admin/app/portal/app ExecStart=/home/admin/app/env/bin/gunicorn --workers 3 --bind unix:/home/admin/app/portal/app/app.sock app.wsgi:application [Install] WantedBy=multi-user.target There is a tree of my project: app - env - portal -- client -- app --- documents --- fixtures --- images --- app ---- __init__.py ---- settings.py ---- urls.py ---- wsgi.py --- app_project ---- ... --- manage.py --- requirements.txt What can be done to make it work and that chan I check to find more clues why it doesn't work? Any input is welcome. Thanks -
Django using custom HTML form without Form model
I'm trying to use a custom login page and HTML form with Django but I'm not sure how to configure the application's urls.py. Here is my HTML form: <form method="POST" action="{% url 'users:login' %}"> {% csrf_token %} <div class="field"> <div class="control"> <select class="bureau_select" name="bureau" autofocus=""> <option value="FNC">Finance</option> <option value="HR">HR</option> <option value="CRT">Creative</option> </div> </div> <div class="field"> <div class="control"> <input class="input" type="text" name="username" placeholder="Name" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input" type="password" name="userpassword" placeholder="Password"> </div> </div> <button class="button">Login</button> </form> users is the application I've made to handle things like auth, changing user profile, etc. My users app looks like this: urls.py from django.urls import path from . import views app_name='users' urlpatterns = [ path('login/', views.CustomLoginView.as_view(), name='login'), ] views.py from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm, ) from django.contrib.auth import authenticate, login class CustomLoginView(LoginView): # form_class = AuthenticationForm template_name = 'users/login.html' def login_user(request, user_id): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... (following Django docs) I'm aware I can create this … -
Fix bootstrap table in weasyprint generated PDF
I'm trying to create a PDF table with Weasyprint in my Django website. The same table is shown in a html page and with Weasyprint. When I use bootstrap colors in the html version it shows correctly, but the colors are lost on the Weasyprint version. That is the only feature missing on the Weasyprint version, which works otherwise. views.py @login_required def scale_answer_pdf(request, scale_id): scale = get_object_or_404(UserScale, pk=scale_id) if scale.user == request.user or request.user.is_superuser: if scale.scale_meta.title == "Now": choices = NowLegend class ScaleForm(forms.ModelForm): class Meta: model = NowModel fields = labellist(NowLabels) labels = NowLabels if scale.scale_meta.title == "Child": choices = NowLegend class ScaleForm(forms.ModelForm): class Meta: model = ChildModel fields = labellist(ChildLabels) labels = ChildLabels form = ScaleForm(instance=scale) **html = render_to_string('diagnosis/scale_answer_pdf.html', {'form': form, 'scale':scale, 'choices':choices}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="{} - {} - {}.pdf"'.format(scale.scale_meta.title, scale.user.username, scale.created.strftime('%Y-%m-%d')) weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response, presentational_hints=True, stylesheets= [weasyprint.CSS(settings.STATIC_ROOT + '/css/sb-admin-2.min.css'), weasyprint.CSS(settings.STATIC_ROOT +'/css/all.min.css')]) return response** else: raise Http404 html for the PDF - the boostrap CSS works, and the table is also showing. But the colors from the table don't. I highlight the table parts that don't show colors {% extends "base_pdf.html" %} {% load i18n %} {% load staticfiles %} {% load get_item %} {% block content …