Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRY validation of query params for djangorestframework view
I want to create a view in django-rest-framework. This view would accept several custom query parameters, so it wouldn’t be based on any existing view. I want the query parameters to be available in the OpenAPI 3 schema for the purpose of type-checking in the TypeScript client. My questions are: How can I perform the validation of these parameters declaratively? Is using Serializer a good way to perform validation of a query string? How can I generate the corresponding part of the OpenAPI 3 schema in a DRY way? I see that the existing drf views don’t use a DRY pattern here (they just return a static directory for schema). Also, the method that generates schema for Serializers is underscore-prefixed, so it might not be a good idea to use it directly (although I don’t know the rationale for this). So what are my options here? -
Alternative for drf-expander
I am using drf-expander for in-line expansions using expandable_fields. However, I have observed that for huge databases, the performance of drf-expander is limitied. Is there an alternative to drf-expander that can help me perform inline expansions more optimally (faster)? -
Django : AttributeError: module 'profiles_api.views' has no attribute 'HelloViewSet'
AttributeError: module 'profiles_api.views' has no attribute 'HelloViewSet' Git Repo urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from profiles_api import views router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') urlpatterns = [ path('hello-view/',views.HelloApiView.as_view()), path('', include(router.urls)), ] Please give your suggestion -
Apache/mod_wsgi ModuleNotFoundError
I am trying to host a Django website on an Ubuntu VPS with Apache/mod_wsgi. If I run it in embedded mode, the site loads. WSGIScriptAlias / /home/admin/web/mywebsite/myproject/wsgi.py WSGIPythonHome /home/admin/web/mywebsite/venv WSGIPythonPath /home/admin/web/mywebsite <Directory /home/admin/web/mywebsite/myproject> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> However, if I try to run it in daemon mode, I get an error: "ModuleNotFoundError: No module named 'myproject'". WSGIDaemonProcess myproject python-home=/home/admin/web/mywebsite/venv python-path=/home/admin/web/mywebsite socket-user=#1001 WSGIProcessGroup myproject WSGIScriptAlias / /home/admin/web/mywebsite/myproject/wsgi.py My WSGI file: import os from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' application = get_wsgi_application() If I run a manage.py command, it shows the same ModuleNotFoundError error in both embedded and daemon mode. What could possibly be wrong? -
invalid literal for int() with base 10: with Django
My model : I am getting invalid literal for int() with base 10 in Django it is working in perfectly in the shell class Category(models.Model): cat_id = models.IntegerField(primary_key=True) category_name = models.CharField(max_length=1000) created_at = models.DateField(auto_now=True ,max_length=30) def __str__(self): return self.category_name class Content(models.Model): content_id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.CharField(max_length=5000) created_at = models.DateField(auto_now=True) def __str__(self): return self.content ** my view ** def create_blog(request): if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] category = request.POST['category'] object_of_category = Category.objects.get(cat_id = (category)) save_post = Content(category = object_of_category, content =content) save_post.save() return redirect(create_blog,{'message':'Post created Successfully!'}) categories = Category.objects.all() return render(request ,'admin/create_blog.html', {'categories' : categories}) -
Django how to map LDAP group to django grup and automatically assign to user
I am wondering if there is possibility to map LDAP group with Django group and assign it automatically to user from LDAP group, OR if there is at least possibility that every new user logged and authenticated on via LDAP can be assign by default to specific group? I have 3 groups created via admin django page: ADMIN ENGINEER READER and i have 3 groups in LDAP: DSAPB2T_PASSED_ADMIN GSAFU3T_PASSED_ENGINEER GSAFU3T_PASSED_READER is there any possibility that when user from GSAFU3T_PASSED_ENGINEER group log in for the first time, will automatically be assign to ENGINEER django group? (same for ADMIN and READER) or if this is not possible or good solution, is there a possibility that every new user (authenticated form any of these 3 LDAP groups) will be automatically assigned to READER group? -
Django Writable fields and serializers error with foreign keys
Not sure what's going on here, but I can't seem to POST as expected. Here's the error I get: TypeError: Got a `TypeError` when calling `Upload.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Upload.objects.create()`. You may need to make the field read-only, or override the UploadSerializer.create() method to handle this correctly. My models.py: class Project(SoftDeletableModel, TimeStampedModel): id = models.AutoField(primary_key=True) name = models.CharField(max_length=511, blank=True) def __str__(self): return str(self.id) class Upload(TimeStampedModel): id = models.AutoField(primary_key=True) file = models.FileField(upload_to=random_filename("uploads-%Y%m%d")) upload_type = models.CharField(choices=AVAILABLE_UPLOAD_TYPES, max_length=127) project = models.ForeignKey(Project, on_delete=models.PROTECT, related_name="uploads") def __str__(self): return str(self.id) serializers.py: class UploadSerializer(serializers.ModelSerializer): class Meta: model = models.Upload # fields = ("file", "upload_type", "project") fields = "__all__" class ProjectSerializer(serializers.ModelSerializer): uploads = UploadSerializer(many=True, read_only=True) class Meta: model = models.Project # fields = "uploads" fields = "__all__" viewsets: class UploadViews(viewsets.ModelViewSet): serializer_class = UploadSerializer queryset = Upload.objects.all() class ProjectViews(viewsets.ModelViewSet): serializer_class = ProjectSerializer queryset = Project.objects.all() I can create projects as expected, but when I try to create uploads, I get the error as described before. Does this have to do with the foreign key? I'm confused what is/isn't writable here. I'm doing this through the django web UI -
What websites mostly used while working on python, django(drf, templates) and angular(typescript, html, css, boostrap, javascript)
what are the useful websites mostly used while working on python, django(drf, templates) and angular(typescript, html, css, boostrap, javascript). I have listed out few websites those are i commonly used. https://www.primefaces.org https://stackoverflow.com/ https://angular.io/ https://docs.python.org https://docs.djangoproject.com/ https://www.geeksforgeeks.org/ https://github.com/ https://dzone.com/ https://tortoisesvn.net/ https://www.django-rest-framework.org/ -
How can I combine two of them and create a new serializer with new fields
I am facing one issue with formating the response of DRF I am sharing my model Details here class Plan(AuditFields, Model): id = models.AutoField(primary_key=True) object_id = models.UUIDField( unique=True, editable=False, verbose_name='Public identifier') plan_name = models.CharField(max_length=255, blank=True) team = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="%(app_label)s_%(class)s_team") class PlanDetail(AuditFields, Model): plan = models.ForeignKey( Plan, on_delete=models.CASCADE, blank=True, null=True) plan_stage = models.CharField(max_length=255, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) status_of_plan = models.CharField(max_length=255, blank=True) Using the Above models I need to create a response like this . But I am facing some issues with this plan details : [ { "plan_stage": "Sample1", "status_of_plan": "Completed", "start_date": "2019-07-01", "end_date": "2019-07-01", }, { "plan_stage": "Sample2", "status_of_plan": "Not Commenced", "start_date": "2019-08-01", "end_date": "2019-08-31", }, { "plan_stage": "Sample3", "status_of_plan": "Not Commenced", "start_date": "2019-09-01", "end_date": "2019-09-30", }, { "plan_stage": "Sample4", "status_of_plan": "Not Commenced", "start_date": "2019-10-01", "end_date": "2019-10-31", }, { "plan_stage": "Sample 5", "status_of_plan": "Completed", "start_date": "2019-11-01", "end_date": "2019-11-30", }, { "plan_stage": "End Date (Final Report)", "status_of_plan": "Completed", "start_date": "2019-12-01", "end_date": "2019-12-31", } ] plan :{ "id" : 1. "object_id": 456789023456546, "plan_name" : "Sample", "team":['Sachin','Dravid'] } I am using two serializers and trying it ..... But its not works in this case class PlanningSerializer(ModelSerializer): '''THis is for Model Plan ''' team = TeamSerializer(many=True, read_only=True) … -
Intellj python test running Django environment separately
I have Django application inside IntelliJ IDE. I can run all Django tests by calling the Django Tests runner. But: This is a time consuming and not ideal for development, where you would like to rerun one test that fail, and not run all 1000 others that are ok. IntelliJ has options (UI) to run one test quickly, but this run python tests runner. I add DJANGO_SETTINGS_MODULE=... inside, but now I get other errors: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I was looking to solve this error and I only found : import django django.setup() inside Settings.py My problem with this is: I think this breaks normal behaviour of the app. App works normal for different environments. It doesn't call code after this setup inside settings, so secret_key and others are not installed This doesn't seam to be really related to tests, but is changing the whole app. So, I am looking for some settings, how to set the normal python tests, so that they will run as django tests. -
list_display rows in a table conditionally django
I have two tables Employee ----- username organisation_id email Organisation ------------ organisation_id company_name User_A->organisation_1 User_B->organisation_1 User_C->organisation_2 User_D->organisation_2 when user_A login he should only see User_A and User_B This code should be like below, logic is first we need to find the current user organization and conditionally display the results in admin page Django admin code admin.site.register(Employee, CustomUserAdmin) admin.site.register(Organization) class CustomUserAdmin(UserAdmin): def filter_view(request): current_user = request.user organization_id =employees.objects.get(id=current_user.id).organization_id List_display = ('username', 'email','Organizations.objects.filter(id=organization_id)') -
Single checkbox form not being submitted.Also getting a MultiValueDictKeyError while submission
<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>Please Fill up the details below (Note that required field are marked by '*' )</u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-show="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="bname" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="phone">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="aadharno" class="form-control" id="aadhar" name="aadhar" pattern="^\d{4}\s\d{4}\s\d{4}$" placeholder="Enter Aadhar Card number with proper spacing" required> </div> </div> <!--logic for no--> <div ng-show="showHideTest=='false'"> <div class="form-group"> <label for="formGroupDistrict">Please provide any of the following Identity Card*:</label> <select name="idcard" id="formGroupDistrict" required> <option>Bank or Post Office photo passbook</option> <option>Voter ID Card</option> <option>Ration Card</option> <option>Kishan Photo Passbook</option> <option>Passport</option> <option>Driving License</option> <option>PAN Card</option> <option>MGNREGS Job Card</option> <option>Her husband's Employee Photo Identity Card issued by the government or any Public Sector Undertaking</option> <option>Any other Photo Identity Card issued by State Government or Union Territory Administrations</option> <option>Certificate of Identity with photograph issued by a Gazetted … -
Django shell not able to execute ORM query
I am using Django shell for debug purpose of my project by using command 'python manage.py shell'. I have found that I am not able to execute ORM queries from shell & getting below kind of error. from base.models import Template_Form, Template_Form_Field Template_Form_Field.objects.all() After executing above code in shell I am getting below error. Traceback (most recent call last): File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_template_form_field" does not exist LINE 1: ...ions", "base_template_form_field"."sequence" FROM "base_temp... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", … -
Filter is not working in Django Rest Framework
I would like to filter my data like assumes I have one model => User UserID UserName UserDescription What I want is=> If i select like => api/user/?userid=1 , It should return only userid == 1 result. If I select like => api/user/?username=test, It should return only username == test result. What I have done? I installed django-filter and add this REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } to setting.py and I test like that but why I get all of my records? even URL is select only userid = 1 api/user/?userid=1 and If I test with the wrong URL parameter and I got all records even the wrong parameter. I do the exact same way with this => https://www.django-rest-framework.org/api-guide/filtering/#generic-filtering -
how to display django form validation error message with ajax?
Here I want to display form validation error message with the help of ajax.For this I tried like this but there are some problems with this code. Here It displays the error message if not group is unique which is fine(works as I wanted) but I want to disappear this message after the user clears the name from input field(which is not happening now.) and if the user writes the unique group name I want to display some other message like "Ok" or something else. How can I do it ? def validate_group_name(request): group = request.GET.get('name') data = {'is_taken': Group.objects.filter(name__iexact=group).exists()} return JsonResponse(data) ajax <script> $("#id_group").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-group-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { $(".error").text("This group name already exists").show(); } } }); }); </script> -
Django - How to sort a select based on the length of two concatenated fields
I'm using Django 3.0 This is my model: class StoreIdentification(models.Model): store = models.ForeignKey(Store, blank=True, on_delete=models.CASCADE, default=None) description_1_text = models.CharField(max_length=48, null=True, blank=True, default=None) description_2_text = models.CharField(max_length=48, null=True, blank=True, default=None) def __str__(self): return f'{self.store.name} - {self.description_1_text} + {self.description_2_text}' I have a select where I need to sort based on the length of the concatenated text of both description_1_text and description_2_text. I'm able to do each one of them separately, all my tries failed. Here are some tries: def identify(request): identifiers = StoreIdentification.objects.all().extra( select={'char_num': 'Length(description_2_text)' + 'Length(description_1_text)'} ).order_by('-char_num') for identifier in identifiers: # Do something ... This one is returning an error next to he Lenght (django.db.utils.OperationalError: near "Length": syntax error) Another try: identifiers = StoreIdentification.objects.all().order_by( Length('description_1_text' + 'description_2_text').desc()) This one concatenated the description_1_text and description_2_text before they were resolved. Try #3: identifiers = StoreIdentification.objects.all().extra( select={'char_num': 'Length(description_2_text) + Length(description_1_text)'} ).order_by('-char_num') The last try just ignored the Length(description_1_text) and ordered only based on description_2_text. I had a few other tries, all ended the same ... with some error. Any suggestions? -
Getting certain value from json
<h2>Content as Array.</h2> <p>Content written as an JSON array will be converted into a JavaScript array.</p> <p id="demo"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr } }; xmlhttp.open("GET", "http://127.0.0.1:8000/test", true); xmlhttp.send(); </script> output: Content as Array. Content written as an JSON array will be converted into a JavaScript array. [{"model": "core.newcarmodel", "pk": 1, "fields": {"car_model_new": "swift"}}, {"model": "core.newcarmodel", "pk": 2, "fields": {"car_model_new": "wagonr"}}, {"model": "core.newcarmodel", "pk": 3, "fields": {"car_model_new": "baleno"}}, {"model": "core.newcarmodel", "pk": 4, "fields": {"car_model_new": "breeza"}}, {"model": "core.newcarmodel", "pk": 5, "fields": {"car_model_new": "spresso"}}] how to get all the carmodels values example: output: swift,wagonr,baleno....so on i would like to get carmodels values from json format and insert in variable like a list example: var carmodel = [swift,baleno,wagonr....] -
DjangoModelForm: How to add extra fields and preprocess them before sending to views
I have a model form which displays all the fields: class BatchForm(ModelForm): class Meta: model = Batch fields = ('__all__') It works fine and shows all the fields in the views. I now want to add extra fields to this form which dont exist in the model. These fields are: completed_tasks: int statistics: array I then want to add 2 methods in the form which auto populate these fields before sending it to the view. The methods will be: def completed_tasks_method(self, obj): return obj.assignments_per_task * obj.total_tasks() def statistics_method(self, obj): #something i cant figure out how to extend the modelform to add additional attributes and then how to populate the fields before sending them to the views. Can you please help ? Thanks. -
Write a thinner view in django ModelViewSet
I have a sample project as follow github link. The problem is the logic handles mostly on view, not serializers. I read it as a bad practice: class OrgAddAPI(viewsets.ModelViewSet): queryset = Organization.objects.root_nodes() serializer_class = OrganizationSerializer def create(self, request): alldata = request.POST # desc = alldata.get("desc", "0") # name = alldata.get("name", "0") desc = request.data.get("desc") name = request.data.get("name") code = request.data.get("code") subpath = request.data.get("subpath") try: parent = Organization.objects.root_nodes().get() except Exception as e: print(e.__class__.__name__) if e.__class__.__name__ == "DoesNotExist": parent = Organization.objects.create(name="BOSS", desc="boss",code="BOSS",subpath="ftech") else: response_dict = {"c" : ErrorCode.ORG_GENERIC_ERROR, "m": str(e), "e" : ErrorCode(ErrorCode.ORG_GENERIC_ERROR.name)} return Response(response_dict) try: Organization.objects.create(name=name, desc=desc, code = code, subpath =subpath, parent=parent) except Exception as e: response_dict = {"c" : ErrorCode.ORG_GENERIC_ERROR, "m": str(e), "e" : ErrorCode.ORG_GENERIC_ERROR.name} return Response(response_dict) response_dict = {"result": "true"} # update response_dict with whatever you want to send in response return Response(response_dict) I tried to refactor to serializer but it not jump to the new function: class OrganizationSerializer(serializers.ModelSerializer): children = RecursiveField(many=True) def validate(self,data): """ //// not jump check that root node must be available :param data: :return: """ serialized = jsonpickle.encode(data) print(yaml.dump(yaml.load(serialized), indent=2)) def create(self, validated_data): name = validated_data.get("name", None) // not jump serialized = jsonpickle.encode(validated_data) print(yaml.dump(yaml.load(serialized), indent=2)) class Meta: model = Organization fields = ('id', 'name', … -
How to use django notifications-hq?
I'm using django notifications for notification of my app and it notifies the user when their is some activities with their post. But i want to add the url of the post in the notification list so users will click the notification and can go to the specific post. I've tried it many ways but can't find the solution. -
How can I speed up call forwarding on Twilio? - Django
I just implemented call forwarding based on the following Twilio tutorial: https://www.twilio.com/docs/voice/tutorials/call-tracking-python-django The call forwarding works, however there are about 3 seconds of "static sounds" before the phone that is dialing the number starts hearing the phone ringer. Why is there such a delay in forwarding the call, how can this be resolved for a production level application? Calls are made over US phone networks, so did not expect delay issues. This is the function implementing the forwarding: # views.py # View used by Twilio API to connect callers to the right forwarding # number for that lead source @csrf_exempt def forward_call(request): """Connects an incoming call to the correct forwarding number""" # First look up the lead source source = LeadSource.objects.get(incoming_number=request.POST['Called']) # Respond with some TwiML that connects the caller to the forwarding_number r = VoiceResponse() r.dial(source.forwarding_number.as_e164) # Create a lead entry for this call lead = Lead( source=source, phone_number=request.POST['Caller'], city=request.POST['CallerCity'], state=request.POST['CallerState']) lead.save() return HttpResponse(r) -
Filter based on number of manytomany
I have models defined as follow: class Employee(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Project(models.Model): ... employees = models.ManyToManyField(Employee, null=True, blank=True) I'm trying to retrieve all the projects that have at least one employee assigned to them, but I don't know how. I tried the following things: projects.filter(employees__gt=0) where projects = Project.objects.all() but I don't think this is the right query, because if I do projects.filter(employees_lte=0) it returns nothing, even if I have projects with no employees assigned. How can I retrieve what I'm looking for? Could you point to a page where I can find all the lookups I can use? Thanks! -
Django url dispatcher using repath arguments
In my django app . I have endpoints for a package with the months like : www.example.com/cart/packagename/months www.example.com/cart/stater/3 which i dont think will good as an url pattern I want something like : www.example.com/cart/?package=stater&months=3 And also want to encode the parameters 'package=stater&months=3' If anyone has any suggestions how to achieve that with django let me know. because before i worked with laravel and its pretty simple to do. -
vscode django extentions makes vscode can't recognize html files
I have installed most of django extensions on vs code , but vs code can't recognize the html files after installing any of them. Is there any way to use any django extension while the html files is recognized by vs code -
Generating PDFs from Pandas DataFrame with ReportLab with Python
I have been battling with exporting my Pandas DataFrame to PDF. Let me explain the situation. I have a Pandas DataFrame for example: commissions_df.columns = [ 'Versicherer', 'Produkt Bereich', 'Produkt Typ', 'Produkt', 'Vertragsart', 'Steuersatz', 'AP gesamt', 'BP gesamt', "Anteil Partner" ] I would like to filter by 'Versicherer', which is category type and have each DataFrame as a separate frame. I was successful at exporting each frame as a sheet with Excel. Here is an image of the way it looks: And here is the code I used to do that: Different_Versicherer = commissions_df.Versicherer.unique() number1 = np.random.randint(0,100) number2 = np.random.randint(101,800) FileName1 = 'FileName' con = "_" ext = ".xlsx" excelname = FileName1 + con + str(number1) + con + str(number2) + ext writer = pd.ExcelWriter(excelname) # iterate through each insurance and add a seprate sheet for all of them for Versicherer_names in Different_Versicherer: frame = commissions_df[commissions_df['Versicherer'] == Versicherer_names] frame.to_excel(writer, sheet_name= Versicherer_names[0:7],index=False) writer.save() Right now, I would like to export the DataFrames to PDF using ReportLab and have each unique item in Versicherer have its own page with header colour: So far here is what I tried: import reportlab from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.utils import ImageReader …