Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i use Django Celery apply_async with eta, it do the job immediately
i looked at celery documentation and trying something from it but it not work like the example. maybe i'm wrong at some point, please give me some pointer if i'm wrong about the following code in views.py i have something like this: class Something(CreateView): model = something def form_valid(self, form): obj = form.save(commit=False) number = 5 test_limit = datetime.now() + timedelta(minutes=5) testing_something.apply_async((obj, number), eta=test_limit) obj.save() and in celery tasks i wrote something like this: @shared_task() def add_number(obj, number): base = Base.objects.get(id=1) base.add = base.number + number base.save() return obj my condition with this code is the celery runs immediately after CreateView runs, my goal is to run the task add_number once in 5 minutes after running Something CreateView. Thank You so much -
Django uwsgi using css file http1.1 404
I just put my Django application online using uwsgi. I can access it from any computer it working well.. the only thing is uwsgi can't load the css file stored in the /static/myapp/style.css path and I don't why. The message I get when accessing a page on my site in the uwsgi console is : GET /static/myapp/style.css => generated 98 bytes in 1msecs (HTTP/1.1 404) 3 header in 100bytes But the file is actually in /static/myapp/style.css I can see it and it was working well in developpement, but now the website is in production it's not working anymore. I added these to my settings.py but nothing changed : STATIC_URL = '/static/' #Was enough in developpement STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = ("/home/user/Django/mysite/static"), I also tried to add option in my uwsgi command like --check-static /home/user/Django/mysite/static Still not working... I'm quite new to putting online a Django app so maybe it's not supposed to work like that. My css file is on the same machine as my Django project. I'm using django 1.11 and uwsgi 2.5.15. I also tried to used nginx but I couldn't get it work properly and as I just want β¦ -
split and iterate through data in django template
Okay so I am passing a dictionary into my template and displaying it in a table as so. Where value.4 is a comma separated string. What I would like to do is truncate the data being displayed in the field and show the full content in a popup modal. My first thought was to split the string and then iterate over it but I can't find any method for doing this. {% if data %} {% for key, value in data %} <tr> <td scope="row">{{ forloop.counter }}.</td> <td> <div id="popup"> <p class="citation" data-hover="{{ value.2 }}">{{ value.1 }} <img src='{% static "img/expand-icon2.png" %}' id="expand"></p> <a class="article" target="_blank" href={{ value.3 }}>{{ value.2 }}</a> </div> </td> {% if value.4 %} <td>{{ value.4 }}<a class='test' href='#' id="trigger_{{ forloop.counter }}"><img src='{% static "img/expand-icon2.png" %}' id="expand"></a></td> {% else %} <td>No Provenance Terms Found</td> {% endif %} ... <div id="classModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="classInfo" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> Γ </button> <h4 class="modal-title" id="classModalLabel"> Triples: </h4> </div> <div class="modal-body"> <table id="classTable" class="table table-bordered"> <thead> <tr> <th style="width: 4%">#</th> <th>Subject</th> <th>Predicate</th> <th>Object</th> <tr> </thead> <tbody> {% for triple in value.4.split %} {% for x in triple %} <tr> β¦ -
Load staticfies do not work in Django
I am new to python Django. I have a project like this below: But in my TestModel APP, there is a index.html here: <!doctype html> {% load staticfiles %} <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="Keywords" content="" /> <meta name="description" content="" /> <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" /> --> <title>Pythonζ’η΄’ι¦ - Slice</title> <!-- Main Theme --> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> <!-- Font --> <link rel="stylesheet" href="http://at.alicdn.com/t/font_n5vylbuqe61or.css" /> </head> <body> ... You see I have load the static files. And in my testdj/ the settings.py, I have set the STATIC_URL: STATIC_URL = '/static/' But in the browser, the stylesheet did not load success. -
Faking a Streaming Response in Django to Avoid Heroku Timeout
I have a Django app that uses django-wkhtmltopdf to generate PDFs on Heroku. Some of the responses exceed the 30 second timeout. Because this is a proof-of-concept running on the free tier, I'd prefer not to tear apart what I have to move to a worker/ poll process. My current view looks like this: def dispatch(self, request, *args, **kwargs): do_custom_stuff() return super(MyViewClass, self).dispatch(request, *args, **kwargs) Is there a way I can override the dispatch method of the view class to fake a streaming response like this or with the Empy Chunking approach mentioned here to send an empty response until the PDF is rendered? -
Python virtualenv can`t work through OneDrive
I store my project on OneDrive and sometimes work on pc and laptop. Both have Windows 10 and absolutly same position C:/OneDrive/code/etc.. . When I use virtualenv and download diffents packages all work perfect, but when I on my laptop nothing work at all(and true for oposite direction). Appears hundreds of problems.(current -- Could not import runpy module ImportError: No module named 'runpy'). What can i do to work without problem on laptop and PC ? Somebody have the same problem? P.S. Sorry for my english -
Django - static files not found both locally and on Heroku
I have a problem with static files using Django with Docker on Heroku. When I open app I get errors like this on Heroku: 2017-07-13T13:37:43.271635+00:00 heroku[router]: at=info method=GET path="/static/rest_framework/js/default.js" host=myapp.herokuapp.com request_id=3bfd8d31-193e-48e8-bb6e-aee9f353ffee fwd="109.173.154.199" dyno=web.1 connect=1ms service=15ms status=404 bytes=291 protocol=https and like this locally: django_1 | [13/Jul/2017 13:35:01] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 109 I tried to do it on the basis of many answers, for instance this topic, unfortunately nothing works. Any suggestions? My settings.py: STATIC_ROOT = '/Users/myUser/Projects/DockerProject/PROJECT/backend/project/project' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Project tree: DockerProject βββ Dockerfile βββ Procfile βββ init.sql βββ requirements.txt βββ docker-compose.yml βββ PROJECT βββ frontend βββ all files βββ backend βββ project βββ prices βββ manage.py βββ project βββ all backend files -
contenttypes.models.DoesNotExist: ContentType matchingquery does not exist how to improve
by another project this comment system is worked! but there nothing, how to fix this issue? full traceback > Traceback (most recent call last): File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\exception.py", > line 41, in inner > response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", > line 187, in _get_response > response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", > line 185, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\serials\views.py", > line 78, in post_of_serie > content_type = ContentType.objects.get(model=c_type) File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\manager.py", > line 85, in manager_method > return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\query.py", > line 380, in get > self.model._meta.object_name django.contrib.contenttypes.models.DoesNotExist: ContentType matching > query does not exist. this is views.py initial_data = { "content_type": serie.get_content_type, "object_id": serie.id } if request.method == 'POST': form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1 : parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data, parent = parent_obj ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) form = CommentForm(initial=initial_data) comments = Comment.objects.filter_by_instance(serie) context = { "serie":serie, "full_path":full_path, "title":title, "poster":poster, "comments": comments, β¦ -
Wagatail embeds YouTube - prevent related videos showing
I need to ensure that related videos dont show on youtube videos in a clients site built with Wagtail. They are all presently using the built in wagtailembeds feature via wagtailembeds_tags {% embed video.url %}. Typically I have done this before by appending the GET parameter 'rel=0' to the URL. I have tried this via the URL field in the page editor screen but it seems it gets stripped off at some stage of its processing. At present I can't see any way of doing this? From looking at the latest branch of the project in ReadTheDocs it seems there may be a way of customising an oEmbed provider soon, just I need a solution now. http://docs.wagtail.io/en/latest/advanced_topics/embeds.html Thanks in advance for any help! -
Django Paginator only paginates the first 100 items of my list
I am working on a simple web application, in which I need to paginate a list of items. Using the built-in Paginator function, I am able to get it working (almost). Problem is, my paginator only shows the first 100 items in my list if there are more than 100 items. My view is like this, def menu(request, domain_name): count = request.session['count'] # actual number of items data = request.session['tickets'] page_limit = 25 paginator = Paginator(data, page_limit, 0) page = request.GET.get('page') try: tickets = paginator.page(page) except PageNotAnInteger: tickets = paginator.page(1) except EmptyPage: tickets = paginator.page(paginator.num_pages) return render(request, 'ticketmenu/menu.html', {'count': count, 'tickets': tickets}) What I get on the browser is something like this, 99 100 Previous Page 4 of 4 Total: 102 I printed out the item id on the page starting at 1. The last line indicates that the actual length of my list is 102, so 2 of them are missing. I don't understand why this is happening, and I cannot find any parameters relating to max_items_in_list. Please help, thank you! -
customise django widget in template
I have standard model form in django with Imagefield and standard widget. It made me such output on the page: Currently: <a href="/media/qwe/Tulips.jpg">qwe/Tulips.jpg</a> <input id="image-clear_id" name="image-clear" type="checkbox" /> <label for="image-clear_id">Clear</label><br /> Change: <input id="id_image" name="image" type="file" /> I want to place outputs of this widget in different parts of page. How can I cut it in templates. If there is a way to use part of the output in template like {{form.name_of_field.label}} or {{form.name_of_field.errors}} I've tried different names but no use There must be a way to use them apart. -
Django ORM & compound primary keys. Relationship status: "It's complicated."
I have a (legacy) database with the following tables. How do i follow the relationship from the orders object to the delivery_adress in Django's views and templates? In SQL, i would simply use join delivery_adress on customer_fk = customer_fk and customer_fk = customer_fk, but how does it work in the Django ORM? The tables are defined like this (i tried to mark down the FK relationships): orders id | ordernr | product | amount | customer (FK) | delivery_adress (FK) ---+---------+---------+--------+---------------+--------------------- 1 | 20 | 5 | 200 | 1 | 1 2 | 21 | 3 | 400 | 2 | 1 3 | 22 | 2 | 20 | 2 | 2 4 | 23 | 1 | 1 | 3 | 1 | | customer --------------------------- | id | name |---- | ---+-------+ | | 1 | John | | | 2 | Steve | | --------- 3 | Guy | | | 4 | Joe | | | | | delivery_adress customer (PK/FK) | delivery_adress(PK) | adress -----------------+---------------------+------- 1 | 1 | SF 2 | 1 | LA 2 | 2 | NY 3 | 1 | CH The Model delivery_adress is: class Delivery_adress(models.Model): customer= models.ForeignKey(Customer, β¦ -
Django - not saving in MySQL database
Please forgive me in advance - I know there are some questions on that - but I really didn't find the solution. I work on Django and I want to populate a Mysql table that was created thanks to a model I made. I also created my form, my html page (template) and my view. I have no error message but nothing is created into the database. Here is my model.py class ModForm1(models.Model) : utilisateur = models.CharField(max_length=100) description = models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution") def __unicode__(self): return "{0} {1} {2} {3} ".format(self, self.utilisateur, self.description, self.date) Here is my form.py class ModForm1Form(ModelForm): class Meta: model = ModForm1 fields = '__all__' Here is my template : <div class="container"> <div style="width:30%"> <form role="form" action="." method="post"> <div class="col-xs-12"> <legend><i class="icon-group"></i>&nbsp;Authentification</legend> {% csrf_token %} <div class="form-group"> <label for="example-text-input">Utilisateur</label> {{ form.utilisateur }} </div> <div class="form-group"> <label for="example-text-input">Description</label> {{ form.description }} </div> <input class="btn btn-primary" type="submit" value="submit" /> </form> </div> </form> </div> And here is my views.py def addentry(request): form = ModForm1Form(request.POST) # if this is a POST request we need to process the form data if request.method == 'POST': if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect β¦ -
Creating Django users with just an email and password - UserCreationForm
I have the need of create an user account in my application using just the email and password fields. Due to this, my custom user model in my models.py is: I customize the UserManager to create user from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) user = self.model(email = email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) And my User model is: from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True, help_text=_('Required. Letters, digits and ''@/./+/-/_ only.'), validators=[RegexValidator(r'^[\w.@+-]+$', _('Enter a valid email address.'), 'invalid') ]) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) objects β¦ -
Django multi table on same model
I have huge table that needed to be sliced into some smaller table, ex: campaign_01, campaign_02, ... While using django queryset with different table name for same model, what I only know to set table name on a model is: Model._meta.db_table = 'tableXXX' However this method doesn't work in single shell/request. (only work for first time, but not for the next) -> maybe because it still on same instance? After the second time we tried to set _meta.db_table = 'tableYYY', it will occur an error "django.db.utils.ProgrammingError: missing FROM-clause entry for table "tableXXX"" I also have tried some suggestion I read for this problem answer like: class ListingManager(models.Manager): def get_custom_obj(self, table_name): self.model._meta.db_table = table_name return self class ObjectName(models.Model): objects = ListingManager() Try to create an Object manager to get new object, but it not work, it still throw same error as before (on the second time setting _meta.db_table) The only way to make it work if we want to set multiple times for _meta.db_table is we need to exit() the shell first, then re-enter the shell mode (which means for loop is not gonna work). I know it can be achieved with raw query 'Insert into tableXXX values ()', but any β¦ -
django saving product id when clicking on a button
I have a ListView that displays a list of results (eg products) which are looped through in the template. Each product in the list has a button which the user can choose to select the product. I would like to store the product id selected by the user in the session so I can use it later. (It will be used in the next view where the user will sign to pay for item and also to pass into external api request to check stock) What's the best way to store the product id in the session for use later Currently I tried this in the template: <a class="btn btn-cta-primary" href="{% url 'users:signup' price_id=quote.priceId %}">Proceed</a> Which I thought would pass it to the next view where I could write it to the session with self.request.session['price_id'] (perhaps it's best to immediately save it to the session when the button is clicked?) -
RapidPro Not sending response to Facebook Messages
I have setup RapidPro on Ubuntu 16.04 and have added Facebook as a channel. When I am sending a message through a Facebook page then it is being received in the RapidPro dashboard but I have added a trigger that when someone sends a message through Facebook then a particular text is sent back to the user on Facebook. Instead of sending back the message to Facebook user, the server just echoes the response on the console as below: M[000000069] Processing - Hello FAKED SEND for [70] - Hello, Thank you for contacting us!!! [0.31] triggers for 69 M[000000069] 0000.315 s - Hello M[000000071] Processing - my status [0.02] triggers for 71 FAKED SEND for [72] - Please share your order number with us. [0.20] rules for 71 M[000000071] 0000.228 s - my status M[000000073] Processing - 1234 [0.03] triggers for 73 FAKED SEND for [74] - You order is shipped [0.28] rules for 73 M[000000073] 0000.309 s - 1234 M[000000075] Processing - ok [0.02] triggers for 75 [0.01] rules for 75 FAKED SEND for [76] - Thanks for contacting the ThriftShop order status system. Please send your order # and we'll help you in a jiffy! [0.25] triggers for β¦ -
Hosting Django project with uWSGI returns in hostname was NOT found in DNS cash
I'm following the uWSGI guide. I can successfully host a random test.py file using uWSGI. I can also successfully host my django project using the runserver command. However uwsgi --http :8443--module mysite.wsgi returns $ curl -v 0.0.0.0:8443 * Rebuilt URL to: 0.0.0.0:8443/ * Hostname was NOT found in DNS cache * Trying 0.0.0.0... * Connected to 0.0.0.0 (127.0.0.1) port 8443 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.35.0 > Host: 0.0.0.0:8443 > Accept: */* > I don't understand what is going wrong. How can I successfully host it? -
Django Crispy forms not showing bootstrap/css or button
I got crispy forms working with my model, though the form looks plain and bootstrap not showing up, also there seems to be no button. Even when adding button and clicking it(it refreshes) no data has been saved to the database. I have tried many ways. What seems to be wrong? Any help would be highly appreciated. forms.py class PlotForm(forms.ModelForm): helper = FormHelper() helper.form_tag = False helper.form_method = 'POST' class Meta: model = Plot fields = '__all__' views: def plot_form(request): return render(request, 'plot_form.html', {'form': PlotForm()}) the html: {% load crispy_forms_tags %} <form action="" method="POST"> {% crispy form %} <input type="submit" class="btn btn-default" value="save"> -
Nested Django serialization
I am using Django and django_rest_framework. I am struggling in creating the serializer/s for my models. I have an url mapped to a view which is expecting a POST request with such JSON: { "sid": "LLL", "simulations": "True", "host": "lvmql111.wdf.sap.corp", "systemresults": { "date_executed": "2017-07-03T14:09:48Z", "codeline": "VCMDEV", "lane_state": "dev", "atsresults": { "ats_class_name": "H2SCloneClone", "successful": "True", "testresults": { "name": "Clone1", "successful": "True", "stack_trace": "/dev/log/executioon.log", "duration": "00:31:21" } } } } I have these models: class LVMSystem(models.Model): sid = models.CharField(max_length=10) simulations = models.BooleanField() host = models.CharField(max_length=100) class SystemResult(models.Model): lvmsystem = models.ForeignKey(LVMSystem, on_delete=models.CASCADE, related_name='systemresults') date_executed = models.DateTimeField() codeline = models.CharField(max_length=100) lane_state = models.CharField(max_length=10) class ATSResult(models.Model): systemresult = models.ForeignKey(SystemResult, on_delete=models.CASCADE, related_name='atsresults') ats_class_name = models.CharField(max_length=100) successful = models.BooleanField() class TestResult(models.Model): ATS = models.ForeignKey(ATSResult, on_delete=models.CASCADE, related_name='testresults') name = models.CharField(max_length=1000) successful = models.BooleanField() stack_trace = models.CharField(max_length=1000) duration = models.DurationField() Most of the tutorials/stackoverflow questions show you how to do it with nested serialization with a depth of 2, which I managed to do - example Also a lot of the questions I read on the topic were from ~2013 and I would guess Django has been improved since then. A couple questions even said that Django doesn't support what I want with plain ModelSerializers. Is this still the β¦ -
Two forms in function def post
I have a written function def post which works for the form of adding comments to posts. In this case, when I send a rate form, no records are added to the database. I need to edit this function so that when I sending a form with a rated post, all data in the form will be saved in the database, as it should. In database by form I need save the value of the rating, user who rated, date and the post which was rated. Just I need after sending form it adds values to the database. views.py: class IndexView(AllAdsViewMixin, ListView): model = UserContent template_name = 'user_content/list.html' context_object_name = 'object' def get_queryset(self): """Return the last all five published contents""" return UserContent.objects.filter(state='1').order_by('-published')[:5] def get_context_data(self, **kwargs): comment_initial_data = { 'content_type': ContentType.objects.get_for_model(self.model).id } reply_initial_data = { 'content_type': ContentType.objects.get_for_model(Comment).id } comment_form = CommentForm(initial=comment_initial_data) reply_form = CommentForm(initial=reply_initial_data) mainpage_images = MainPageImages.objects.first() rate_form = RateForm() context = super(IndexView, self).get_context_data(**kwargs) context['comment_form'] = comment_form context['reply_form'] = reply_form context['mainpage_images'] = mainpage_images context['rate_form'] = rate_form return context def post(self, request, **kwargs): comment_form = CommentForm(request.POST) if comment_form.is_valid(): content_type_id = comment_form.cleaned_data.get('content_type') object_id_data = comment_form.cleaned_data.get('object_id') content_data = comment_form.cleaned_data.get('content') content_type = ContentType.objects.get_for_id(content_type_id) print(object_id_data) print(content_data) new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id_data, content=content_data, ) else: β¦ -
Multiple storage containers in Django
Is it possible in Django to store image files in different buckets/containers in external object storages such as S3, OpenStack Swift etc.? Thanks for the help. -
How to Build a Django Ajax Decorator? [duplicate]
This question already has an answer here: Django - Custom decorator to allow only ajax request 2 answers I would like to ask about how i can create a Django Decorator with a function. To get for example an Ajax request on my views. def ajax_test(request): if request.is_ajax(): message = "This is ajax" else: message = "Not ajax" return HttpResponse(message) Into: @api_views[Ajax] -
django allauth email signup - custom logic
I am using django 1.10 and django-allauth for authentication on my website. For email/password (i.e. non social) login, I want to be able to place code to check the email - so that I DISALLOW signup from certain well known spammy domains. So I want to incorporate logic like this: BANNED_DOMAINS = ('foobar.com', 'foo.biz', 'example.') def email_has_banned_domain(email): found = False for x in BANNED_DOMAINS: if x in email: found = True break return found How do I then, incorporate this simple function to the allautrh workflow, to prevent singups from banned domains? -
Sending GET/POST requests to Google APIs from Django
I have a Django 1.10 project from which I have to make GET/POST requests to Google APIs. I have succeeded to pass Google OAuth 2.0 authorization process in the following code: def a_oauth2(request): flow = client.flow_from_clientsecrets('client_secrets.json', scope=..., redirect_uri=) flow.params['access_type'] = 'offline' # offline access flow.params['include_granted_scopes'] = 'true' # incremental auth if 'code' not in request.GET: auth_uri = flow.step1_get_authorize_url() return HttpResponseRedirect(auth_uri) else: auth_code = request.GET['code'] credentials = flow.step2_exchange(auth_code) http_auth = credentials.authorize(httplib2.Http()) And here's where I am stuck. My goal now is to export Google Drive document. The question is, how do I retrieve the OAuth token and pass it to the respective GET request? And how does the discovery.build(...) method fit into the story? Help me please, I have spent two days trying to solve this :((