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>
Related
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'])
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})
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).
views.py file:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('upload/testpage.html')
return HttpResponse(template.render)
app/templates/app/testpage.html file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
Upload
</body>
</html>
app/urls.py file:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),]
project/urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', include('upload.urls')),]
Getting an error when running file on local server 127.0.0.1:8000/app of "TemplateDoesNotExist at /app/"
How can this be resolved?
With your current file path app/templates/app/testpage.html this one should works
def index(request):
template = loader.get_template('app/testpage.html')
return HttpResponse(template.render)
Another way to do it is to change your template path to app/templates/upload/testpage.html
I think you did not create any upload folder inside templtes folder.
If you have app folder like that
app/templates/app/testpage.html
Now, you can fix it
template = loader.get_template('app/testpage.html')
Try this,
from django.shortcuts import render
def index(request):
return render(request, 'app/testpage.html')
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.