Passing django settings to django template using angularjs - python

I have this settings.py that include my global_constants.py
Now I want to access the Constants that I have defined in my global_constants.py in my Django Template using Angular JS. How to do that?
My global_constants.py contaains the following function:
def my_image_urls(request):
return {
"URL_ONE": "http://mywebsite.com/IMAGE/Image_one",
"URL_TWO": "http://mywebsite.com/IMAGE/Image_two",
}
Now I want to Access this URL_ONE and URL_TWO in my template/index.html which is called by my Views.py. But MY PURPOSE IS TO CALL THIS USING ANGULARJS into my template. How exactly I can achieve that. Need an overview so that I get on right direction :)
How I want to use it in my Templete is like this:
{{ URL_ONE }} /myimage.jpeg
{{ URL_TWO }} /myimage_two.jpeg
PLEASE NOTE THAT I AM USING ANGULARJS FOR MY TEMPLATE

For getting values from django into angularjs there are two main ways:
Create a view that returns JSON
In the view that serves your angularjs application, use django templates to encode extra information either into a script tag or data attributes.
So if you absolutely do not want to use any django templating then your angular js app will need to call your JSON settings view.
If you wish to eliminate that initial round trip then use django templating to inject your values into javascript:
<script type="text/javascript">
var DJANGO_URLS = {URL_ONE: "{{URL_ONE}}", URL_TWO: "{{URL_TWO}}"};
</script>
Your angular app can now access the variables globally (ie window.DJANGO_URLS).

Related

How do I emit the HTML of an external website in a Django template?

I want to get the contents of one of my pages on an external site, the HTML and all contents. If were in .NET I could use WebClient and retrieve the page, save it to a variable, and emit it in Razor. PHP can use cURL.
How can I do that in a Django template? Do I need to create a Plugin that uses urllib?
If it matters, I am using DjangoCMS. I searched and tried the Django http module.
I have looked at the helper Django module for http and didn't see anything. I wasn't sure where to put urllib or requests, as in I do not know if what I am trying to do requires me to build a plugin or a custom template tag.
I was hoping to know how to do it with either Python and Django's template language or just the template language, so I really do not want to do this in JavaScript, iframe, object, etc.
You can use the reqeusts library, and define a function as a part of a view.
Alternatively you can define a simple tag if you want it to be globally accessible.
For instance
import requests
from django import template
register = template.Library()
#register.simple_tag
def get_site_source(url):
res = requests.get(url)
return res.text
and in the template:
...
{% get_site_source url %}
...

Django Variable Template Tags

<p>Hello, my name is {{ name }} ! </p>
Where/how do I set the variable: name = 'mike'? I've tried putting this in the settings.py and models.py file and it does not work.
Any info of proper code to put in a .py file would be great! I've searched through the docs page but didn't see how to set a variable for retrieval.
You need to set your variable value in the view function which normally put in view.py
e.g.
def hello(request):
return render(request, "hello.html", {"name": "mike"})
And you may would like to check https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render to find more about how to render templates with passed variables.
You need also learn more about how does Django's URL mapping works https://docs.djangoproject.com/en/dev/ref/urls/
Use context processors in django. Django handles this dilemma of making some information available to
all pages with something called context processors.
Some Code is like this,
Create a new file called context_processors.py inside your utils app directory, and add the
following code to it:
from project import settings
def context_data(request):
return {
'name': settings.name,
'request': request
}

How to avoid hardcoded template name in a django app, integrated with django-cms?

I have a custom Contact Form App, and I want to integrate it with django-cms. From what I understand I have to register the app with django-cms, and then in my views I have to return a RequestContext instance instead of a regular context instance. So in my views.py, I have
return render_to_response('my_template.html',
{'form': form},
context_instance=RequestContext(request))
I don't know if I'm missing something here, but my issue here is that I don't want to hardcode the template name my_template.html. Instead, I want the template to be the same one I put when adding a new page, so my question is, is there a way to get the template from the django-cms page thats hosting the app or do I have to hardcode the template to be used?
If your apphook is a single view mounted on /, you can just use {% extends request.current_page.get_template %}, however this does not work on subpages in your app.
For that you would need to reverse the root view of your app, use cms.utils.page_resolver.get_page_from_request with the use_path argument to get the page, then call get_template on the page and extend that.

Locating django app resources

tl:dr
How would a hosted django app correctly transform resource paths to match any hosted location (/ or /test or /testtest)?
Full Description
Let me try to explain what I am trying to do.
I am trying to write a somewhat re-usable django app which I intend to use from within multiple projects. This app is called systemstatus.
The systemstatus app provides a page under '$^' which provides a simple interface to query the system status.
This page makes an ajax query back to the systemstatus app to determine the actual system status and report it on the UI.
The systemstatus app provides a location '^service/$' which points to the ajax call handler.
This page has to somehow figure out the correct URI for the ajax handler depending on where this app is hosted (e.g. under / or /status or /blahblah).
I am wondering what an ideal way of doing this would be. I would say that this applies to other resources bundled inside the app too (stylesheets, images).
Right now I am using request.path to determine what the target path should be. This path is then passed down as a parameter to the template. But this approach will soon become too cumbersome to handle.
def system_status (request):
queryPath = request.path + "service/"
return render_to_response ('systemstatus.html', {'queryPath': queryPath})
My page template looks like this:
function do_ajax () {
$.getJSON ('{{ queryPath }}', function (data) {
$("#status").html (data.status);
});
}
Thanks!
You shouldn't hardcode your urls like that, but use reverse instead!
Django also has a built-in template tag to reverse urls. So you could do something like
function do_ajax () {
$.getJSON ('{% url path.to.my_ajax_view %}', function (data) {
$("#status").html (data.status);
});
}
directly in your template!
You can also send the ajax request directly to your current page's url and check if it is an ajax request or not:
def my_view(request):
if request.is_ajax():
# generate response for your ajax script
else:
# generate the response for normal request
# (render template of your page)

How do I add data to an existing model in Django?

Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface.
You will want to wire your URL to the Django create_object generic view, and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.
Sample URLconf for the simplest case:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
This topic is covered in Django tutorials.
Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.
Django Admin Setup
Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.

Categories

Resources