Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help to fetch required data from model in django
I have below two models, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) class share_files(models.Model): select_file = models.CharField(max_length=300) from_user = models.CharField(max_length=50) select_user = models.CharField(max_length=50,default=None) user_files stores file uploaded by respective user. and share_files stores shared file name yo user xx by user bb. I want to show shared files with logged in user in template, my function for it in view.py is, def user_files_all(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: data = user_files.objects.filter(user_uploaded=request.user) data1 = share_files.objects.filter(select_user=request.user) data2 = user_files.objects.filter(Filename=data1.select_file,user_uploaded=data1.from_user) args = {'data': data,'data1':data1} return render(request, 'accounts/files.html', args) but i am getting error for line, data2 = user_files.objects.filter(Filename=data1.select_file,user_uploaded=data1.from_user) as attribute select_file is not present for data1. I want data from user_files model for all users and filename selected in data1. And then want to render that in template. How to achieve that? Need help. Thanks in advance. -
Cannot install Django 2 Beta 1 on Ubuntu Server 16.04
I'm trying to install Django 2 beta 1 on an Ubuntu Server 16.04 using the command line shown on Django's download page without success. The given command line is: pip install --pre django but when I run it, it is trying to install Django 1.11.6. (Downloading Django-1.11.6-py2.py3-none-any.whl (6.9MB)) Does anyone know how I can successfully install the beta ? -
How to update django admin changelist view context from ajax called?
I customized django admin changelist view with FullCalendar template, I would like to display my event when I click prev or next month button, but I cannot figure out how to update data back from changelist_view method. view.html $('.fc-prev-button').click(function(){ var d = $('#calendar').fullCalendar('getDate'); var currentYear = d.year(); var currentMonth = d.month()+1; $.ajax({ url: window.location.href, method: "get", data: { currentYear: currentYear, currentMonth: currentMonth }, success: function(e) { alert('success!'); } }); admin.py def changelist_view(self, request, extra_context=None): ... response = super(BookingAdmin, self).changelist_view( request, extra_context=extra_context ) # get current datetime currentYear = currentMonth = 0 if 'currentYear' in response.context_data: currentYear = response.context_data['currentYear'] if 'currentMonth' in response.context_data: currentMonth = response.context_data['currentMonth'] now = datetime.datetime.now().strftime('%Y-%m-01') if currentYear == 0 and currentMonth == 0 else datetime.date(currentYear, currentMonth, 1).isoformat() response.context_data['now'] = now # fetch booking after today qs = response.context_data['cl'].queryset bookings = qs \ .extra(select={'ci_date':"to_char(checkin_date, 'YYYY-MM-DD')", 'co_date':"to_char(checkout_date, 'YYYY-MM-DD')"}) \ .filter(checkin_date__gt=now).order_by('checkin_date') response.context_data['bookings'] = bookings return response error AttributeError: 'HttpResponseRedirect' object has no attribute 'context_data' I don't know if this is the correct way to do ajax in Django, need some hints to solve it out, thank you so much! -
Django get user by generic USERNAME_FIELD
Is there a nice way to get a user from Django User model making a query with the generic USERNAME_FIELD instead? In other words, instead of: User.objects.get(username='my_user') or User.objects.get(email='test@user.com') I would like to do something like: User.objects.get(User.USERNAME_FIELD=a_username_variable) Obviously, the latter throws a SyntaxError, but I am asking if there is a way to query based on USERNAME_FIELD -
%s must be from the same graph as %s with Tensorflow and django
I use the web framework Django to render service.I debug the code in the local,and it returns the correct result.However,it throws an exception when I post the data with fiddler. the code is below: from PIL import Image import numpy as np import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import random import base64 import io as stringIOModule from io import BytesIO IMAGE_HEIGHT = 50 IMAGE_WIDTH = 223 MAX_CAPTCHA = 5 CHAR_SET_LEN = 36 alphabet = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def vec2name(vec): name = [] for i in vec: a = alphabet[i] name.append(a) return "".join(name) X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT*IMAGE_WIDTH]) Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA*CHAR_SET_LEN]) keep_prob = tf.placeholder(tf.float32) # define CNN def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1): x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1]) # 3 conv layer w_c1 = tf.Variable(w_alpha * tf.random_normal([5, 5, 1, 32])) b_c1 = tf.Variable(b_alpha * tf.random_normal([32])) conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1)) conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') conv1 = tf.nn.dropout(conv1, keep_prob) w_c2 = tf.Variable(w_alpha * tf.random_normal([5, 5, 32, 64])) b_c2 = tf.Variable(b_alpha * tf.random_normal([64])) conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2)) conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') conv2 = tf.nn.dropout(conv2, keep_prob) w_c3 … -
NoReverseMatch while using get_absolute_url in Django
Error Trace: NoReverseMatch at /search/ Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=mur Django Version: 1.11.6 Exception Type: NoReverseMatch Exception Value: Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. URL Conf: url(r'^about/(?P<slug>[-\w]+)$', about_pages, name="about_pages") Model: class Book(models.Model): slug = models.SlugField(default = "") def get_absolute_url(self): reverse("about_pages", kwargs = {"slug" : self.slug}) Template: {% for result in results %} <a href = {% url result.get_absolute_url %}>{{result.name}}</a> {% endfor %} Is my regex alright? I feel its generating the url correctly but not finding a matching pattern in URLConf to navigate to a view. -
Django template block code does not work when included as a snippet
I want to change the state of the navbar as highlighted in different pages. When I am normally placing the nav-bar in base.html and add a block content it works. <!DOCTYPE html> <html lang=en> <head> <title>Dashboard</title> {% include 'snippets/css.html' %} </head> <body> <!-- Sidebar Holder --> <nav id="sidebar"> <ul class="list-unstyled components"> <li{% block nav_live %}{% endblock %}> <a href="{% url 'live_now' %}"><i class="fa fa-users" aria-hidden="true"></i>Live Now</a> </li> <li{% block nav_out %}{% endblock %}> <a href="{% url 'outcome' %}"><i class="fa fa-crosshairs" aria-hidden="true"></i>Outcome Score</a> </li> <li {% block nav_customer %}{% endblock %}> <a href="{% url 'customer_search' %}"><i class="fa fa-search" aria-hidden="true"></i>Customer search</a> </li> <li {% block nav_journey %}{% endblock %}> <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false"><i class="fa fa-map-o" aria-hidden="true"></i> Journey Shaping</a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li><a href="{% url 'persona' %}">-Persona</a></li> <li><a href="#">-Outcomes</a></li> <li><a href="#">-Action Maps</a></li> <li><a href="#">-Auto Responses</a></li> </ul> </li> <li {% block nav_analytics %}{% endblock %}> <a href="#analyticsmenu" data-toggle="collapse" aria-expanded="false"><i class="fa fa-bar-chart" aria-hidden="true"></i>Analytics</a> <ul class="collapse list-unstyled" id="analyticsmenu"> <li><a href="#">-Visitor Activity</a></li> <li><a href="#">-Visit History</a></li> <li><a href="#">-Action Map Performance</a></li> <li><a href="#">-Interactions</a></li> </ul> </li> <li{% block nav_settings %}{% endblock %}> <a href="#settingsmenu" data-toggle="collapse" aria-expanded="false"><i class="material-icons md-18" >tune</i>Settings</a> <ul class="collapse list-unstyled" id="settingsmenu"> <li><a href="{% url 'set_phone' %}">-Phone Number</a></li> <li><a href="{% url 'track_code' %}">-Tracking Code</a></li> <li><a href="#">-Action Map Performance</a></li> … -
Django weasyPrint fontconfig error
I have an application that I need to get pdf files from so I opted for weasyprint but after installing with PIP I imported import weasyprint I got an error in terminal OSError: ctype.util.find_library() did not manage to locate a library called fontconfig Then I tried to use from weasyprint import HTML, CSS from weasyprint.fonts import FontConfiguration I still got the same error. Without writing any further codes the import statements is stuck on the error. I’m running the lates django and weasyprint as of October. Thanks in advance -
Remove "django_ct" foreign key constraint from haystack queries
I have an existing SQL base, which is indexed by Solr. I want to use haystack, because of its abstraction and object creation from queries. The problem is that the haystack search forms and SearchQuerySet always add &fq=django_ct:(appname.model) to the query. Is there a way to remove this from the generated query. There is a way to rename it, but i did not find any way to remove it at all. This query always fails, because there isn't any fq which is called django_ct and why does it has to be there in the first place ? -
AttributeError at /login/ 'WSGIRequest' object has no attribute 'get' in Django
Ok more on forms. I have finally got my form to validate, post and redirect to page it needs to. Now my issue is when I return to the page with the form I get this error: python manage.py runserver I am facing issue. when i run python manage.py runserver getting error :- AttributeError at /login/ 'WSGIRequest' object has no attribute 'get' django version :- 1.5.2 views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required(login_url="login/") def home(request): return render(request,"home.html") app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), ] main urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from log.forms import LoginForm urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('log.urls')), url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}), url(r'^logout/$', views.logout, {'next_page': '/login'}), ] login.html {% extends 'base.html' %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} … -
Django join tables to show data on the intersection between rows and columns
I've two class models, in which the first one (Activity) is prefilled by the admin, while the second (workingDays) is used as an input form to be filled by the website users, as follows: class Activities(models.Model): activity= models.CharField(primary_key= True, max_length= 300) provider= models.CharField(max_length= 50) activity_id= models.CharField(max_length= 50) class WorkingDays(models.Model): user = models.ForeignKey(User) activity= models.CharField(choices=labels, max_length=200) activity_id = models.CharField(max_length=25) worked_hours= models.FloatField(max_length=3) worked_days = models.FloatField(max_length=2) I need to render a view template with the "user" on the column tags, "activity" on the rows, and the number of worked_hours on the intersection as follows: ------------------------------------------ Activity | user1 | user2 | user3 | user4| ------------------------------------------ act1 | 12 | | 10 | | ------------------------------------------ act2 | | 20 | 10 | 10 | ------------------------------------------ act3 | 5 | | 10 | 14 | ------------------------------------------ Any help using Django-ORM or django-tables ? -
Creating a API test environment in Django
I am in need of creating a test environment for a Django app. My app provides some REST APIs and it does http requests to other external APIs. In production, there is no problem. However, during development, my app needs to be able to provide fake responses by mocking the responses from external APIs, so that it should not rely on the external API server being up or down. I don't want to make my app code dirty. So, checking DEBUG=True and sending response is not a solution. After thinking for a while I came to a theoretical solution: Write a middleware which does the mocking work. But, I have not been able to make this work out. Can anyone provide me how to do this, or any other ways of creating a test server which does not have to rely on external API server and network issues? -
apps/goods/models.py 'apps.goods.models' apps is not package?
my project directories is: apps/ goods/ models.py views.py base.py trades/ users/ __init__.py apps/goods/base.py from django.views.generic.base import View from apps.goods.models import Goods class GoodsListView(View): def get(self, request): json_list = [] goods = Goods.objects.all()[:10] for good in goods: # json_dict = {} # json_dict['name'] = good.name # json_dict['category'] = good.category.name # json_dict['market_price'] = good.market_price # json_dict['add_time'] = good.add_time # json_list.append(json_dict) from django.forms.models import model_to_dict for good in goods: json_dict = model_to_dict(good) json_list.append(json_dict) from django.http import HttpResponse import json return HttpResponse(json.dumps(json_list), content_type='application/json') i'm debug base.py not get data, but get the error: from apps.goods.models import Goods ModuleNotFoundError: No module named 'apps.goods'; 'apps' is not a package and, i remove 'apps' in 'apps.goods.models', get the error: from goods.models import Goods ModuleNotFoundError: No module named 'goods' env: pycharm-2017.2 django-1.11.6 why get the error? -
Django - which are the permitted filters in if condition in a template? slice and first seems not working
I am getting the partition info and send it to template, in a <table>. If a partition's used percentage is above 90%, the percentage should be in red. Because there are more than one partition in the machine, so the conditional style of rows are independent, so it is better to decide when rendering, not in the view. The percentage come as integer (89), not in decimal(0.7). If it is decimal, I can use {% if '0.9' in value %}, but it is not the case. I have my template like this: (part.0 to part.4 are other data about partitions) <tbody> {% for part in partitions %} <tr> <td>{{part.0}}</td> <td>{{part.1}}</td> <td>{{part.2}} GB </td> <td>{{part.3}} GB </td> <td>{{part.4}} GB </td> {% if part.5|slice:"0:1" == "8" or part.5|slice:"0:1" == "9" %} <td><font color="red">{{part.5}}%</font></td> {% else %} <td>{{part.5}}%</td> {% endif %} </tr> {% endfor %} </tbody> Now, it does not complain, but does not turn red neither when the data matches the condition. In the documentation, I see this frase: Filters You can also use filters in the if expression. For example: {% if messages|length >= 100 %} You have lots of messages today! {% endif %} But, it mentions no other filters … -
Exporting data with dumpdata when using django-taggit
I am using django-taggit for tags, and would like to get my data from a development instance of my app to my production instance. Currently, I am using manage.py dumpdata and loaddata with natural keys to export and import the data. The problem is that this leaves out the tags. I could tell dumpdata to include the taggit app, but that doesn't use natural keys - so if the IDs are different on the server (they will be), then the data doesn't match up. I've tried to achive custom serialisation by subclassing TaggableManager and adding serialize=True and a custom value_to_string method. The idea was to serialize tags as a comma separated string, but this didn't do anything. Any idea how I can serialize my tags, so I can move data between databases? -
Access Apache 2.4's localhost from another system in same network
I am running a Django application on Apache2.4 server. I wish to access the page http://localhost:8081/home from another system. I'm in a corporate environment so both server and client machine will be inside a same private network. So the issue is, I am being able to access the page by using the server IP address, on the server machine (http://xx.xx.xx.xx:8081/home ) but the page is not being loaded when I use it on the client machine. ( similarly, I can access the page as systemname.dns.com:8081/home from server machine but not from client machine) So what can exactly be my problem and how can I solve it? Modified part of httpd.conf: LoadFile c:/users/username/appdata/local/programs/python/python36/python36.dll LoadModule wsgi_module c:/users/username/lms/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd WSGIScriptAlias / c:/users/username/lms/LMS/wsgi.py WSGIPythonHome c:/users/username/lms WSGIPythonPath c:/users/username/lms <Directory "C:/Users/username/lms"> <Files wsgi.py> Require all granted </Files> </Directory> -
About forms and instance
Sometimes, I have to display multiple checkbox to check or uncheck some items. So the form could have some checkbox already checked. To do this, I use form = myform(instance=manyTomanyField). The problem here, I can't do it because my many to many field has a through parameter : games = models.ManyToManyField(Games, through="Relation" verbose_name="Jeu") Indeed, I'm using through="Relation". That's why I have this error message : AttributeError at /team/recruitment/ 'ManyRelatedManager' object has no attribute '_meta' views.py : def view_team_recruitment(request): if request.user.is_authenticated(): media = settings.MEDIA form = TeamRecruitmentForm(instance=Team.objects.get(owner=request.user).games) Models.py : class Team(models.Model): name = models.CharField(max_length=15, null=False) tag = models.CharField(max_length=4, null=False) description = HTMLField(blank=True, null=True, default='') logo = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True) games = models.ManyToManyField(Games, through="Relation", verbose_name="Jeu") owner = models.ForeignKey(User, verbose_name="Créateur", related_name='myteam') date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.name class Relation(models.Model): on_team = models.ForeignKey(Team, verbose_name="Equipe") on_game = models.ForeignKey(Games, verbose_name="Jeu") on_plateform = models.ForeignKey(Plateform, verbose_name="Plateforme") recruitment = models.BooleanField(default=True) class Plateform(models.Model): name = models.CharField(max_length=100, unique=True, null=False, verbose_name="Plateforme") guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="Abréviation") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.name class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.FileField(upload_to='media/games/', validators=[validate_file_extension], blank=True, … -
the meaning of API in Model class API - django
I could not get the meaning of API in Model class. I understand the definition of REST API thoroughly, In fact, I study a book in django in which a statement I encountered is This document contains all the API references of Field including the field options and field types Django offersand I think this API is different from REST API. Model API reference document: https://docs.djangoproject.com/en/1.11/ref/models/ -
Issue with Synapse API retreiving user nodes - django/python
I am working on a django app and I am integrating SynapsePay API into my project. I am having an issue with the retrieval of the nodes list. The main issue is that the api is supposed to responds in json format, but it is returning a class / set of lists. Does anyone know how to correctly integrate this part and send this request and response.... Here is my code and the response. def listedLinkAccounts(request): # the following grabs the currenly logged in users record and profile within # the application currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user = currentUser) # the following will grab the users synapse id from the users local profile. user_id = currentProfile.synapse_id print(user_id) # the following will grab the entire synapse profile by sending an api request # with the users synapse profile. synapseUser = SynapseUser.by_id(client, str(user_id)) # the following are options for how to display and structure the response for # all of the different nodes linked to the users account options = { 'page':1, 'per_page':20, 'type': 'ACH-US', } # the following is the request and response with all of the users linked nodes # ready to be processed and storage of certain information. … -
Whats the default permissions generator automatically of a model?
When I create a model: class Info(models.Model): name = models.CharField(max_length=26) detail = models.CharField(max_length=16) class Meta: permissions = ( ("add_info", "Can view info"), # C ("read_info", "Can view info"), # R ("update_info", "Can update info"), # U ("delete_info", "Can delete info") # D ) When I makemigrations, but there comes error: app07.Info: (auth.E005) The permission codenamed 'add_info' clashes with a builtin permission for model 'app07.Info'. app07.Info: (auth.E005) The permission codenamed 'delete_info' clashes with a builtin permission for model 'app07.Info'. So, when I create a user the model will create permissions automatically. But you see, the READ and UPDATE permissions are not read_info and update_info, so whats the default permissions of a model? -
Run django api from postman: CSRF verification failed
I'm trying to run an api using postman. My application is developed in django 1.11.6 using python 3.5. My app is installed on an ubuntu server. These are the steps that I follow: Click on "import" tab on the upper left side. Select the Raw Text option and paste my cURL command. Hit import and I have the command in your Postman builder Press send button. My curl command is: curl -i -H 'Accept: application/json; indent=4' -X POST https://127.0.0.1/users/:register/ -d "id=111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames=" The error I get is Forbidden (403) - CSRF verification failed. Request aborted. When I run the curl command via cygwin, it's working properly. This is the view function that I'm using: class ApiUserRegister(APIView): permission_classes = () serializer_class = RegisterUserSerializer def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint serializer.is_valid(raise_exception=True) data = serializer.data if User.objects.filter(id=data['id']).exists(): user = User.objects.get(id=data['id']) is_new = "false" resp_status = status.HTTP_200_OK else: user = User.objects.create(id=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], lastname=data['lastname'], othernames=data['othernames']) user.save() is_new = "true" resp_status = status.HTTP_201_CREATED resp = {"user": serializer.get_serialized(user), "isnew": is_new} return Response(resp, status=resp_status) -
get a file with API and map to database in django framework
I am using django with python 3. I want to create a REST-API that get's a file and map's it to the database. The data in the file is not JSON but it's CSV. Thank's for any help -
The Core of Django is a modern string format:` "{ }".format(dict)`
I am newbie to Django for a month.it prompts me to think that Django's core is python's modern string format. "{key}".format(dict) #Compare to render(request, name_of_a_string_of_html, dict) as for iteration and condition: {% if %}{% endif %} {% for in %} {% endfor %} % if % is 'open html tag' imitating <p>. the outer {} is modern string format symbol. % endif % is close tag For {{ variable }} is the same, the inner is html tag while the outer is string modern format symbol. Does my understanding hit the core or wrong technically? -
logic to integrate Django REST framework in existing app
I've a set of django Class based views: CreateView, UpdateView, etc.. with crispy-forms. I've looked at documentation of DRF and seen viewsets.ModelViewSet that make the api page available instead of createview and updateview. Now I miss how I can assign my old crispy-form to the api view. I can convert my previous views with forms to call the new modelviewset? In the first page of documentation it talk about crispy-form, but I cannot find an example. Thanks, BR -
Hindi font is not displaying correct words in the created pdf using python reportlab pdf library
I am using on reportlab pdf library in django framework in order to create pdf reports in hindi language.I am getting data from PostgreSql database as mention below format. waterdate month year rivername stationname distname 2011-06-22 00:00:00 June 2011 नयार मरोरा पौड़ी 2011-06-22 00:00:00 June 2011 गंगा हरिद्वार हरिद्वार 2011-06-22 00:00:00 June 2011 गंगा नरोरा/डी0एस0 बुलन्दशहर 2011-06-22 00:00:00 June 2011 गंगा फतेहगढ़ फर्रूखाबाद 2011-06-22 00:00:00 June 2011 गंगा गुमटिया कन्नौज I have written following code to display above table into pdf file. printing.py from reportlab.lib.pagesizes import letter,A4 from reportlab.platypus import SimpleDocTemplate,Paragraph,Table,TableStyle from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_CENTER,TA_JUSTIFY from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from .models import Rainfall pdfmetrics.registerFont(TTFont('Hindi1', 'gargi.ttf')) class printReport: def rainfall_report(self): buffer = self.buffer doc = SimpleDocTemplate(self.buffer,rightMargin=10,leftMargin=10,topMargin=25,bottomMargin=25,pagesize=self.pagesize) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name="TableHeader",alignment=TA_CENTER,)) styles.add(ParagraphStyle(name="ParagraphTitle", fontSize='11',alignment=TA_JUSTIFY,fontName="FreeSansBold")) styles.add(ParagraphStyle(name="Justify", fontSize='11',alignment=TA_JUSTIFY,fontName="FreeSansBold")) data = [] data.append(Paragraph( 'Rainfall Data', styles['Title'])) data.append(Spacer(1,12)) table_data =[] table_data.append([ Paragraph('Date', styles['TableHeader']), Paragraph('Month', styles['TableHeader']), Paragraph('Year',styles['TableHeader']), Paragraph('River Name',styles['TableHeader']), Paragraph('Station Name',styles['TableHeader']), Paragraph('District Name',styles['TableHeader']) ]) rainfall_data = Rainfall.objects.all()[:10] for rainfall in rainfall_data: table_data.append([ rainfall.waterdate, rainfall.month, rainfall.year, rainfall.rivername, rainfall.stationname, rainfall.districtname ]) user_table = Table(table_data,colWidths=[doc.width/7.0]*7) user_table.hAlign = 'CENTER' user_table.setStyle(TableStyle( [ ('INNERGRID', (0,0), (-1,-1), 0.25 , colors.black), ('BOX',(0,0),(-1,-1,),0.5, colors.black ), ('VALIGN',(0,0),(-1,0), 'MIDDLE'), ('BACKGROUND',(0,0),(-1,0), colors.gray ), ('TEXTCOLOR', (0,1), (-1,-1), colors.black), ('VALIGN',(2,1),(-3,-1),'MIDDLE'), ('ALIGN',(0,1),(-1,-1),'CENTRE'), ( 'FONT' …