1

I get really confused about django and file locations a lot, and I'm on django 1.10. But in my static/(django-proj-name)/js/ folder (just showing the way I have my main.js file and I need to call a python script, in conjunction with the jquery tokeninput plugin. Lets call the script keywords.py

This script is going to need to call all instances of a model, Keyword, so I need to be able to import from my models file.

Im' a bit inexperienced with django, but from reviewing some of the projects I've seen over the summer I was startinng to believe that including the line, from (django-proj-name).models import * was the main way to import from models. This at least works for all of the files that I have in my /management/commands/ folder.

But i tried putting keywords.py in my static folder just because I know at the very least I can use the {% static %} template tag to find the file in html. I ran the file without manage.

Traceback (most recent call last):
  File "../../management/commands/import_statements.py", line 5, in <module>
    from gtr_site.models import *
  ImportError: No module named gtr_site.models

Though I have the same importation line, again, in /management/commands/. And that doesn't cause any problems.

So I didn't put the file in the "correct" file location... I didn't put keywords.py in a place where

  1. I know how to import from my models.py file from the keywords.py script's location

  2. My javascript file can find it and run it without crashing. This script needs to be able to successfully import from models.

so where am I supposed to put this script, or how can I specify a location for it?

5
  • You need to define a Django "view" that will be called from Javascript, and map this view to the URL you want to call in order to return the data consumed by the JS client. Possibly a dupe of stackoverflow.com/questions/13175510/… Commented Sep 4, 2017 at 20:39
  • @PauloScardine So that's new to me. I assume I'll have to use ajax right? For something similar to the following question... stackoverflow.com/questions/31878960/… Do you got any tips on what I could look up to help out? Commented Sep 4, 2017 at 20:45
  • Just to clarify the above, make an Ajax call to the view, the view calls the python function and return the result/data. You cannot run Python code from the client side but from the server side. Commented Sep 4, 2017 at 20:46
  • @deaspo thank you. Again if there's any documentation or video you know that I should be looking at for help, please let me know. Commented Sep 4, 2017 at 20:48
  • For implementing Ajax in your project see the official documentation Link, meanwhile search for Django ajax from Google and you will find several examples on how toimplement it. @byronSmith Commented Sep 4, 2017 at 21:00

1 Answer 1

2

Let's say you have a js library that expects data in the following format:

 {"results": [
    {"name": "Foo", "number": 1}, 
    ..., 
    {"name": "Bar", "number": 999}
 ]}

You started an application called myapi:

  $ django manage.py startapp myapi

And suppose you have a Model like this at myapi/models.py:

 from django.db import models

 class Foo(models.Model):
     name = models.CharField(max_lenght=100),
     number = models.IntegerField()

In myapp/views.py define the following view:

from django.http import JsonResponse
from django.views import View
from .models import Foo

class FooList(View):
    def get(self, request, *args, **kwargs):
        qs = list(Foo.objects.values('name', 'number').all())
        data = {"results": qs}
        return JsonResponse(data)

Then map this view to some url. For the sake of simplicity let's just add this to your main urls.py file:

url('api/v1/foo/$', FooList.as_view(), name='foo-list'),

Now you should be able to reach it from the browser. The example below uses jQuery:

$.getJSON('http://yourdomain.com/api/v1/foo/', 
    function(data, textStatus, jqXHR) {
        console.log(data);
    }
)

That is it. I did this from memory so you probably will find a few errors or missing imports - but this should put you on the right track.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I wanted to ask though.... I'm not sure what the url path would be in my case given I'm working on a web application for getJSON would really be. I'm working on a development server at the moment. So I don't have a domain that would be suitable to copy and paste unless it was just the temp address of the dev server. I've created the view and url but I feel like I still sorta have the same question I began with. Javascript needs to look somewhere via getJSON and I'm not sure where.
Perhaps more info would be needed to answer that question... And I apologize. It's just that i read the stackoverflow question you linked previously and a commenter acknowledged how the most upvoted answer offers a url that wouldn't come anywhere close to what would be needed on a web application (since, the OP offered url: ~/yourscript.py)
you can try to use http://localhost:8000 that is the default address for the Django development server (the one you start by python manage.py runserver). If your browser is paranoid and prevent you from loading from localhost you can just map a random name, lets say, mydevenv.com to localhost (127.0.0.1) by editing your /etc/hosts file (\Windows\system32\drivers\etc\hosts on Windows) and use it: mydevenv.com:8000 will point to your local development server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.