I'm working through the random machine example, but I'm having trouble. I've installed Dajax and Dajaxice according to these two pages: Dajax and Dajaxice. My ajax.py file looks like this:
import random
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def randomize(request):
dajax = Dajax()
dajax.assign('#result','value',random.randint(1, 10))
return dajax.json()
Here's my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
def dajax(request):
return render_to_response( 'dajax.html', context_instance=RequestContext(request) )
Here's my urls.py:
from django.conf.urls.defaults import patterns, include, url
from dajaxice.core import dajaxice_autodiscover
from dajaxice import urls
from django.conf import settings
from Dajax.myapp.views import dajax
dajaxice_autodiscover()
urlpatterns = patterns('',
(r'^%s/' % (settings.DAJAXICE_MEDIA_PREFIX), include('dajaxice.urls')),
(r'^dajax/$', dajax),
)
My html form tag looks like this:
<form>
<input type="text" name="result" value="" id="result">
<input type="button" name="rand" value="Let's Rand!" id="rand" onclick="Dajaxice.myapp.randomize(Dajax.process); return false;">
</form>
Here's what my head tag looks like:
<head>
<title>My base template</title>
{% dajaxice_js_import %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript" charset="UTF-8"></script>
<script src="{{ STATIC_URL }}js/jquery.dajax.core.js" type="text/javascript" charset="UTF-8"></script>
</head>
I added the following to my init.py file in my project dir:
from myapp.ajax import randomize
Also of note, my Django app's name is myapp.
On my page, when I click on Let's Rand!, the page goes to http://localhost:8000/dajax/?result=2, and no value shows up in the text input box. I checked the console in Chromium and there aren't any errors.
Did I incorrectly install either Dajax or Dajaxice, or is there something wrong with my code above?
My guess is that because I'm using jQuery instead of Prototype, there's something different I need to do.
Thanks for your help!
You need a return false; in your onClick handler after the call to Dajax.
put this in your views.py :
from dajaxice.core import dajaxice_autodiscover
dajaxice_autodiscover()
You need to make sure that the app you are trying to import the ajak.py file from is in your INSTALLED_APPS in settings.py.
See the source for autodiscover:
http://docs.dajaxproject.com/dajaxice/_modules/dajaxice/core/Dajaxice.html
Related
Can someone advise what is the cleanest/easyest way to connect my query to the Data/Label part of chart.js script?
Thank you in advance.
For example, you can do this in your views.py:
# inside views.py
from django.views.generic import View
from django.shortcuts import render
class YourView(View):
def get(self, request, *args, **kwargs):
context = {} # <- you can add whatever you want in here
# some code...
return render(request, "path/to/js/file", context, content_type="text/javascript")
Inside your urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path("data/js", views.YourView.as_view(), name="somejs"),
# and other urls...
]
Inside your template (html file)
<!-- this is just an example -->
<div>
<canvas id="myChart"></canvas>
<script type="text/javascript" src="{% url 'somejs' %}"></script>
<div/>
Inside your js file, you can do some javascript.
var chart = document.getElementById("myChart");
"{{some_context}}" // you can access to the context
{% if some_context %}
// do something
{% endif %}
I am trying to make a Django based website, and I want to make a dropdown with if and else conditions working on it, means that if a person selects physics in the dropdown and presses the submit button, it should go to a specific page and if he presses chemistry then it goes to a specific page, please tell me how to do this, I am attaching my code.
Main page (home.html):
<!DOCTYPE html>
<html>
<head>
<title>Hi there</title>
</head>
<body>
<form action="{% url 'test' %}">
<select name="Subject">
<option value="Mathematics">Mathematics</option>
<option value="Physics">Physics</option>
<option value="Chemistry">chemistry</option>
<option value="accounts">accounts</option>
<option value="bsuiness">business</option>
</select>
<input type="submit" value="Generate Password" class="btn btn-primary">
</form>
</body>
</html>
Views.py:
from django.shortcuts import render
def home(request):
return render(request, 'homepage/home.html')
def test(request):
if request.GET.get('Physics'):
return render(request, 'homepage/home.html')
else:
return render(request, 'homepage/test2.html')
urls.py
from django.contrib import admin
from django.urls import path
from homepage import views as home_views
from homepage import views as test_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_views.home, name='home'),
path('test/', test_views.test, name='test'),
Please help by telling what to code to make the if statement work
You don't need to add if statement to your django code
Django's backend framework which means you can't do any dinamic change on page.
button generate link
1)https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
then make more pages and root them
2)https://docs.djangoproject.com/fr/3.1/topics/http/urls/
Before Django please try make a webpage on HTML + CSS + Js
What you want to do is capture the GET/POST request (that you send with your form submit button) in Django, then you get the dropdown parameter and then based on that condition, you can decide which webpage on which url Django will serve.
Then on the client side you have to handle going to the url that you decided to serve with Django.(This can be done with javascript)
I am using Django 1.8 and Python 3.5
This is my urls.py file
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
urlpatterns = [
# Examples:
url(r'^$', 'mainpage.views.home2', name='home2'),
url(r'^currency/(?P<currencywa>[\w]+)', 'currency.views.curr1', name='curr1'),
url(r'^userpage/', 'login.views.userpage', name='userpage'),
]
I am trying to make links using Jquery for Django
what I want to do is this
test // this resides in a table
using jquery
I wish to use urlnames instead of url that is I wish to use name='curr1'
var typein="test";
$('#cryptotable > tbody:last-child').append('<tr id=\"5\"><td>data1</td> </tr>');
I want to do this equivalent in django
test
But when I click on this ,I get redirected to http://localhost:8000/{% url 'curr1'%} instead of http://localhost:8000/curr1}
What do I do to use Django way of url links made using Jquery ?
IN OTHER WORDS
I wish to do this (Dynamically using Jquery)-->
<html>
<body>
<a href='{% url "curr1" %}'>test</a>//put this duynamically using Jquery
</body>
</html>
I am just writing a sample template for general use case:
Template:
{% load staticfiles %}
<?xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>sample</title>
<script type="text/javascript" src="{% static 'jquery.min.js' %}"></script>
</head>
<body>
</body>
</html>
<script>
var typein = "<a href = {{url}}>Click Here</a>";
$('body').append(typein);
</script>
View:
from django.shortcuts import render_to_response
from django.template import RequestContext
def home(request):
url = "home"
return render_to_response('home.html', {'url' : url}, RequestContext(request))
URL:
from django.views.generic import TemplateView
from django.contrib.sitemaps.views import sitemap
from django.conf.urls import include, url
from django.contrib import admin
from views import *
urlpatterns = [
url(r'^$', home),
url(r'^home/', home),
url(r'^robots.txt/', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
url(r'^sitemap.xml/', TemplateView.as_view(template_name='sitemap.xml', content_type='text/xml'))
]
The url template tag needs to be converted to a full URL during template rendering inside the server. Once the HTML reaches the client browser, javascript cannot make that transformation from url tag to full URL.
You could render the URL in a hidden part of your HTML document, so that javascript can access the URL later (in the browser) and place it inside a table, for example (like the other answer to this question shows in the example).
My views.py file is as follows:
from django.shortcuts import render, render_to_response
from chartit import DataPool, Chart
from chartit.chartdata import DataPool
from weather.models import MonthlyWeatherByCity
import simplejson
from chartit import DataPool, Chart
def weather_chart_view(request):
ds=DataPool(series=[{'options': {'source': MonthlyWeatherByCity.objects.all()},'terms': ['month','houston_temp','boston_temp']}])
cht = Chart(datasource = ds, series_options =[{'options':{'type': 'line','stacking': False},'terms':{'month': ['boston_temp','houston_temp']}}],chart_options ={'title': {'text': 'Weather Data of Boston and Houston'},'xAxis': {'title': {'text': 'Month number'}}})
return render_to_response('chart.html',{'weatherchart': cht})
The urls.py file inside the app is as follows:
from django.conf.urls import include, url
from django.contrib import admin
from weather import views
urlpatterns = [
url(r'^$', views.weather_chart_view , name='weather_chart_view')
]
The models.py file is as follows:
from django.db import models
class MonthlyWeatherByCity(models.Model):
month = models.IntegerField()
boston_temp = models.DecimalField(max_digits=5, decimal_places=1)
houston_temp = models.DecimalField(max_digits=5, decimal_places=1)
The chart.html file is as follows:
<head>
<!-- code to include the highcharts and jQuery libraries goes here -->
<!-- load_charts filter takes a comma-separated list of id's where -->
<!-- the charts need to be rendered to -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script src="/highcharts.js" type="text/javascript"></script>
{% load chartit %}
{{ weatherchart|load_charts:"container" }}
</head>
<body>
<div id='container'> {{ weatherchart|load_charts:"container" }}</div>
</body>
On running the server and opening the app I am getting the error:
TemplateSyntaxError at /weather/
'chartit' is not a valid tag library: ImportError raised loading chartit.templatetags.chartit: cannot import name simplejson
I have also included the app, chartit and json in the INSTALLED_APPS.
As you can see I have also imported simplejson in views. Where am I going wrong?
Please suggest if I need to post anything else to make the problem lucid.
There is a fix for the problem on the github page of the project. Do a pip install simplejson and then locate the file chartit/templatetags/chartit.py in the chartit module and replace the line of simplejson import as shown below.
from django import template
-from django.utils import simplejson
+import simplejson
from django.utils.safestring import mark_safe
It looks like a hack but works till the fix is merged.
You need to add chartit to INSTALLED_APPS in "settings.py"
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chartit',
)
Then, follow #akoshodi 's response.
In latest version of chartit (0.2.8) issue is fixed, so the only thing that you should do is to add 'chartit' in INSTALLED_APPS exactly as #MiaeKim mentions.
I'm a newbie to Django and created a sample project with an app:
views.py
from django.http import HttpResponse,Http404
from django.contrib.auth.models import User
from django.template import Context
from django.template.loader import get_template
def main_page(request):
template = get_template('main_page.html')
variables = Context({
'head_title': u'Django Bookmarks',
'page_title': u'Welcome to Django Bookmarks',
'page_body': u'Where you can store and share bookmarks!'
})
output = template.render(variables)
print 'output',output
return HttpResponse(output)
urls.py
from django.conf.urls.defaults import patterns, include, url
from bookmarks.views import *
urlpatterns = patterns('',
(r'^$',main_page),
(r'^user/(\w+)/$',user_page),
#(r'login/$','django.contrib.auth.views.login')
)
main_page.html
<html>
<head>
<title>{{head_title}}</h1>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>
When I print the output variable, I see everything perfectly all right but when I run the server and point to the page, I see a blank page.
You are missing the closing tag </title>
Your template should look like this
<html>
<head>
<title>{{head_title}}</title>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>