How to add Variable to JSON Python Django

How to add Variable to JSON Python Django

Content Index :

How to add Variable to JSON Python Django
Tag : python , By : Simone
Date : November 27 2020, 09:01 AM

seems to work fine i just made this i load the json from the google Response before make jason.dumps like in this code .
class GetRouteDriver(APIView):
    authentication_classes = (TokenAuthentication,)    
    permission_classes = (IsAuthenticated,)
    def get(self, request, username, origin, destination):  
        origin_lat, origin_lng = origin.split(',')
        destination_lat, destination_lng = destination.split(',')

        url = 'https://maps.googleapis.com/maps/api/directions/json?origin=' + origin + '&destination=' + destination + '&key'+ GOOGLE_KEY 
        request_data = urllib2.urlopen(url)
        #serialized_data = request_data.read()

        serialized_data = json.dumps( { 'ride_id': 1 , 'route': json.loads(request_data.read()) })
        route = json.loads(serialized_data)
        return Response( route, status=status.HTTP_200_OK )

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

python django API authentication post request - output variable displaying json string in browser, but NOT when printed

Tag : python , By : Munir
Date : March 29 2020, 07:55 AM
should help you out , you should instead use

django python: how to make json from django queryset

Tag : python , By : Lex Viatkine
Date : November 14 2020, 06:58 AM
like below fixes the issue Firstly, there's an error in your expected output. You probably meant:
[{"pid": 1,
  "s": [{"sid": 1, "sd": "south-1"},
        {"sid": 2, "sd": "north-5"},
        {"sid": 3, "sd": "west-3"}
  "loc": "KL"
>>> q = ... # as above
>>> r = {"pid": q[0]["pid"], "loc": q[0]["loc"]}  # since pid and loc are always the same
>>> r["s"] = [{"sid": x["sid"], "sd": x["sd"]} for x in q]
>>> print r
[{'pid': 1,
  's': [{'sid': 1, 'sd': 'south-1'},
        {'sid': 2, 'sd': 'north-5'},
        {'sid': 3, 'sd': 'west-3'}
  'loc': 'KL'
>>> print json.dumps(r)  # gives the output as a json string

Pass python/django variable into javascript as JSON?

Tag : javascript , By : user112141
Date : March 29 2020, 07:55 AM
To fix this issue Woking on personal project website with django 1.9 and python 3.4. I am using FullCalendar. The idea is to pass a set of appointment objects into the html page containing the javascript for the calendar. But right now, I am just trying to pass a single default appointment. , Just use the safe filter:
var data = jQuery.parseJSON('{{appt | safe}}');
var apptData = {{ appt | safe }};

Error while using function name as a variable in Pycharm, Python, Django: local variable 'processed' referenced before a

Tag : python , By : user157138
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I use Pycharm Professional 2019.2, Python 3.7.4, Django 2.2.5. As I know, function names are global variables in modules. But I have a function that denies that. , One simple solution is to do:
def processed(request):
    # Do not use the function name as the parameter name.
    ret = processed

    # It should be 'POST', not 'post'.
    if request.method == 'POST':
        # It should be 'POST', not 'post'.
        text = request.POST['text']
        ret = text.upper()

    return HttpResponse(ret)

Python / Django / Jinja2: How to extend a variable name with the value of another variable (e.g. in a for-loop)?

Tag : python , By : Sonal
Date : March 29 2020, 07:55 AM
it should still fix some issue The recommended approach for complex logic in templates is to write the logic in a model method, rather than in the template itself.
In your case, I think this is what you want:
class SomeModel(models.Model):
    slider_image_1 = models.ImageField(upload_to='images/', blank=True)
    slider_image_2 = models.ImageField(upload_to='images/', blank=True)
    slider_image_3 = models.ImageField(upload_to='images/', blank=True)
    slider_image_4 = models.ImageField(upload_to='images/', blank=True)
    slider_image_5 = models.ImageField(upload_to='images/', blank=True)

    def slider_images(self):
        fields = [field.name for field in self._meta.get_fields()]
        results = []
        for field in fields:
            if 'slider_image' in field:
                data = getattr(self, field)
                if data:

        return results

    def slider_images(self): # simplified version
        results = [getattr(self, field.name) for field in self._meta.get_fields() 
        if 'slider_image' in field]
        return [result.url for result in results if result]
{% for url in object.slider_images %}
  <img src="{{ url }}">
{% endfor %}
Related Posts Related QUESTIONS :
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com