Skip to content

Instantly share code, notes, and snippets.

@bramburn
Created October 30, 2019 13:28
Show Gist options
  • Save bramburn/d6b2b026f47b83e109613d740c022e6c to your computer and use it in GitHub Desktop.
Save bramburn/d6b2b026f47b83e109613d740c022e6c to your computer and use it in GitHub Desktop.
Example of calling another view from a new view in Django
from django.http import Http404, HttpRequest, QueryDict, HttpResponse
from . import views
import json
# The following code sample shows you how to call another method
# from a view to another. This is pretty useful if you're querying internal APIs.
# I normally have separate views for public and cron type Apis, sometimes you want to call
# an existing view and get the information (or process something) rather than using the requests method in python.
def main(request):
# Start by initialising the HttpRequest() class
req = HttpRequest()
# Create a QueryDict for POST or GET, you can also modify other class variables
req.GET = QueryDict("hash=12312323&hello=123" , mutable=False)
# Call up the views.py OldMethod
jsonResponse = views.OldMethod(req)
# Process the returned JsonResponse()
jsonData = json.loads(jsonResponse.content)
# you can also check if it returned a 200 status code
if (jsonResponse.status_code == 200):
# do what you want here
return redirect(jsonData['signed_url'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment