pass data from Django view to react - django

I have a django view that returns a variable in order to be rendered in template
return render_to_response('index.html', {
'courses': courses})
I'm using ReactJS to render the index.html file, but I'm not sure whether i have to point to index.html in my view or the ReactJS file.
If I have to point to index.html how can I use the courses variable with React ?
Update
the variable courses that i'm passing is of type dictionnary

Templates processing is anterior to any sort of JavaScript interpretation. This means that you will have to, in some sense, emulate its hardcoding beetween the js tags.
First, know that the python dictionary is likely to be corrupted when received on the client side. To prevent this, you may want to send it as a json object. Which means that, in you script views.py, you will have to json.dumps your dictionary. As follows
from django.shortcuts import render
import json
#...
#...
return render(request,
'your_app/index.html',\
{'courses': json.dumps(courses)}\
)
Note that I use render instead of render_to_response, because render is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext
Also, note that you do have to point to your index.html, but the exact path depends on the strucutre of your project. Above, I assume you followed the recommended django project layout, i.e.
myproject/
manage.py
your_project/
__init__.py
urls.py
wsgi.py
settings/
__init__.py
base.py
dev.py
prod.py
your_app/
__init__.py
models.py
managers.py
views.py
urls.py
templates/
your_app/
index.html
[...]
Then, on the html side,
...
<script>
var courses = {{courses|safe}}
// working with the variable courses
</script>
...
Now, you can do what you want with it, be it with ReactJS library.

Related

How to create hierarchical urls within django app?

I have multiple app based django project and within some apps url scheme getting complicated due to number of models. Hence I'm looking a way to make a hierarchical url structure within the app.
In my project's urls file I do the following.
from order import urls as order_urls
In the order app I have urls.py and urls directory which contains separate url patterns for each model as follows.
In the app's urls.py file I import the model's urls as follows.
from urls import rental as rental_urls
urlpatterns = [
url(r'^rental-request/', include(rental_urls)),
]
This gives me the error: ModuleNotFoundError: No module named 'urls'
If I put __init__.py it gives me circular import error.
I'm not sure this is the correct way/possible for my requirement. Anyone could explain the correct way to achieve it?
Having a folder called urls (with an __init__.py file) as well as a file urls.py in the same folder will probably cause trouble to load the module order.urls from anywhere in your project. How does Python will know which file must be loaded ?
Consider this structure:
├── main.py
├── urls
│   └── __init__.py
└── urls.py
And this content for each file:
# urls/__init__.py
urlpatterns = "I'm in folder"
# urls.py
urlpatterns = "I'm in file"
# main.py
import urls
print(urls.urlpatterns)
When you run main.py, the result is:
% python main.py
I'm in folder
Possible solutions :
You may delete the urls.py and move its content to urls/__init__.py, or rename the folder urls to avoid conflicts and updates imports accordingly (in urls.py)

Django: how to simplify calls for rendering templates from subdirectory

I have django project with a couple applications. To be able use templates with common names (like index, menu, ..., page1, page2) in more then one of them I adopted this schema:
app1/
templates/
app1/
page1.html
page2.html
app2/
templates/
app2/
page1.html
page2.html
and in views I use it like that:
def myview(request): # in app1
context={'name':'John', 'surname':'Lennon'}
return render(request,"app1/page1.html",context)
or
def myview(request): # in app2
context={'tool':'hammer', 'size':'big'}
return render(request,"app2/page1.html",context)
it works, but I have to write the full app name (app1/, app2/) in each and every render (and no app uses templates from other app or just from templates/ (except the project itself) ) and the apps names are actually long like 10-17 characters (not short as app1, app2)
The question: is there a way to do it better, that each applications render would not default to templates/ but to templates/app1/, templates/app2/ and so, respectively?
Thanks for all suggestions
One simple solution is, you can declare the path on top of the app or in settings.py and use that variable in entire script, for example:
path1 = "app1/templates/"
path2 = "app2/templates/"
def myview(request): # in app1
context={'name':'John', 'surname':'Lennon'}
return render(request,path1+"page1.html",context)
def myview(request): # in app2
context={'tool':'hammer', 'size':'big'}
return render(request,path2+"page1.html",context)
This can also reduce the typing efforts.

Import relative apps in Django

I'm new to Django and have a question about app structure and imports. My project structure looks like this (from deploydjango.com):
root/
manage.py
mysite/
__init__.py
urls.py
wsgi.py
settings/
apps/
__init__.py
profile
__init__.py
models.py
views.py
video
__init__.py
models.py
views.py
photos
__init__.py
models.py
views.py
Basically I will have some profiles on my site, where each profile then have a number of uploaded photos and videos. So in my video model I have the following code:
from django.db import models
from XXXXX import Profile
class Video(models.Model):
# more fields
company = models.ForeignKey(Profile, related_name='videos')
How do I import the Profile model for use in the Video model? Or is my structure not suitable..? What would be best practice for this?
I think your structure is fine. Basically, python's modules are just a python file which you may import like this: import <filename> and you will have its functionality imported. But when you group some python files in a folder and include in that folder a file called init.py there you have a python package. With is a better way to manage a group of modules and it allows the dot notation in your imports. Django apps behave like packages as you may see.
If you want to import Profile within your video module then you have to do this:
from profile.models import Profile
That is, assuming that the Profile model is defined in your profile app in models.py. That should do.
If you want more information about python project structure this is a great place.

ImportError After Moving App to Nested Folder

My application was working fine when I wanted to see whether I could organize my project in a better way. I read through this tutorial on structuring a django project.
Before my project structure was as follows:
camucamu
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
What I wanted to do was move the books app into an apps folder. Thus I did that and changed the project structure to the following:
camucamu
apps
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
I then changed the imports in views.py and admin.py
from books.models to apps.books.models.
I also changed INSTALLED_APPS in settings.py from books to apps.books.
When I then tried to run syncdb, I get the following error:
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
django.core.exceptions.ImproperlyConfigured: ImportError apps.books: No module named apps.books
What am I messing up here so it can't find my app anymore?
Your apps folder does not have an __init__.py file so it cannot be recognized as a python module
I got the same error, following the same guide, as the last point of the following list was not cited. Make sure you performed the following changes:
Create a blank __init__.py file inside the apps folder (needed for python to recognize it as a package)
Update the import statements wherever you refer to an external app:
from projectname.apps.appname.models import YourModel, YourOtherModel
Inside settings.py edit INSTALLED_APPS such that it looks like this:
INSTALLED_APPS = (
...
# apps
'projectname.apps.appname1',
'projectname.apps.appname2',
)
This one is not specified in the guide: In all your urls.py files, update the urlpatterns!
BEFORE:
# client views
urlpatterns += patterns('appname',
...
)
AFTER:
# client views
urlpatterns += patterns('projectname.apps.appname',
...
)
Finally remember to update your changes by calling python manage.py syncdb
Hope that helped.

Django view - load template from calling app's dir first

I try to keep a somewhat consistent naming scheme on my HTML templates. I.e. index.html for main, delete.html for delete page and so forth. But the app_directories loader always seems to load the template from the app that's first alphabetically.
Is there any way to always check for a match in the calling app's templates directory first?
Relevant settings in my settings.py:
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.filesystem.load_template_source',
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
)
I've tried changing the order of TEMPLATE_LOADERS, without success.
Edit as requested by Ashok:
Dir structure of each app:
templates/
index.html
add.html
delete.html
create.html
models.py
test.py
admin.py
views.py
In each app's views.py:
def index(request):
# code...
return render_to_response('index.html', locals())
def add(request):
# code...
return render_to_response('add.html', locals())
def delete(request):
# code...
return render_to_response('delete.html', locals())
def update(request):
# code...
return render_to_response('update.html', locals())
The reason for this is that the app_directories loader is essentially the same as adding each app's template folder to the TEMPLATE_DIRS setting, e.g. like
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'app1', 'templates'),
os.path.join(PROJECT_PATH, 'app2', 'template'),
...
os.path.join(PROJECT_PATH, 'templates'),
)
The problem with this is that as you mentioned, the index.html will always be found in app1/templates/index.html instead of any other app. There is no easy solution to magically fix this behavior without modifying the app_directories loader and using introspection or passing along app information, which gets a bit complicated. An easier solution:
Keep your settings.py as-is
Add a subdirectory in each app's templates folder with the name of the app
Use the templates in views like 'app1/index.html' or 'app2/index.html'
For a more concrete example:
project
app1
templates
app1
index.html
add.html
...
models.py
views.py
...
app2
...
Then in the views:
def index(request):
return render_to_response('app1/index.html', locals())
You could even write a wrapper to automate prepending the app name to all your views, and even that could be extended to use introspection, e.g.:
def render(template, data=None):
return render_to_response(__name__.split(".")[-2] + '/' + template, data)
def index(request):
return render('index.html', locals())
The _____name_____.split(".")[-2] assumes the file is within a package, so it will turn e.g. 'app1.views' into 'app1' to prepend to the template name. This also assumes a user will never rename your app without also renaming the folder in the templates directory, which may not be a safe assumption to make and in that case just hard-code the name of the folder in the templates directory.
I know this is an old thread, but I made something reusable, that allows for simpler namespacing. You could load the following as a Template Loader. It will find appname/index.html in appname/templates/index.html.
Gist available here: https://gist.github.com/871567
"""
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages, prefixed by the appname for namespacing.
This loader finds `appname/templates/index.html` when looking for something
of the form `appname/index.html`.
"""
from django.template import TemplateDoesNotExist
from django.template.loaders.app_directories import app_template_dirs, Loader as BaseAppLoader
class Loader(BaseAppLoader):
'''
Modified AppDirecotry Template Loader that allows namespacing templates
with the name of their app, without requiring an extra subdirectory
in the form of `appname/templates/appname`.
'''
def load_template_source(self, template_name, template_dirs=None):
try:
app_name, template_path = template_name.split('/', 1)
except ValueError:
raise TemplateDoesNotExist(template_name)
if not template_dirs:
template_dirs = (d for d in app_template_dirs if
d.endswith('/%s/templates' % app_name))
return iter(super(Loader, self).load_template_source(template_path,
template_dirs))
The app_loader looks for templates within your applications in order that they are specified in your INSTALLED_APPS. (http://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types).
My suggestion is to preface the name of your template file with the app name to avoid these naming conflicts.
For example, the template dir for app1 would look like:
templates/
app1_index.html
app1_delete.html
app1_add.html
app1_create.html