Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON array only defined if invoked in function from Django - Not passed as argument?
Using Django, I'm passing a JSON array to my template as a string, then converting it back to JSON with JSON.parse. In an effort to clean up my code I would like to pass the JSON array into a function as an argument, versus' currently invoking it in the middle of the function. Here is the code as it is now, in the Django template: // Create Google Map function createMap() { var sampleList = JSON.parse('{{ samplesJson | escapejs}}'); var plotList = JSON.parse('{{ plotsJson | escapejs}}'); console.log(sampleList.length); } And here is the code as it is output client-side: // Create Google Map function createMap() { var sampleList = JSON.parse('[{\u0022id\u0022: 54, \u0022title\u0022: \u0022Test Sample 1\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:14:30.345076+00:00\u0022, \u0022coordinates\u0022: \u002245.58837890625, \u002D122.39273834228516\u0022, \u0022type_primary\u0022: \u0022Brix\u0022, \u0022value_primary\u0022: 15.52022647857666, \u0022type_secondary\u0022: \u0022Dry Matter\u0022, \u0022value_secondary\u0022: 16.35165786743164}, {\u0022id\u0022: 55, \u0022title\u0022: \u0022Test Sample 2\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:15:01.127750+00:00\u0022, \u0022coordinates\u0022: \u002245.58849334716797, \u002D122.39277648925781\u0022, \u0022type_primary\u0022: \u0022Brix\u0022, \u0022value_primary\u0022: 16.902915954589844, \u0022type_secondary\u0022: \u0022Dry Matter\u0022, \u0022value_secondary\u0022: 17.531015396118164}]'); var plotList = JSON.parse('[{\u0022id\u0022: 124, \u0022title\u0022: \u0022Test Plot\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:13:29+00:00\u0022, \u0022coordinates\u0022: \u0022[ {lat: 45.58871801349195,lng: \u002D122.3925570656067}, {lat: 45.58834260811055,lng: \u002D122.39249269259034}, {lat: 45.588297559296066,lng: \u002D122.39322225344239}, {lat: 45.58874804581401,lng: \u002D122.39320079577027}]\u0022, \u0022crop\u0022: \u0022Mango\u0022, \u0022samples\u0022: \u0022[54, 55]\u0022, \u0022aggregate\u0022: {\u0022Brix\u0022: 16.211571216583252, \u0022Dry Matter\u0022: 16.941336631774902}}, {\u0022id\u0022: 125, \u0022title\u0022: \u0022Test Plot 2\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 14:02:15.820832+00:00\u0022, \u0022coordinates\u0022: \u0022[\u005Cn {lat: 45.588755567618534,lng: \u002D122.39336172831116},\u005Cn … -
Got this UnboundLocalError at /nesting/ local variable 'content' referenced before assignment
I want to display the necessary field errors when the user who is populating the form does not enter valid information into the forms. However, each I time I test the error script by clicking the submit button without populating any of the fields I get this error : UnboundLocalError at /nesting/ local variable 'content' referenced before assignment How do I correct this? This is my code : veiws.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from nesting.forms import Identity_form from nesting.models import Identity_unique class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_form() Identities = Identity_unique.objects.filter(user = request.user) var = {'form': form, 'Identities': Identities} return render(request, self.template_name, var) def post(self, request): form = Identity_form(request.POST or None) if form.is_valid(): NIS = form.save(commit = False) NIS.user = request.user NIS.save() content = form.cleaned_data['NIS'] form = Identity_form() return redirect('nesting:nesting') The error messages is saying the error is caused by this line var = {'form': form, 'content': content} return render(request,self.template_name, var) nesting.html {% extends 'base.html' %} {% load widget_tweaks %} <html> <head> {% block head %} <title>nesting</title> {% endblock %} </head> <body> {% block body %} <div class = "container" style = "margin-top: 80px;"> <form method = 'post' novalidate> {% csrf_token … -
Using Python for real time scalable application
me and a friend are doing requirements survey for a project, and this project have one base feature that is in real-time, so we are searching for NoSQL solutions with python to build an API and we passed by Flask, Django Rest with mongo and Eve. And here we are asking for some insights about frameworks and recomentations to start with. We expect to build a stable and medium to large scale app. If anyone could help, we'll be grateful a lot. -
Django 1.11 don't include login.app
I have a problem with my login app, when I configure the logout in urls.py the traceback tell me the next: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10fc44510> Traceback (most recent call last): File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/dmuino/.virtualenvs/Pruebas/CursoProDjango/eventus/eventus/urls.py", line … -
querying a self referencing table in Django
I have a model which references itself so that I have a parent / child relationship between users in the db. A parent can have multiple children, but a child can only have one parent. Firstly, is this the correct way to define the model: class User(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self') Secondly, I need to query the model and return all the children of a particular parent. I have read some articles on tree structures where queries can be more complicated. But given I only need one layer deep, will this return all the children: children = User.objects.get(parent=PARENT_ID) where PARENT_ID is obviously the id of the parent -
How to loop through a dic value in python template
I am new to Python/Django development, i want to loop through a dic value that i am sending from my view on my template but i can't get the value base on index/key. Kindly help me out. My View def contact(request): contactDetails = {'name': ['Adeola Ajayi', 'Olayemi'], 'email': ['a@gmail.com', 'b@gmail.com']} return render(request, 'PythonWeb/contact.html', {'contactDetails':contactDetails}) My Template {% block content %} <br><br> {% for contact in contactDetails%} <p> name: {{ contact.name }} </p> <p> name: {{ contact.email }} </p> {% endfor %} {% endblock %} This is how i want my template to display name: Adeola Ajayi email: a@gmail.com name: Olayemi email: b@gmail.com -
how to connect django and vue.js webpack?
i work with django rest_framework and recently i should work with vue.js and i wanna a good tutorial for django + vue.js. please help me to find a good refrence. i am so confused. i already see this links https://www.youtube.com/watch?v=C7oiYr4_NdUa var cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } -
Possible to have multiple serializers per view using Django Rest Framework
As I'm working, my ./views.py is becoming really competitive and I'm wondering if there is a way to refactor it to be DRY. I think in order to do so, I would need the ability to use specify multiple serializers per view. data would need to be less ambigious so that it actually describes the data it is receiving so that it can be passed into the correct serializer, which would mean it would need to know the API route the received data came from. Not sure how to do that except with a one class per route, how I currently have it setup. Then there would need to be a way to specify multiple serializers in a view to send the respective data to. Not seeing that this is possible. # ./urls.py from .views import ( SecurityQuestionsAPIView, UserSigninTokenAPIView, UsernameRecoveryAPIView, ValidateKeyAPIView ) urlpatterns = [ url(r'^signin/', UserSigninTokenAPIView.as_view(), name='signin'), url(r'^verify/', verify_jwt_token), url(r'^refresh/', refresh_jwt_token), url(r'^username_recovery/', UsernameRecoveryAPIView.as_view(), name='username_recovery'), url(r'^validate_key/', ValidateKeyAPIView.as_view(), name='validate_key'), url(r'^security_questions/', SecurityQuestionsAPIView.as_view(), name='security_questions'), ] # ./views.py from .serializers import ( SecurityQuestionsSerializer, UserSigninTokenSerializer, UsernameRecoverySerializer, ValidateKeySerializer ) # Used for logging into the web application class UserSigninTokenAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserSigninTokenSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserSigninTokenSerializer(data=data) … -
read file csv in memory django python
Hi I am reading a csv with open (' file. csv', r) this for a file stored in disk now I would like to read the file without having to be uploaded only in memory I tried this, but it gives me a mistake: file = request. File[' file'] open (file, r) in django python as I can do? -
FileNotFoundError when using django.test.client.post
I had some django test code that used to work in python 2 but started throwing some errors in python3. Here's a snippet: def test_filter(self): c1 = dt.Client() c1.login(username='user1', password='pass') f = open('data/tiny.txt', 'rb') test_file = { 'datafile': f, 'uid': 'bb', 'private': 'True', 'name': "tr1" } response = c1.post( '/api/v1/files', test_file, format='multipart' ) When I run this using python3 I get the following Exception: Exception ignored in: <bound method _TemporaryFileCloser.__del__ of <tempfile._TemporaryFileCloser object at 0x115904160>> Traceback (most recent call last): File "/Users/pete/miniconda3/envs/cenv3/lib/python3.6/tempfile.py", line 450, in __del__ self.close() File "/Users/pete/miniconda3/envs/cenv3/lib/python3.6/tempfile.py", line 446, in close unlink(self.name) FileNotFoundError: [Errno 2] No such file or directory: '/var/folders/yb/3jwdnlf17gd1dcq65th786d00000gn/T/tmpw_t0j9bw.upload' Interestingly, this exception doesn't affect the outcome of the tests. They still pass. It does get reported in the output and is rather annoying. Any ideas on what's causing this? Creating the object with a file using Object.create works fine and doesn't throw an error. -
How to get invoice_id from PayPal after success transaction
I want to get invoice_id that i send to PayPal. I send to PayPal invoice_id: ... <input type="hidden" name="invoice" value="MyOrderId" id="id_invoice"/> ... My success url looks like this: http://host?success=true I want to catch GET parameter success and edit some Order with id=invoice_id: ... if request.method == 'GET': if request.GET.get('success'): order = Order.object.get(id=request.GET.get('invoice_id')) order.status = 'Success' order.save() ... Maybe i need say to PayPal that i want to get returned invoice_id from it, or where i can find it and get? -
How to filter backward joins?
I have a model Article and several ArticleDescription (one for each language). class Article(models.Model): articleid = models.CharField(primary_key=True, max_length=100) def __unicode__(self): return str(self.articleid) class ArticleDescription(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) lang = models.CharField(max_length=2, default='en', blank=False, null=False) description = models.TextField(blank=True, null=True) class Meta: unique_together = ('article', 'lang') def __unicode__(self): return str(self.description) I am struggling now how to make a join to select only the current language's description in my template. I use this code to get my articles: c = models.Article.objects.all().order_by('articleid') In c, I have my ArticleDescriptions available in my template like this: {% for b in c %} {{ b.articledescription_set.all }} {% endfor %} But, I do not want all the descriptions, just the one for the current language. So I am looking for something like: c = models.Article.objects.all().join(ArticleDescription, lang=curlang).order_by('articleid') and then I can use the description like this in my template: {% for b in c %} {{ b.articledescription.description }} {% endfor %} But, I have no idea how to do this, or where to look. -
Django - Attach PDF generated by a view to an email
This question has some elements here, but no final answer. There is view generating a PDF with easy_pdf from easy_pdf.views import PDFTemplateResponseMixin class PostPDFDetailView(PDFTemplateResponseMixin,DetailView): model = models.Post template_name = 'post/post_pdf.html' Then, I want to attach this generated PDF to the following email : @receiver(post_save, sender=Post) def first_mail(sender, instance, **kwargs): if kwargs['created']: user_email = instance.client.email subject, from_email, to = 'New account', 'contact@example.com', user_email post_id = str(instance.id) domain = Site.objects.get_current().domain post_pdf = domain + '/post/' + post_id + '.pdf' text_content = render_to_string('post/mail_post.txt') html_content = render_to_string('post/mail_post.html') # create the email, and attach the HTML version as well. msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach_file(post_pdf, 'application/pdf') msg.send() I also have tried this one: msg.attach_file(domain + '/post/' + post_id + '.pdf', 'application/pdf') -
All django databases are deleted
Because I deleted the mysql file by mistake last time, I can't use any database, including django, how to recover all the data tables of django **django==1.9.8** **python==3.5.2** This is my profile -
How to sort queryset by annotated attr from ManyToMany field
Simplest example: class User(models.Model): name = ... class Group(models.Model): members = models.ManyToManyField(User, through='GroupMembership') class GroupMembership(models.Model): user = ... group = ... I want to get list of Groups ordered by annotated field of members. I'm using trigram search to filter and annotate User queryset. To get annotated users I have something like that: User.objects.annotate(...).annotate(similarity=...) And now I'm trying to sort Groups queryset by Users' "similarity": ann_users = User.objects.annotate(...).annotate(similarity=...) qs = Group.objects.prefetch_related(Prefetch('members', queryset=ann_users)) qs.annotate(similarity=Max('members__similarity')).order_by('similarity') But it doesn't work, because prefetch_related does the ‘joining’ in Python; so I have the error: "FieldError: Cannot resolve keyword 'members' into field." -
TypeError: view must be a callable or a list/tuple in the case of include
First off I apologize for asking this question again as apparently others have. I am having trouble with this and have been receiving the error that you see in the title of the post. I'm following along with the tutorial and have understood it up to this point. I'm not even really sure what the method does. So first off if someone can answer that it would be appreciated. Secondly, how do I fix that error. I realize I must have Django's old syntax. How would I fix that? views.py(I created this file under my root directory) from django.shortcuts import render def index(requests): return render(request, 'index.html', {}) urls.py (also under root directory) urlpatterns = { url(r'^$', 'post.views.index'), url(r'^admin/', admin.site.urls) I have an html file called index is in my template/layout Thanks to anyone who might be able to help. I realize this is probably a total noob question. -
How to parse (Decimal('str'),) with python
in my view i make a call to a stored procedure that return to me the ID of the entry it created. I need to use this id as arguments for another stored procédure. My problem is that the result of the first query is : (Decimal('1046'),) and of course wont fit as argument for the second procedure. How can i parse it to only get the '1046' ? -
I am getting this error Forbidden (csrf token missing or incorrect.)
I am fairly new to python/django. But my code has been running perfectly fine. And now I am suddenly getting this error. My code is about file upload. I have added {% csrf_token %} in the view. The "django.middleware.csrf.CsrfViewMiddleware" is in the settings file. And I am returning the response with the render () function. Is there anything that I need to check on? I have been running/testing this code for a week or so and now suddenly this error is popping up. I am not sure how to debug it. Thanks in advance, Vrunda -
Django Forms - Custom Date Input
I am having an issue clearing a date through the following form: class CreateArtistProfile(forms.ModelForm): focus_str = forms.CharField() birthdate = forms.DateField(input_formats="%d %B, %Y") occupation = forms.CharField(required=False) tagline = forms.CharField(required=False) class Meta: model=ArtistAccount fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"] I am using Materialize's datepicker, and trying to submit the date string it gives me. If I select a date, the field value looks like this 30 September, 2004 But Django continues to reject it: ('birthdate', 'Enter a valid date.') I think I've set the correct date formats. Am I doing something else wrong? -
Fetch picklist values through SOQL query in Salesforce
I am using Djnago & Salesforce. I establish connection between them through simple-salesforce I have created a custom picklist on Contact Object of Salesforce. I wont to fetch all the 20 values of my picklist & display in Django. I am looking for SOQL to fetch values from Salesforce. sf = Salesforce(instance_url='https://test.salesforce.com', session_id='') sf1 = Salesforce(connection parameters) sf3 = sf1.query("SELECT Color__c FROM Contact") sf3 will give me values set for respective Contact records. I want to fetch all the 20 values I have entered while creating Color__c on Contact object. In Apex we can do that, something like below public class PicklistUtil { public static List<Schema.PicklistEntry> getContactColor() { return Contact.Color__c.getDescribe().getPicklistValues(); } } I am looking to do the same in Django. Can someone please help? -
using Spring Boot JWT for authentication in DJango
My understanding is that the JWT is composed of a header, payload, and secret and is put together like something below I have a REST server that uses services to access data stored upon it. Some of the data is in an Oracle DB. From what I can see, one would "consume" the REST services from DJango side as seen below by using something like urllib3. def get_books(year, author): url = 'http://api.example.com/books' params = {'year': year, 'author': author} r = requests.get('http://api.example.com/books', params=params) books = r.json() books_list = {'books':books['results']} return books_list Src 1 proper-way-to-consume-data-from-restful-api-in-django Src 2 how-do-you-get-django-to-make-a-restful-call In the same message above ("Src 1"), it is mentioned that perhaps access to REST services can take the place of accessing data from thea database: If the service allowed for CRUD, you might opt for per-verb functions in service.py - get_book, put_book, delete_book etc. In using REST, the idea is that they (REST functions) can be called from Andriod, IOS, etc. The goal was to write the code once and use it in as many places as possible. In the example above, my understanding is that if one wanted to secure the services, one would use JWT. Since the server code was using … -
Django - Return Pdf and JsonResponse using same class instance
I have a view that return a JsonResponse. I want to generate a pdf report using the Building instance (the structure variable). For example, the view that return the JsonResponse is: @login_required def buildings(request): if request.POST and request.is_ajax(): s_form = BuildingForm(request.POST) if s_form.is_valid(): structure = Building(**s_form.cleaned_data) html = render_to_string('wind/results/buildings/buildings_results.html', {'structure': structure}) return JsonResponse({"result": html}) else: return JsonResponse({'building_errors': s_form.errors, status=400) else: s_form = BuildingForm() return render(request, 'wind/buildings.html', {'s_form': s_form}) I have the following code for generate and return the pdf: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' buffer = BytesIO() report = BuildingsReport(structure) # I want to use the same Building instance pdf = report.generate_pdf() response.write(pdf) return response What I want is use the same building instance for generating the pdf and the html variable. Using a different view to return the pdf implies a new Building instance. Except that there is another solution that solves the problem using another view. In the Frontend I want to show the JsonResponse and have the pdf available for the user to download using a html button. Using Celery is adecuated for this task? Thanks in advance! -
Updating custom user profile
In my web app, I need two users, regular site users and employees. I am using a custom user based on AbstractUser to achieve this. class CustomUser(AbstractUser): pass class Employee(CustomUser): user = models.OneToOneField(settings.AUTH_USER_MODEL) # other fields In settings.py I have: AUTH_USER_MODEL = 'app.CustomUser' I want to provide a profile page for both the regular site user and the Employee user. First, I created a form called UserProfileEditForm for regular site users: class UserProfileEditForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and get_user_model().objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): user = super(UserProfileEditForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user the corresponding view: @login_required def user_profile_edit(request): user = get_user_model() if request.method == 'POST': form = UserProfileEditForm(request.POST, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() return redirect('user_profile') else: form = UserProfileEditForm(instance=request.user) return render(request, 'user/user_profile_edit.html', { 'form': form }) and the form: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Update Information</button> </form> In the edit user profile page, I see the email rightly … -
Can I make 'get_absolute_url' return a related modal DetailView?
first-time poster, long-time lurker. Hopefully someone can help me figure this one out. So I have a Django project that includes a model named 'Artist'. I've created the detail view showing all the variables associated with this model (yay!) Now I want to include a comment feature for each artist, so I've created a model named 'ArtistComment': class ArtistComment(models.Model): author = models.ForeignKey(User, default=1) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='artistcomment') message = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse('events:artistdetail', kwargs={'pk': self.pk}) def __str__(self): return self.created_at.strftime('%H: %M - %d %b') My urls.py looks like this: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), My ArtistComment CreateView looks like this: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['artist', 'message',] def form_valid(self, form, **args): form.instance.author = self.request.user self.object = form.save() return super(ArtistCommentCreate, self).form_valid(form) And finally the URL in the ArtistDetail view looks like this: <a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' %}">Add A New Comment</a></p> (I'm using a modal div to make the form pop-up) My issue is that when I submit a new comment the 'get_absolute_url' returns the Primary Key from the ArtistComment, rather than the Artist the ArtistComment is related to. How would I make the … -
Python Django Wagtail, multiprocessing for search through PDF files
I have encountered a bit of a challenge, with searching through a library of PDF files for a given string. I do understand that going through a PDF file for a string is not an exact science but having used pyPdf and re libraries i have reasonable reusults. This is an example piece of code i found online which works for me def fn_search_pdf(my_dict): # xfile : the PDF file in which to look # xString : the string to look for import pyPdf, re PageFound = -1 print my_dict pdfDoc = pyPdf.PdfFileReader(file(my_dict['xFile'], "rb")) for i in range(0, pdfDoc.getNumPages()): content = "" content += pdfDoc.getPage(i).extractText() + "\n" content1 = content.encode('ascii', 'ignore').lower() ResSearch = re.search(my_dict['xString'], content1) if ResSearch is not None: PageFound = i #q.put(id) my_dict['q'].append(my_dict['id']) #print 'list',my_dict['q'] break def do_pdf_search(object,xString): procs = [] manager = Manager() res = [] temps = manager.list() pool = Pool(processes=1) list_dicts = [] for index, pdf in enumerate(object): for p in pdf.document_en: path = '/var/www/my/path/media/documents/'+os.path.basename(p.value.url) #path = 'E:/my/path/media/documents/'+os.path.basename(p.value.url) list_dicts.append({'xFile': path, 'xString': xString, 'q': temps,'id': pdf.id}) pool.map(fn_search_pdf, list_dicts) pool.close() pool.join() return temps do_pdf_search(Newsletters.objects.all(),'the string i'm looking for') on my windows machine it works just fine when i launch the Django service through python manage.py runserver 0.0.0.0:9988 …