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 %}
Related
So my Django form is not rendering in the html.
all I'm able to see is the Get Rank text.
I'm not sure if it's because I don't have a model or maybe it's something wrong with my html?
If you need to see anything else let me know not sure what's wrong, I also tried just doing it all inside of the home function but then it doesn't render the html at all.
Side question - Also I only plan on grabbing the users name, and the tag outside their name ("JohnDoeNA#1") so I probably use a get method correct?
EDIT: Fixed the button not working now only thing not rendering is the form. (Mis-spelling)
Updated Code to be correct.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def index(response):
return render(response, "main/base.html")
def home(response):
form = SearchUser()
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-ee8fcdce-05c5-4ad4-b909-8efa722b1134')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': form,
'userid': userid,
# 'mmr': apidata['rank']
})
forms.py:
from django import forms
class SearchUser(forms.Form):
name = forms.CharField(label="Name", max_length=200)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("home/", views.home, name="home")
]
home.html:
{% extends 'main/base.html'%}
{% block content %}
<h2>Valorant Ranked Checker</h2>
<form method="post" action="/home/">
{{form}}
<button type="submit", name="search">
Get rank
</button>
</form>
<p><strong>{{userid}} - {{mmr}}</strong></p>
{% endblock %}
base.html:
<!DOCTYPE html>
<head>
<title>Blue's Valorant Ranked Checker</title>
</head>
<body>
<div id="content", name="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
You have two main issues here:
You were rendering your base template as your root directory (base.html) and therefore Django's template inheritance wasn't working correctly. You'll want to render the child template (the one that includes extends) if you want template inheritance to work properly.
You need to pass your Django form (SearchUser) to the render function of the view
I recommend making these changes:
====================
Remove reference to the index view in your urls.py as we don't need it. Instead, use your home child template as your root view:
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home")
]
====================
Remove the no longer needed index function from views.py. You'll also want to pass reference to your form (SearchForm) inside of Django's render shortcut function.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def home(response):
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-APIKEY')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': SearchUser(), # include reference to your form
'userid': userid,
# 'mmr': apidata['rank']
})
def search(response):
form = SearchUser()
return render(response, "main/home.html", {"form": form})
Your view function that renders the form and the form template must match. form also must be in your context.
Put the form in the home.html and change the home view like so:
def home(response):
form = SearchUser()
return render(response, "main/home.html", {'form': form})
I am using django=3.0.0 as my backend. I have years in my database as a datetimefield and I want to put it as an option for my select button which will change the charts dynamically in chartjs.
Do I have to make a filter for this or is there any other way to put my years in chartjs.
Can anyone guide me how to do this?
Well, here's an example.
# views.py
class SomeView(View):
def get(self, request, *args, **kwargs):
context = {} # put some data here
return render(request, "pathto/jsfile.js", context)
# urls.py
urlpatterns = [
# ...
path("chart/js", views.SomeView.as_view(), name="js"),
# ...
]
# template
<!-- example -->
<div>
<canvas id="chart"></canvas>
<script type="text/javascript" src="{% url 'js' %}"></script>
<div/>
# jsfile.js
var chart = document.getElementById("chart");
{% if some_context %}
// do something
{% endif %}
I have simple requirement. There is a URL that is stored in DB. I need to retrieve this URL from the DB and in my template use this URL as SRC value in an iframe.
Model.py:
from django.db import models
# Create your models here.
class DashboardLink(models.Model):
dashboard_url = models.CharField(max_length=255, unique=True)
Views.py
from django.shortcuts import render
from .models import DashboardLink
def index(request):
dashboard_url = DashboardLink.objects.all()
return render(request, 'index.html')
In Index.html I have the following code, in which I want to use the url retrieved from the DB.
index.html
<p>{{ dashboard_url.dashboard_url }}</p> ### This is to just check if the data is being fetched or not.. This too results in blank. ####
<section>
<iframe width="100%" height="700" src="{% for item in dashboard_url %} {{ item }} {% endfor %}" frameborder="0" allowfullscreen></iframe>
</section>
<br><br>
</div>
In urls.py I have the following code:
*urls.py*
path('index/', logged_in_views.index, name='index'),
When I use Inspect, I see the following
[![enter image description here][1]][1]
Can someone please help me in understanding what am I missing?
[1]: https://i.stack.imgur.com/C7Oek.png
Send context to template:
def index(request):
dashboard_url = DashboardLink.objects.all()
context = { "dashboard_url": dashboard_url}
return render(request, 'index.html', context)
You can use models.URLField for urls too
Just quick info I'm a beginner in python and django.
Here is an issue:
I'm trying to create simple blog app with django, I've created all whats needed and I'm able to render one of my main pages however when I try to access posts page(to be able to view current posts) I receive the following error:
Request Method: GET
Request URL: http://localhost:8000/posts/
Django Version: 2.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post' not found. 'post' is not a valid view function or pattern name.
I'm not sure why I receive this error as I have posts view function written and accessible, here are my files:
my_blog/urls.py
"""Defines URL patterns for my_blog."""
from django.conf.urls import url
from . import views
#needed app name
app_name='my_blog'
urlpatterns=[
#Homepage
url(r'^$',views.home,name='home'),
# Show all posts.
url(r'^posts/$', views.posts, name='posts'),
models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
"""Post that can be viewed"""
title=models.CharField(max_length=200)
text=models.TextField()
date_added=models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
if len(self.text)<50:
return self.text
else:
return self.text[:50] + "..."
views.py
from django.shortcuts import render
from .models import BlogPost
from django.http import HttpResponseRedirect
# Create your views here.
def home(request):
"""The home page for Learning Log"""
return render(request,'my_blog/home.html')
def posts (request):
"""Show all posts."""
posts=BlogPost.objects.order_by('date_added')
context={'posts':posts}
return render(request, 'my_blog/posts.html', context)
HTML pages:
home.html
{%extends "my_blog/base.html"%}
{%block content%}
<html>
<p align="center">Welcome to my Blog</p>
</body>
</html>
{%endblock content%}
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Blog</title>
</head>
<body bgcolor="#85C1E9">
<p>
Home -
Posts
</p>
{%block content%}{%endblock content%}
</body>
</html>
posts.html
{%extends "my_blog/base.html"%}
{%block content%}
<p>Posts</p>
<ul>
{%for post in posts%}
<li>{{post}} </li>
{%empty%}
<li>No posts have been added yet.</li>
{%endfor%}
</ul>
{%endblock content%}
Thanks in advance for assistance
In your template you have:
{% url 'my_blog:post' post.id %}
This gives an error because you have not yet defined a URL pattern in my_blog/urls.py with name="post".
The view name that you are looking up in your template does not match the name defined in your urls.py. You need to make
urls.py
url(r'^posts/$', views.posts, name='posts'),
and
posts.html
<li>{{post}} </li>
match by either adding an s in posts,html or remove the s in urls.py
Edit
Looking a little deeper... You need to define your detail view (post with a parameter) in views.py. And add a corresponding entry in urls.py Then undo the change I recommended earlier.
You should also consider renaming your views from posts and post to something like post_list and post_detail
I want to use the content of a variable with the name "files" in my template in django. My views.py looks like this:
from django.shortcuts import render
import os
def index(request):
os.chdir("/home/ubuntu/newproject/static")
for files in os.listdir("."):
return render(request, 'sslcert/index.html','files')
And my template with the name "index.html" looks like this:
<head>
{% block title %}
<h3>
Following directories are in this folder:
</h3>
{% endblock %}
</head>
<body>
<<(HERE SHOULD BE THE OUTCOME OF THE VARIABLE LIST)>>
</body>
Help would be really cool and explanation too :/ I am a real beginner in django and I wish to know how this template and views stuff is connected :) please do not hate on me if this question is really stupid :(
You can pass variable to template like this:
from django.shortcuts import render_to_response
def index(request):
os.chdir("/home/ubuntu/newproject/static")
for file in os.listdir("."):
files.append(file)
return render_to_response('sslcert/index.html', {'files':files})
And in template you can use it like:
{{files}}
if you want to use whole field or you can loop through them
{% for file in files %}
# do something with file here
{% endfor %}
Do something like:
from django.shortcuts import render
import os
def index(request):
os.chdir("/home/ubuntu/newproject/static")
files = []
for file in os.listdir("."):
files.append(file)
context = {'files':files}
return render(request, 'sslcert/index.html', context)
and then the template:
<head>
{% block title %}
<h3>
Following directories are in this folder:
</h3>
{% endblock %}
</head>
<body>
{{ files }}
</body>
render function You are using in Your example got dictionary argument which can extend context passed into template
render(request, template_name[, dictionary][, context_instance][, content_type][, status][, current_app][, dirs])
dictionary
A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
so you can pass any data into template as dictionary which keys will be available in template as variable
from django.shortcuts import render
def index(request):
dir = "/home/ubuntu/newproject/static"
return render('sslcert/index.html', {'files': os.listdir(dir)})