Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep track of counter and increment value by one in Django
Is there way to keep track of a counter in a Django template and increment its value by one only if it meets a certain condition? For example I want to do something like this: {% with car_counter=0 %} {% for car in cars %} {% if car.make=="Ford" and car_counter < 3 %} {{car.price}} ??? increment car_counter ??? {% endif %} {% endfor %} {% endwith %} I would like to only execute the loop 3 times if it meets this condition. How would I go about this? -
Name 'Group' is not defined
Django 1.11 Python 3.6.1 For my project is to be deployed, I will have to predefine some things. Namely, I'll need a couple of groups for users. So, I made a directory "deployment" and placed it next to the project's directory. When a new database will be created, I'll just execute: python manage.py shell < ../deployment/initialize_project.py This code works: from django.contrib.auth.models import Group Group.objects.create(name="commentator") # Can only comment. Group.objects.create(name="contributor") # Can add, change and delete # objects. This code does not: from django.contrib.auth.models import Group def initialize_roles(): Group.objects.create(name="commentator") # line 6 Group.objects.create(name="contributor") initialize_roles() # line 12 Traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 6, in initialize_roles NameError: name 'Group' is not defined I marked line 6 and 12 in the code above (as inline comments). I tried to use pdb.set_trace(), but the same error appear. As if pdb is not defined. I also tried not to … -
How to set WSGIPassAuthorization when serving Django via runmodwsgi
I'm using mod_wsgi express to host a Django site. I create the server config by running ./manage.py runmodwsgi and passing some options like --setup-only. I would like to use HTTP basic auth (using the browser's built-in prompt). I can't find out how to have the auto-generated apache config set this directive: WSGIPassAuthorization On Is there a way to do this with mod_wsgi express? -
Adding captcha to django crispy form
I'm working with Django 1.8 and Django crispy forms. I need to add a captcha to my form which looks like: class SellerForm(forms.ModelForm): class Meta: model = Seller # Your User model fields = ['contact_name', 'contact_address', 'contact_email'] labels = { 'contact_name' : 'Your Name', 'contact_address' : 'Your Address', 'contact_email' : 'Email', # 'captcha': "Enter captcha" } helper = FormHelper() helper.form_method = 'POST' helper.form_action = "/contact/" helper.form_id = 'form' helper.add_input(Submit('Submit', 'Submit', css_class='btn-primary')) Reading through the docs at http://django-simple-captcha.readthedocs.io/en/latest/usage.html doesn't make it clear to me how to use the crispy forms plugin. What is the best approach to be able to add a captcha? -
queryset update using F() object don't works in datamigrations
I'm trying to create a datamigration using update queryset method. I have a complex migration process for my case, so i faced the following problem. The simple example from __future__ import unicode_literals from django.db import migrations, models def move_data(apps, schema_editor): MyModel = apps.get_model("my_app", 'MyModel') MyModel.objects.all().update(new_field=models.F('old_field')) class Migration(migrations.Migration): dependencies = [ ('orders', '0057_auto_20170410_1513'), ] operations = [ migrations.RunPython(move_data), ] In my case i got FieldError. F() object can't resolve the field old_field, but if i will use something like this for obj in MyModel.objects.all(): obj.new_field=obj.old_field obj.save() instead of MyModel.objects.all().update(new_field=models.F('old_field')) all will be good I have a few models inherited from one base model and i need to move some fields from on of the child model to parent. So i made this with the following steps rename the old fields in child create the new fields in parent move data from old fields to new fields delete the old fields I faced this at the 3 step and can't understand why it don't works Can somebody provide some explanation of this? Is it related to the model state rendering process somehow? -
Deploying Django application in AWS. Raise Disallowed Host exception
I am newbie in Amazon Web Services and I'm trying to deploy a Django application using elastic BeansTalk. I'm following the AWS developer guide and when I deploy the application using EBCLI and open the browser to see my application running, I get the following error. Request Method: GET Request URL: http://django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com/ Django Version: 1.9.12 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 123. response = middleware_method(request) File "/opt/python/run/venv/lib/python3.4/site-packages/django/middleware/common.py" in process_request 56. host = request.get_host() File "/opt/python/run/venv/lib/python3.4/site-packages/django/http/request.py" in get_host 109. raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com'. You may need to add 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com' to ALLOWED_HOSTS. Obviosly the application was deployed but for some reason the exception raises. Can anybody help me, please? -
is the Django management command executed in a separate process?
Django has many management commands. In addition, we can write our own commands. What happens after I make a shell call python manage.py XXX? Will the code be executed in a process that launched from the shell? Or the shell process just communicates with the main Django process that executes the command? -
I created a new model signup with appropriate fields which creates users just fine but I am unable to create a log in for the same [Django]
I was following "CodingEntrepreneurs - Try Django Tutorial 5 of 21 - Django Views for the Sign up model" tutorial on YouTube and was able to successfully create a signup model with proper details. After that I wanted to implement sign in feature for the same, so I started following > https://www.youtube.com/watch?v=O4zNUCFtfdY&feature=youtu.be < but I am unable to log in through this process, it is always returning the unable to login page, I am completely lost even though I have spent a lot of time figuring this out on my own. This is the project folder. Any help would be appreciated. Signin.html <!DOCTYPE html> <html> <head> </head> <body> <h1>Sign In</h1> {% if form.errors %} <p> Sorry thats invalid username or password</p> {% endif %} <form method="POST" action="/auth/">{% csrf_token %} <label for="email">E-mail</label><br><input type="email" name="email" value="" placeholder="E-mail"><br> <label for="password">Password</label><br><input type="password" name="password" placeholder="password"> <input type="submit" > </form> </body> </html> views.py from django.shortcuts import render,render_to_response from django.http import HttpResponse from django.template import RequestContext from .forms import SignUpForm,SignInForm from django.contrib import messages from django.contrib.auth import authenticate,login from django.template.context_processors import csrf # Create your views here. def home(request): return render_to_response('index.html') def signup(request): form=SignUpForm(request.POST or None) if form.is_valid(): save_it=form.save(commit=False) save_it.save() messages.success(request,'thanku for joining') return render(request,'signup.html',{'form':form}) def SignIn(request): … -
Protecting or Licensing a Django Application
I am making a Django application and I am running into an issue. I know Python is interpreted and it would be impossible to completely fight against piracy, however I want to implement some sort of security/licensing feature for my application. I thought I would post the question because I can't find much information about this online. I'm not sure if I should create some sort of installer which downloads files from a server depending on if a key is valid or not and installs them onto a users host, or if I should encrypt the files upon sending and decrypt them with a key. If anybody has any pointers or if anybody has faced this before I'd love to hear! -
Django: apps.get_model(). Models aren't loaded yet. Error
I want to import a module (lets say "Subject") from an app (lets say "A") which imports some modules from this app (lets say "B"). When I use apps.get_module('A.Subject') in the B/models.py it is giving me an error message "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." Please note that I already tried something like: 'models.ForeignKey('A.Subject')' But I don't want this kind of Foreign Key. Because it makes me first remove the models.ForeignKey() and migrate, and then adding it to my database. here is my files: A/models.py from B.models import my_model class Subject(models.Model): name = models.CharField(max_size=100) price = models.FloatField() """ other stuffs """ B/models.py from A.models import Subject class Profile(models.Model): subjects = models.ManyToManyField(Subject) """" other stuff """ -
Django Sites + ALLOWED_HOSTS
I'm implementing a django multi-site portal. I'm probing it and I get an "Invalid HTTP_HOST header" exception when I try to access a site domain that I have register in Sites model. Is it necessary to set the url in settings.ALLOWED_HOSTS too? -
Selenium cookie for subdomain
I'm setting up some functional tests for a django site which redirects users to dashboard.appname.com when they visit appname.com when they're already logged in. In order to allow this in the test infrastructure, I need to add a cookie to the browser with .appname.com as the domain. I do this with self.browser.add_cookie(dict( name=settings.SESSION_COOKIE_NAME, domain='.appname.com', value=session_key, path='/', )) This all works fine when I use the Chrome webdriver but if I use the Firefox webdriver, I get selenium.common.exceptions.WebDriverException: Message: InvalidCookieDomainError is not defined which I think means that it won't allow a wildcard subdomain like this. But I need to use the wildcard in order to get the dashboard.appname.com to work. Given that the Chrome webdriver works, I suspect that it's geckodriver that's broken but I'm not 100% sure. Any ideas? -
AJAX+DJANGO sending pdf as formData:UNSUPPORTED` MEDIA TYPE
Trying to send pdf to django backend using ajax. formData is made this way. And pdf exists as well as formData object, so everything is correct. var fd = new FormData(); fd.append('file', files[i]); ajax request: $.ajax({ url: '/upload_ticket/', data: { file : fd, csrfmiddlewaretoken: "{{ csrf_token }}" }, type: 'POST', contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+) processData: false, // NEEDED, DON'T OMIT THIS success : function() { alert('succes'); }, // handle a non-successful response error : function() { alert('error'); } }); That code returns that formData pdf is unsupported `Failed to load resource: the server responded with a status of 415 (UNSUPPORTED` MEDIA TYPE) why? How can I implement that correctly? -
How to pass user object to forms in Django
How would I pass a user object or a request to my form for using it as an initial value for input textbox? For example, I have my form: class ContactForm(forms.Form): contact_name = forms.CharField(required=True, initial="???") contact_email = forms.EmailField(required=True) subjects = forms.ChoiceField(choices=emailsubjects) content = forms.CharField( required=True, widget=forms.Textarea ) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(ContactForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "Your name:" self.fields['contact_email'].label = "Your email:" self.fields['content'].label = "What do you want to say?" self.fields['subjects'].label = "Please, select the subject of your message" Where i want my user.first_name to be as a default value for contact_name field. Here is my views.py, where i call for form: def ContactsView(request): form_class = ContactForm(request=request) # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') subjects = form.cleaned_data['subjects'] subjects = dict(form.fields['subjects'].choices)[subjects] # Email the profile with the # contact information template = get_template('threeD/email/contact_template.txt') context = Context({ 'contact_name': contact_name, 'subjects': subjects, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New message from " + contact_name, content, "Message - " + subjects + ' ', ['smart.3d.printing.facility@gmail.com'], headers={'Reply-To': contact_email} ) email.send() messages.success(request, "Thank you for your message.") … -
Django - Change Fields in Group Admin Model
The built-in django group model on the admin site only shows name but I want to include additional fields that are already part of the group model, such as id. I have tried adding these fields using the following admin.py setup: from django.contrib import admin from django.contrib.auth.models import Group class GroupsAdmin(admin.ModelAdmin): pass list_display = ["name", "pk"] class Meta: model = Group admin.site.register(Group, GroupsAdmin) But this returns the error: django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered. I have successfully registered other models (I've created) on admin but the above doesn't work for those models that are already a part of django. How can I add fields in the admin model for Group? -
django (1.11) manytomanyfield templatetags filter
The task is this: There are doctors, there are specializations. A doctor can have several specializations. It is necessary to draw a conclusion of the list of Doctors by specialization. Model: class Doctor(models.Model): title = models.CharField(max_length=200, verbose_name='Имя') slug = models.SlugField(unique=True) image = models.ImageField(null=True, blank=True, verbose_name='Фото') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано') special = models.ManyToManyField('Specialization') experience= models.CharField(max_length=200, verbose_name='Стаж', blank=True) category = models.CharField(max_length=200, verbose_name='Категория', blank=True) content = RedactorField(verbose_name='Контент') keywords = models.CharField(max_length=1024, blank=True, null=True) description = models.CharField(max_length=1024, blank=True, null=True) class Meta: verbose_name = 'Врача' verbose_name_plural = 'Врачи' def __str__(self): # For Python 2, use __unicode__ too return self.slug def get_absolute_url(self): return reverse('show_doctor', kwargs={'slug': self.slug}) class Specialization(models.Model): name = models.CharField(max_length=200, verbose_name='Название') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано') class Meta: verbose_name = 'Специализацию' verbose_name_plural = 'Специализации' def __str__(self): # For Python 2, use __unicode__ too return self.name Templatetags: from django import template from doctor.models import Doctor, Specialization register = template.Library() @register.inclusion_tag('doctors_list.html') def get_doctors_list(request): special_list = Specialization.objects.all() return { 'doctors_list': Doctor.objects.filter(special=special_list), 'spec_list': special_list } HTML Template: {% for s in spec_list %} <h3>{{ s.name }}</h3> <ul> {% for d in doctors_list %} <li><a href="{% url 'doctor_detail' d.slug %}">{{ d.title }}</a></li> {% endfor %} </ul> {% endfor %} Should be: PrtSc . I can not figure it out, help … -
Django: Check if Today in Range of Datetime Object
(Django 1.10 , Python 2.7) I have a year model: class Year(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() election_nomination_start_datetime = models.DateTimeField() election_nomination_end_datetime = models.DateTimeField() I want to make a Middleware -which I've never done before- to check if datetime.today or datetime.now is within the range of dates between election_nomination_start_datetime and election_nomination_end_datetime of any of the Year objects; and accordingly certain pages' accessibility will differ. I have no idea how to execute this, so any help is much appreciated. Also, if an example could be given for using middlewares the way I've described above (limiting access to URLs etc), that would be very beneficial for me. Thank you. -
Access objects inside another class in the current class
I have two classes : From models.py of the perception app @python_2_unicode_compatible class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) and from models.py from the request app @python_2_unicode_compatible class Request(RequestProcess, FolderLinkMixin, TimeStampedModel): folder_auto_create_childs = [] customer = models.ForeignKey('customers.CustomerProfile') request_type = models.CharField( _('Type'), max_length=15, choices=settings.LOANWOLF_REQUEST_TYPE_CHOICES) state = dxmodels.StateField(RequestWorkflow) validation = models.OneToOneField( 'loanwolf.ValidationData', blank=True, null=True) created_by = models.ForeignKey('users.User') rejection_reason = models.CharField( _('Reason of denial'), max_length=250, blank=True, null=True) expires_at = models.DateTimeField(_('Expires at'), blank=True, null=True) copied_from = models.OneToOneField( 'requests.Request', blank=True, null=True, default=None) notes = GenericRelation(Note) contract = models.OneToOneField('contracts.Contract', on_delete=models.SET_NULL, blank=True, null=True, default=None) I would like to access the class variables from Request into the class Perception. I know they are somehow related, because when I type In [3]: Perc = Perception.objects.get(pk=1) In [4]: Perc.loan.request.request_type Out[4]: u'new' For instance, if I want to get access the class variable request_type from Request inside the class Perception, do I have to import the class Request inside the class Perception and insert the line Perc = Perception.objects.get(pk=1) request_type = Perc.loan.request.request_type P.S. Please tell me if the question is unclear. To be clear, … -
Django form self validation not working
My urls.py is something like this : from django.conf.urls import url from django.views.generic import ListView, TemplateView from .models import Dreamreal from . import views urlpatterns = [ url(r'^connection/login/$', views.login), url(r'^connection/$', TemplateView.as_view(template_name = 'login.html')), url(r'^login/$', views.login, name = 'login') ] My views.py is : from .forms import LoginForm from . import models def login(request): username = "not logged in" if request.POST: # GET THE POSTED FORM MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] else: MyLoginForm = LoginForm() return render(request, 'loggedin.html', {'username' : username}) My forms.py is : from django import forms from .models import Dreamreal class LoginForm(forms.Form): username = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) # METHOD TO VERIFY IF USER IS IN DB def clean_message(self): username = self.cleaned_data.get("username") dbuser = Dreamreal.objects.filter(name = 'username') if not dbuser: raise forms.ValidationError("User does not exist in our db!") return username My models.py is : from django.db import models class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = 'dreamreal' My login.html is : <html> <head> <title>LOG IN</title> </head> <body> <form name="form" action="/connection/login/" method="POST"> {% csrf_token %} <div style="max-width: 470px;"> <center><input type="text" name="username" placeholder="username" style="margin-left: 20%;" required> </center> … -
Django Oauth get the users friends list
I am just starting django. I have a basic app set up as seen below. Can somebody guide me step by step in how to set up a facebook Oauth login system and grab the users data.. I want the user to click login, grab their email and friends list ID and redirect the user to another logged in users only page. I also want to print that list to the console(obviously will do stuff with this later). I have my client ID and Secret already. Ive done it a lot easier in flask but i cant grasp how to do it in django. Running Django 1.9.12 -
How to use group option in django form checkbox?
I know how to use CheckboxSelectMultiple in django but when I have groups in choices I don't know how to deal with it. Em.. it's difficult to describe my question in words. Let me take the code below for an example. models.py class MyModel(models.Model): preference = models.CharField(max_length=20, choices=( (u'Fruit',( ('apple',u'Apple'), ('pear',u'Pear'), )), (u'Color',( ('red',u'Red'), ('blue',u'Blue'), )), ) ) forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel filelds = [ 'preference'] widgets = {'preference':forms.CheckboxSelectMultiple} As you can see, if I write MyForm like that, I'll fail to render the options. and I don't want to use ModelMultipleChoiceField. I've read the document again and again but I still couldn't understand how to meet this requirement.. Anybody can help me? Thanks in advance. -
Access objects inside another class in the current class
I have two classes : @python_2_unicode_compatible class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) and @python_2_unicode_compatible class Request(RequestProcess, FolderLinkMixin, TimeStampedModel): folder_auto_create_childs = [] customer = models.ForeignKey('customers.CustomerProfile') request_type = models.CharField( _('Type'), max_length=15, choices=settings.LOANWOLF_REQUEST_TYPE_CHOICES) state = dxmodels.StateField(RequestWorkflow) validation = models.OneToOneField( 'loanwolf.ValidationData', blank=True, null=True) created_by = models.ForeignKey('users.User') rejection_reason = models.CharField( _('Reason of denial'), max_length=250, blank=True, null=True) expires_at = models.DateTimeField(_('Expires at'), blank=True, null=True) copied_from = models.OneToOneField( 'requests.Request', blank=True, null=True, default=None) notes = GenericRelation(Note) contract = models.OneToOneField('contracts.Contract', on_delete=models.SET_NULL, blank=True, null=True, default=None) I would like to access the class variables of Request from the class Perception. I know they are somehow related, because when I type In [3]: Perc = Perception.objects.get(pk=1) In [4]: Perc.loan.request.customer_product Out[4]: <CustomerProduct: Loan: 500.00 $ / Brokerage Fees : 170.00 $> For instance, if I want to get access the class variable customer_product from Request inside the class Perception, do I have to import the class Request inside the class Perception and insert the line Perc = Perception.objects.get(pk=1) In [4]: Perc.loan.request.customer_product -
Testing all django models with one test case
I started writing tests for my django app and I wondered is there a way to test, some functionalities that are the same in more than one model, at the same time. For example if I want to test the __unicode__() method, which comes up in all of my classes, and instead of writing a test for every single model, would it be possible to optimize it and test it once for all models? -
Line breaks causing error in django template parsing
I'm trying to follow the public goods tutorial for oTree, but my templates are giving syntax errors. I'm using vim to edit (and in this case create) the templates, but when I try to run otree resetdb It returns the following error: SystemCheckError: System check identified some issues: ERRORS: public_goods_tutorial: (otree.E008) Template syntax error in /[obfuscated]/oTree/public_goods_tutorial/templates/public_goods_tutorial/Contribute.html 1 | b'' 2 | b'{% extends "global/Page.html %}' -------^ 3 | b'{% load staticfiles otree_tags %}' 4 | b'' 5 | b'{% block title %} Contribute {% endblock %}' 6 | b'' 7 | b'{% block content %}' Error: Could not parse the remainder: '"global/Page.html' from '"global/Page.html' It seems the template linter/parser is choking on the newline/carriage return character at the start of the line (to be clear - the b' characters are "appearing out of nowhere" - they do not appear in the file when I am editing in vim. Having run through the simple survey tutorial and edited template files in that, this problem did not manifest itself. The error is specifically happening on a new file I created rather than (though that may just be coincidence because it is alphabetically first?) I've checked and both encoding and fileencoding for this … -
Add rows in a table using reportlab django
I am using reporlab to generate pdf in my django project. I have multiple data which I want to store in a table format using reportlab. I create a table. But the table shows only first data no further data update in table rows. The table looks like: Inspection_Id | Licence_Plate | Images | Comment 100 | TEST | http://www.test.com/image.jpg | Qwerty Code Snippet is Below: from django.http import HttpResponse from rest_framework import generics from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, cm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, Table, TableStyle from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER from reportlab.lib import colors class DamageExportViewSet(generics.ListAPIView): renderer_classes = [PDFRenderer,] def get(self, request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Damage Report File.pdf"' width, height = A4 styles = getSampleStyleSheet() styleN = styles["BodyText"] styleN.alignment = TA_LEFT styleBH = styles["Normal"] styleBH.alignment = TA_CENTER def coord(x, y, unit=1): x, y = x * unit, height - y * unit return x, y inspection = Paragraph('''<b>Inspection Id</b>''', styleBH) licplt = Paragraph('''<b>Licence Plate</b>''', styleBH) imgs = Paragraph('''<b>Images</b>''', styleBH) cmnts = Paragraph('''<b>Comments</b>''', styleBH) buffer = BytesIO() p = canvas.Canvas(buffer, pagesize=A4) p.drawString(20, 800, "Report generated at " + timezone.now().strftime('%b %d, %Y %H:%M:%S')) damage_data = Damage.objects.all() try: for i in …