Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect user to app based on permission and group
Say i have a django project which have 4 apps 1 app is for logging in project urls: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^', include('Login.urls')), url(r'^admin/', admin.site.urls), ] settings: LOGIN_REDIRECT_URL = '/' login app urls: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), ] now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker so i want to redirect user based on their type of employment. how can i achieve this ? any help is appreciated -
Ionic: A bit Strange CORS issue with the IOS emulator
This is the code. $http({ method: 'GET', url: imageUrl }); I'm using the Ionic framework. It works fine in web, andorid mobile and android emulator. But when I use the same in the IOS 9.3 emulator(4.1.1), I get the error XMLHttpRequest cannot load 'imageUrl'. Origin 'XXX' is not allowed by Access-Control-Allow-Origin. I suppose I can eliminate any possible errors in the backend, as it is working with the other UI frameworks. Also in the backend(Django framework) I've set CORS_ORIGIN_ALLOW_ALL and CORS_ALLOW_CREDENTIALS to True, added the IP address with port to CORS_ORIGIN_WHITELIST and the needed headers(including Access-Control-Allow-Origin) in CORS_ALLOW_HEADERS. So, Is there anything specific that needs to be done to make this error go away for the IOS emulator / platform ? -
3d distance calculations with GeoDjango
I am using python 2.7.12 django 1.10.6 postgreSQL 9.5.6 postGIS 2.2.2 First question I need to use GeoDjango to calculate distance between two points. When I checked the documentation https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoquerysets/#distance it says that GeoQuerySet.distance() is deprecated and instead use Distance() from django.contrib.gis.db.models.functions. The following code works OK: from django.contrib.gis.db.models.functions import Distance p1 = Instrument.objects.get(pk=151071000).coordinates p2 = Instrument.objects.filter(pk=151071008) for i in p2.annotate(distance=Distance('coordinates', p1)): print i.distance print i.distance.__class__ Output: 461.10913945 m <class 'django.contrib.gis.measure.Distance'> My model: class Instrument(models.Model): ... coordinates = gis_models.PointField(null=True, blank=True, dim=3) But I have only two points so when I try to use Distance() without annotate() it returns instance of class django.contrib.gis.db.models.functions.Distance() rathen than django.contrib.gis.measure.Distance(): p1 = Instrument.objects.get(pk=151071000).coordinates p2 = Instrument.objects.get(pk=151071008).coordinates print Distance(p1, p2) Output: Distance(Value(SRID=4326;POINT Z (-76.48623600000001 44.260223 0)), GeomValue(SRID=4326;POINT Z (-76.490923 44.262658 0))) How do I receive the same result as with using annotate()? Second question I have to calculate 3d distance that is taking into account depth/elevation. But when I try to do it I receive the same result as with 2d. Below I changed elevation to 200 in the first object: p1 = Instrument.objects.get(pk=151071000) p1.coordinates = 'SRID=4326;POINT Z (-76.48623600000001 44.260223 200)' p2 = Instrument.objects.filter(pk=151071008) for i in p2.annotate(distance=Distance('coordinates', p1.coordinates)): print i.distance Output: 461.10913945 m -
if condition in django template "{{ }}"
Before showing a text I have to evaluate it. Instead of {% if value %} text_true {% else %} text_false {% endif %} Are there anything like: {{ text_true if value else text_false }} -
Django template not re-rendering on succesful AJAX get request
I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was succesful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again. My view: def test(request,id=1): return render(request,'test.html',{'num':id,'next':9}) My template and ajax code: <script src='https://code.jquery.com/jquery-3.2.1.min.js'></script> <p>{{num}}</p> <button onclick='test({{next}})'>Test</button> <script> function test(next){ $.ajax({ url:'/test/'+next, type: 'GET', success: function(){ console.log('done'); } }); } </script> Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change. -
take image path from select django form
i have a django app and i working with upload images user authentication and django select form. in the django select form i have some question about how to work this first i upload images correct before with other form. second i create a select django form list with self login user images. now i need take that selection image path to do some image processing from this form. image form i have create something but i am not sure if is correct but i am sure that is not where i need. here the code : models.py class MyModel(models.Model): user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='upload') views.py @login_required(login_url="login/") def myview(request): Myf = MyModelForm(user=request.user,data=request.POST) print myf return render(request,'home.html',{'Myf':Myf}) form.py class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): if 'user' in kwargs: self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) choices = [(obj.id, obj.upload.url) for obj in MyModel.objects.filter(user=self.user)] self.fields['upload'].widget = Select(choices=choices) class Meta: model = MyModel fields = ('upload',) html page : <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ Myform}} <input type="submit" name="" value="Submit"> </form> debug mode : [18/Apr/2017 16:03:36] "GET /favicon.ico HTTP/1.1" 404 2926 <tr><th><label for="id_upload">Upload:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select id="id_upload" name="upload" required> <option value="1">/media/user_2/image1.jpg</option> <option value="3">/media/user_2/image2.jpg</option> <option value="4">/media/user_2/image3.jpg</option> <option value="5">/media/user_2/image4.jpg</option> <option … -
celery kombu unresolved dependencies post python upgrade
I upgraded my ubuntu environment to 16.04 which also upgraded python to 2.7.12 My environment is as below: 1) Celery - 3.1.25 2) Django - 1.6.5 3) Kombu - 3.0.24 I was getting below errors while I tried to start my celery worker: File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 20, in from kombu.utils.compat import _detect_environment ImportError: cannot import name _detect_environment I went through kombu code base and got the relevant function for _detect_environment and that resolved the issue. But, second time I hit below exception: File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 29, in from celery.five import buffer_t, items, python_2_unicode_compatible, values ImportError: cannot import name buffer_t And could not resolve it. I tried along with latest version of kombu but that also did not help. I know Django is very old but I am scared to upgrade that as it might break other things. It was working fine along with ubuntu 14.04 Any idea? -
Angular -Js $http.post not working in django
I have just started Django and what I was trying to implement $http.post method of angular to post form data to my Django database,and my further plan was to update the view to display the results without page refresh.so what i thought to post data in django db and then my view function will return a jsonresponse,of that posted data which i can use to update the view using $http.get method. But the problem is occuring with me is whenever i post data it is not able to post the data and returning an empty json response. Here is my codes which i am working on:- urls.py from django.conf.urls import url from . import views app_name='demo' urlpatterns=[ url(r'^$',views.index,name="index"), url(r'^add_card/$',views.add_card,name="add_card") ] views.py from django.shortcuts import render from django.http import HttpResponse,JsonResponse from .forms import CardForm from .models import Card # Create your views here. def add_card(request): saved = False if request.method == 'POST': #print('hi') form = CardForm(request.POST) #print('hi') if form.is_valid(): #print('hi') card = Card() #print('hi') card.content = form.cleaned_data['content'] #print('hi') saved = True card.save() #print('hi') return JsonResponse({'body':list(q.content for q in Card.objects.order_by('-id')[:15])}) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) def index(request): return render(request,'demo/index.html',{'form':CardForm()}) controller.js var nameSpace = angular.module("ajax", ['ngCookies']); nameSpace.controller("MyFormCtrl", … -
Jmeter authorization where should I put token?
Something wrong with my authorization flow but I can't to figure out what exactly. Response data: {"detail":"Authentication credentials were not provided."} Does it may be related to used technologies: Python/Django + React JS ? View Results Tree HTTP Request по которому отправляется логин/пароль -
Djano bulk_create while populating ImageField
I am trying bulk_create a list of Person objects from some list of raw parsed API data. the data contains: Id Comment Image person = raw_api_data[0] obj = Person( id=person['id'], comment=person['comment'], ) if person['image'] is not None: obj.image.save( '.jpg', ContentFile(person['image'].decode('base-64')), save=False, ) new_persons.append(obj) Person.objects.bulk_create(new_persons) I want to be able to avoid creating local image files on file system in case bulk_create fails. (IntegrityError for example) Is there any way to avoid creating the file itself before the create process itself while also be able to bulk create all objects with their images? I did not find any other ideas besides creating the content file before appending the object itself to the bulk list. Thank you -
django url regex changing on redirect
This is how to the url regex should look like url(r'^(?P<username>\w+)/'...... But on redirect is becomes url(r'^(?P<username>\\w+)/'....... Notice the backslash before the 'w' became double and because of that I keep getting the no reverse match error....what could be the problem -
Jupyter and Django
Here is my folder : /home/bussiere/Workspace/ reetags -- kiwixi -- settings.py retagsTest i'am launching jupyter in reetagsTest but when i try to do this in jupyter : MYPROJECT = '/home/bussiere/Workspace/reetags/' import os, sys sys.path.insert(0, MYPROJECT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kiwixi.settings") import django django.setup() i have a : ImportError: No module named 'settings' And i would like to acces to django ORM / objects and everything without launching django thanks and regards -
Reactjs REST API call to Django fails
I have hosted an app(ReactJS + Django) on amazon ec2 server. When the client app makes a REST API call, I get connection refused error on the ec2 instance. But when I run the app locally, it works smoothly. I have added the correct inbound rules in security groups for the ports for both client as well as django server. The client makes a call to http://localhost:8000/getImages The django service is also running on the same port. As a matter of fact, the app was working fine on the ec2 server also just a couple of weeks ago with the exact same settings. I'm not sure as to what changed in the mean time and what could possible fix this error. Any suggestions? -
ModuleNotFoundError: No module named 'PyDemo.accounts'
I am trying out Django app for the first time. I have a little experience regarding this. I am trying to host a simple index.html in my app, but I am getting the following error. url.py: from django.conf.urls import url,include from django.contrib import admin from PyDemo.accounts.views import my_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^demo/',my_view) ] views.py: from django.shortcuts import render_to_response from django.template import RequestContext # Create your views here. def my_view(request): return render_to_response('index.html',locals(),context_instance=RequestContext(request)) Whenever I am running this I get the following error: return import_module(self.urlconf_name) File "C:\Users\tcssuoy\Desktop\DJANGO\mysite\lib\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 "C:\Users\tcssuoy\workspace\PyDemo\PyDemo\PyDemo\urls.py", line 18, in <module> from PyDemo.accounts.views import my_view ModuleNotFoundError: No module named 'PyDemo.accounts' Can you please help me out on this? -
django-ckeditor :data not loading in the Form
I'm Using Django-ckeditor as a model form widget.I have been able to able to save data using the model-form. Now that I want to edit any saved data the form does not load the data onto the CKeditor. Django 1.10 Python 3.5 Windows 7 64bit forms.py class templateform(forms.ModelForm): class Meta: model = presciptiontemplates fields = ['template', 'templateid', ] widgets = { 'template': CKEditorWidget(), } labels = { "templateid": _("Patient ID"), } views.py def get_template(request, tid): template = presciptiontemplates.objects.get(templateid=tid) form = templateform(request.POST, instance=template) if form.is_valid(): form = form.save(commit=False) form.patientid = tid form.save() else: form = templateform(request.POST, instance=template) return render(request, 'presapp/viewtemplate.html',{'form': form}) HTML <div id="preview-content"> <form method="post" style="margin-top:20px;"> {% csrf_token %} {{ form.media }} {{ form|safe }} <div class="" style="margin-top:20px ;"> <button class="btn waves-effect waves-light left" type="submit">Submit <i class="material-icons right">add_circle</i </button> </form> </div> </div> -
Django - Python 3 - "AssertionError: A model can't have more than one AutoField."
I'm getting crazy over this. I created my database with MySQLWorkbench This his my Schema Than I used the terminal command to get the model-code: $python3 manage.py inspectie After passing the code to my models.py I try to use the models in the shell with $python3 manage.py shell But then I'm getting always this error: "AssertionError: A model can't have more than one AutoField." But the error makes no sense, since there are only one AutoField in each Model, see: class Brands(models.Model): bid = models.AutoField(db_column='BID') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. fair = models.IntegerField(db_column='Fair', blank=True, null=True) # Field name made lowercase. eco = models.IntegerField(db_column='Eco', blank=True, null=True) # Field name made lowercase. country = models.CharField(db_column='Country', max_length=45, blank=True, null=True) # Field name made lowercase. companies = models.ForeignKey('Companies', models.DO_NOTHING, db_column='Companies_ID') # Field name made lowercase. class Meta: managed = False db_table = 'Brands' unique_together = (('bid', 'companies'),) class Companies(models.Model): cid = models.AutoField(db_column='CID') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. fair = models.IntegerField(db_column='Fair', blank=True, null=True) # Field name made lowercase. eco = models.IntegerField(db_column='Eco', blank=True, null=True) # Field name made lowercase. country = models.CharField(db_column='Country', max_length=45, blank=True, … -
Error in displaying chart in Django with chartit
I have an application for which I am trying to display a simple chart of number of proposals per country. I am using pivotchart in chartit as explained here I have a model like this class Proposal(models.Model): org = models.CharField(max_length=200) country = models.CharField(max_length=100) recdate = models.DateField(blank=False) subdate = models.DateField(blank=False) status = models.CharField(choices = stat_val, max_length=20) and as explained in the chartit GitHub, I have added this to views from django.db.models import Count from chartit import PivotDataPool, PivotChart from django.shortcuts import render_to_response def proposal_pivot_chart_view(request): # Step 1: Create a PivotDataPool with the data we want to retrieve. proposalpivotdata = PivotDataPool( series=[{ 'options': { 'source': Proposal.objects.all(), 'categories': ['country'], }, 'terms': { 'countprop': Count('id'), } }] ) # Step 2: Create the PivotChart object chart1 = PivotChart( datasource=proposalpivotdata, series_options=[{ 'options': { 'type': 'column', 'stacking': True }, 'terms': ['countprop'] }], chart_options={ 'title': { 'text': 'Proposals by Countries' }, 'xAxis': { 'title': { 'text': 'Country' } } } ) # Step 3: Send the PivotChart object to the template. return render_to_response({'chart1': chart1}) and I have created a template like this <!DOCTYPE html> <html> <head> {% load staticfiles %} {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" > <link rel="stylesheet" href="{% static 'bootstrap/css/light-bootstrap-dashboard.css' %}" … -
Django project using python 2.7 even though interpretor points to python version 3.5
My project interpretor points to python version 3.5.2: (/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5) However when I go to the python shell in the project terminal (i'm using pycharm btw), it loads python 2.7. Any idea why? -
Get a variable out of a 'Model' -- Django Template
I have a complicated question, so I hope I can write it in a understandable way. I have a template (index.html) and I'm using a custom tag for setting a few variable. I can set this varible with: {% set table_breaker_houses = 4 %} And I use it later many times with, for example: {% if forloop.counter <= table_breaker_houses %} This is how it works now, but I want something like this: {% for settings in Settings %} {% set table_breaker_houses = "{{ settings.table_breaker_houses }}" %} {% endfor %} {% if forloop.counter <= table_breaker_houses %} "Settings" is a model with values, so I can manage my settings with the adminpanel. Could someone please help me out? Thanks for readings so far and sorry for my bad english. :) With best regards, borsTiHD -
Django: how to avoid redirection in a DeleteView
I am using a DeleteView which is redirecting after success, but I am trying to avoid this. I figured the part that redirected the page was in this method in the DeletionMixin (the last line): def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return HttpResponseRedirect(self.get_success_url()) So I overrode it: def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return HttpResponse(json.dumps({'success': True}), content_type='application/json') Nonetheless, when deleting the entry, the response keeps redirecting the page. This is the relevant part of my client code: $.ajax({ url: '{% url some_delete_route some_model.id %}', type: 'DELETE', success: function () { $this.closest('.item-container').remove(); } }); What am I missing? What should I do to avoid the redirection? I am doing the same thing for other views like FormView and CreateView and I did not experience this issue. -
IndexError at /delta/ - list index out of range - Django
The user selects two aircraft to compare from the list page. However I get the following error: IndexError at /delta/ list index out of range. It's complaining about this line in particular: first_value = getattr(aircraft_to_compare[0], key) Is there an obvious error that I'm making here? View def aircraft_delta(request): ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) property_keys = ['name', 'manufacturer', 'aircraft_type', 'body', 'engines', 'image', 'cost','maximum_range','passengers','maximum_altitude','cruising_speed', 'fuel_capacity','description','wing_span','length'] column_descriptions = { 'image': '', 'name': 'Aircraft', 'maximum_range': 'Range (NM)', 'passengers': 'Passengers', 'cruising_speed': 'Max Speed (kts)', 'fuel_capacity': 'Fuel Capacity', 'aircraft_type': 'Type', 'body':'Body', 'engines':'Engines', 'cost':'Cost', 'maximum_altitude':'Maximum Altitude', 'description':'Description', 'manufacturer':'Manufacturer', 'wing_span':'Wing Span (FT)', 'length':'Total Length (FT)' } data = [] for key in property_keys: row = [column_descriptions[key]] first_value = getattr(aircraft_to_compare[0], key) second_value = getattr(aircraft_to_compare[1], key) if key not in ['image', 'name']: delta = abs(first_value - second_value) else: delta = '' row.append(first_value) row.append(delta) row.append(second_value) data.append(row) return render(request, 'aircraft/aircraft_delta.html', { 'data': data }) -
No bin and lib in new django app
I have no bin and lib next to my root directory, which I have in another project but i'm not sure how I got them. So this is my app tree right now: Desktop | project | app > | | | db.sqlite3 | init.py | | manage.py | views.py | | templates | settings.py | | | urls.py And my other app has: Desktop | project | app | app> | | | bin | init.py | init.py | | db.sqlite3 | db.sqlite3 | settings.py | | include | manage.py | urls.py | | lib | templates | views.py So is one of these improperly configured?/which one is the better option? -
django summernote is not displaying
views.py def post_detail(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('post_detail') else: form = PostForm() return render(request, 'post_detail.html', {'form': form}) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('Penname','text',) widgets = { 'text': SummernoteInplaceWidget(), } models.py class Post(models.Model): #user = models.OneToOneField(User) Penname = models.CharField(max_length=200) text = models.TextField() def __str__(self): return self.Penname post_detail.html <!DOCTYPE HTML> <html> <head> </head> <body> <div class="container"> <form method="post"> {{ form.as_p }} <button type="button" class="btn btn-primary">Submit</button> </form> <div> <h1>{{ post.Penname }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> </div> </body> </html> urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^summernote/', include('django_summernote.urls')), url(r'^post/$', imagec_views.post_detail, name='post_detail') ] I want a summernote editor option for my text field,but it is displaying only 'Text' string and summernote is not displaying ,even it is not displaying a simple textfield -
EmberJS Build Failed with no such file or directory for jquery.js
I have an Ember + Django project that previously worked last week and I have not made a single change since. But now every time I rebuild the project it gives me the following error: Build failed. The Broccoli Plugin: [SourceMapConcat: Concat: Vendor /assets/vendor.js] failed with: Error: ENOENT: no such file or directory, stat '/Users/IFH/Desktop/planner/planner-frontend/frontend/tmp/source_map_concat-input_base_path-V4BWWQCZ.tmp/0/bower_components/jquery/dist/jquery.js' at Error (native) at Object.fs.statSync (fs.js:844:18) at Concat.keyForFile (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:87:20) at Array.map (native) at Concat.CachingWriter._conditionalBuild (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:109:65) at /Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34 at tryCatch (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:539:12) at invokeCallback (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:554:13) at publish (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:522:7) at flush (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:2414:5) Previously it would create those files in that 'tmp' directory, but now nothing is even being created. Once again, I did not change any file before this error occurred. Please let me know what I should change in order to fix this issue. -
how to pass arguments to django views function and return csv on a button click?
I am not able to download the CSV when I click the button. it's working when I directly enter URL i.e localhost:8000/tweets with default values in the view function. but when I'm doing it on button click following output is coming and become idle. url(r'^tweets/', views.scrape_tweets), <div class="modal-footer"> <button id="download_tweets" class="btn btn-success" type="submit">Download</button> </div> $("#download_tweets").click(function() { var input = $('#query_input').val(); fdate = $('#startDate input').datepicker("getDate"); edate = $("#endDate input").datepicker("getDate"); data = {'input': input, 'startDate':convert_date(fdate),'endDate':convert_date(edate)} // console.log(data) $.ajax({ // url : '/tweets', url : '/tweets/?input='+input+'&startDate='+convert_date(fdate)+'&endDate='+convert_date(edate), type : 'get', data : data, success: function(result){ setTimeout(function(){ console.log('Success'); }, 3000); }, error: function (jqXHR, exception) { console.log("Errorrrrrrrrrrrrrrrrrr") console.log(jqXHR) } }); }); def scrape_tweets(request): # Get tweets by query search query = str(request.GET['input']) start_date = str(request.GET['startDate']) end_date = str(request.GET['endDate']) print '\n\n',query, start_date, end_date,'\n\n' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="tweets.csv"' writer = csv.writer(response) writer.writerow(['Id', 'Tweet', 'Favorites', 'Retweets', 'Date & Time']) tweetCriteria = TweetCriteria().setQuerySearch(query).setSince(start_date).setUntil(end_date).setMaxTweets(200) start_time = timeit.default_timer() tweets = TweetManager.getTweets(tweetCriteria) print timeit.default_timer() - start_time for i in tweets: writer.writerow([unicode(i.id).encode("utf-8"), unicode(i.text).encode("utf-8"), unicode(i.favorites).encode("utf-8"), unicode(i.retweets).encode("utf-8"), unicode(i.date.strftime("%Y-%m-%d %H:%M")).encode("utf-8")]) return response Output in terminal Terminal: Virat Kohli 2017-04-18 2017-04-18 0.789546012878 [18/Apr/2017 10:54:21] "GET /tweets/?input=Virat%20Kohli&startDate=2017-04-18&endDate=2017-04-18&input=Virat%20Kohli&startDate=2017-04-18&endDate=2017-04-18 HTTP/1.1" 200 41