Unable to send variable from views to html python - python

Am Unable to sent the temp_k variable from my views to index.html. I have made a request from weather API and trying to pass it to my html.
Please suggest how we are supposed to send the variable from views to template.
views.py
from django.template.loader import render_to_string
import requests
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
my_dict = {'insert_me': "From andu.py"}
return render(request, 'mywebapp/index.html', context=my_dict)
def temperature(request):
#zip=requests.form['zip']ss
r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22')
json_object=r.json()
my_dict1={'temp_k' :json_object['main']['temp']}
return render(request,'mywebapp/index.html', context=my_dict1)
index.html
<!DOCTYPE html>
{% load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hey</title>
<link rel="stylesheet" href={% static "cs/style.css" %}/>
</head>
<body>
<h1>This is the Header</h1>
<img src="{% static "images/youownme.jpeg" %}" atl="Uh Oh">
<h2> Temperature:{{temp_k}}</h2>
</body>
</html>

I have tried your code and it works fine so you may want to check if you are rendering the right HTML files maybe, i've changed your code to make sure it's working and it is
my_dict1={'temp_k' :json_object['wind']['speed']}
sorry but I cant write a comment yet!

Use render like this :
return render(request,'mywebapp/index.html',{'context':my_dict})

Related

I am getting AttributeError in RequestContext in DJango

I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue
I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0
Traceback:
Exception Type: AttributeError
Exception Value:
'RequestContext' object has no attribute 'META'
views.py
from django.shortcuts import render
from django.template import RequestContext
def survey(request):
return render(RequestContext(request),'wfhApp/survey.html')
And my html page is as follow:
<!DOCTYPE html>
{% load django_typeform %}
{% load sekizai_tags %}
<html>
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Hi there!</h1>
<div class="target-dom-node" style="width: 100%; height: 500px;"></div>
<script src="https://embed.typeform.com/embed.js"></script>
<script src="/survey/script.js"></script>
{% typeforms_embed 'https://theother2thirds.typeform.com/to/hNZW30' 'New typeform' '{"hideHeaders": true, "hideFooter": true}' %}
</body>
</html>
urls.py
from django.conf.urls import url
from wfhApp import views
app_name = 'wfhApp'
urlpatterns = [
url(r'^survey/$',views.survey, name='survey'),
]
The issue is that you're wrapping the request inside of a RequestContext object, which is incorrect for the render() function.
The render() function will build the RequestContext object for you, so it expects the request and any extra context variables as arguments.
Instead, just pass the request directly to the render() function:
def survey(request):
return render(request, 'wfhApp/survey.html')

POST method is not working when submitting form in django

I created feedback form using form module in django. i wrote the code for printing form data entered by user when submitting form. But when i submit the form post is not working as a result user data is not printing . I am beginner in django .I tried lots to solve this .but i couldn't. please help me if anyone know what is my wrong in code
forms.py
from django import forms
class feedbackForm(forms.Form):
Name=forms.CharField()
RollNo=forms.IntegerField()
Email=forms.EmailField()
feedback=forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render
from .import forms
def feedback_view(request):
form=forms.feedbackForm()
if request.method=='POST':
form=forms.feedbackForm(request.POST)
if form.is_valid():
print('form validation success and printing feeback info')
print('student name :',form.cleaned_data['Name'])
print('student RollNo:',form.cleaned_data['RollNo'])
print('student Email :',form.cleaned_data['Email'])
print('student feedback :',form.cleaned_data['feedback'])
return render(request,'testapp/feedback.html',{'form':form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^feed/', views.feedback_view),
]
feedback.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="{%static "css/demo1001.css"%}">
<title></title>
</head>
<body>
<div class="container" align=center>
<h1>ShefJaz Student 2feedbackform </h1><br>
<form method="post">
{{form.as_p}}
{%csrf_token%}
<button type="button" class="btn btn-primary">sumbit feedback</button>
</form>
</div>
</body>
</html>
You are using a function as a API view so, It should be mentioned in the method decorator like shown below
from rest_framework.decorators import api_view
#api_view(['POST'])
def feedback_view(request):
.....
your code
.....
Hope it will give you the solution.
more than one HTTP methods can be used like shown here.
#api_view(['POST', 'GET'])

Error when trying to render Folium map on Django Server

view.py
map = folium.Map(location=[df['latitude'].mean(),
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)
map.save("map.html")
context = {'my_map': map}
return render(request, 'my_map.html', context)
my_map.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ my_map }}
</body>
browser result:
folium.folium.Map object at 0x7f49d85662b0
im not sure how to approach getting the html/js to work on the browser after the user has submitted their input via the previous html form...
I have seemed to look everywhere and there are a lot of similar problems with solutions but I could not get any to work!
Thanks!
This response is here to increase the google coverage for others who, like me, also experienced this problem when trying to render a Folium map within a Django template.
Your Code
Please see the comments inside each code block for how to render the map as expected.
views.py
map = folium.Map(location=[df['latitude'].mean(),
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)
map.save("map.html")
# {'my_map': map} will output the object, which is what you are seeing
# to rectify this we need to turn it into an iframe which
# the template can then render.
context = {'my_map': map} # change to {'my_map': map._repr_html_()}
return render(request, 'my_map.html', context)
Template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
# after making the change in our views.py this will return the html but
# the template will not render it as expected because it is being escaped.
# You must declare it 'safe' before it will be rendered correctly.
{{ my_map }} # change to {{ my_map | safe }}
</body>
For more information see the Folium doc page here or this SO post.
Hope that helps.
Map objects have a render method which render its html representation.
You can try directly:
<body>
{{ my_map.render }}
</body>
Or you can use the Map.render method to implement a custom inclusion tag, that way you can pass arguments to the render method. See this for reading more about inclusion and custom tags.
# The template tag.
for django.template import Library
register = Library()
#register.inclusion_tag
def render_map(map_object, **kwargs):
return map_object.render(**kwargs)
In your template:
<body>
{% render_map my_map some_arg1=arg1 some_arg2=arg2 %}
</body>

Insert python string into Django template context with markup

If I render a static image in the .html template it works. But if I provide the static markup string as dictionary value to the template (the context), it will not work. It seems to be something to do with string formatting and not allowing me to use {% %} the way I need to. I have tried:
1. .format()
2. escaping the percent characters
3. raw strings
4. concatenation
5. autoescape
6. | safe
and a number of other things
Basically, I am constructing a multi-line string in view.py with '''{% %}''', and then rendering a template with this string as the context. Python 2.
UPDATE
Simple non-working example:
view.py
def index(request):
image_insert = ''
images = ['image1.jpg', 'image2.jpg', 'image3.jpg']
for image in images:
image_insert += '<img src="{}">'.format(image)
context = {'insert': image_insert}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src={% static "image.jpg" %}>
Second Image <!-- does not work -->
{{ image_insert | safe }}
</body>
</html>
Page Source:
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src=/static/mqdefault.jpg>
Second Image
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
</body>
</html>
Obviously, there is a difference. This is Django 1.11 btw if it makes a difference.
You can also achieve this by passing img source from the view as follow:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
context = {'image_src': static("image.jpg")}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src="{{ image_src }}">
</body>
</html>
UPDATE: Multiple Images
You can generate markup with multiple images and pass it in the context as seen in the views.py:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
images = [static('image1.jpg'), static('image2.jpg'), static('image3.jpg')]
images_html = "".join([
"<img src={image}>".format(image=image)
for image in images
])
context = {'images_html': images_html)}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Now, your updated index.html will be:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
{{ images_html|safe }}
</body>
</html>
Hope it helps.
working code:
def index(request):
context = {'image_insert': "image.jpg"}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src="{% static "image.jpg" %}">
Second Image <!-- does not work -->
<img src="{% static image_insert %}">
</body>
</html>

Why did I get a blank page after using Django_ajax with django?

I'm a beginner in django, I follow the steps showed at GitHub, but I just got a blank page, here my code:
views.py
from django.shortcuts import render
from django_ajax.decorators import ajax
#ajax
def AjaxView(request):
return render(request, 'blogs/ajaxtest.html'`
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^ajax/', 'blogs.views.AjaxView', name='Ajax'))
ajaxtest.html
<head>
<script type="text/javascript" src="{% static '/blogs/django_ajax/js/jquery.ajax.min.js' %}"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<title>Ajax Test</title>
</head>
<body>
<script type="text/javascript">
ajaxGet('/', function(content){
//onSuccess
alert(content);
})
</script>
</body>
You need to include jQuery before django_ajax or django_ajax won't work, it is a requirement.
Also your AjaxView function seems to be incomplete.

Categories

Resources