Django - not showing my var in template - python

I'm starting in Django.
I'm trying to pass to my template my var to be shown in my browser but not working.
here's my views.py
from django.shortcuts import render
from django.http import HttpResponse
from preguntasyrespuestas.models import Pregunta
from django.shortcuts import render_to_response
# Create your views here.
def index(request):
string = 'hi world'
return render_to_response('test/index.html',
{'string': string})
here's my urls:
from django.conf.urls import *
from django.contrib import admin
from django.contrib.auth.views import login
from preguntasyrespuestas.views import index
urlpatterns = [
url(r'^$', index, name='index'),
]
my html:
<!DOCTYPE html>
<html>
<head>
<title> Preguntas </title>
</head>
<body>
<p>{{ string }}</p>
</body>
</html>
Basicaly I want to show what's in string in my template. but not working..
My error:
Using the URLconf defined in django_examples.urls, Django tried these URL patterns, in this order:
^$ [name='index']
The current URL, test/index.html, didn't match any of these.
What am I doing wrong? Thanks..

You should not add test/index.html at the end of your url in the browser, just something like http://127.0.0.1:8000/ and make sure that templates/test/index.html exists.

Django's url routing uses regular expressions to match routes.
url(r'^$', index, name='index'),
In this case you have just a single valid route, which is the empty string r'^$'. So you can only get a response by visiting for example http://localhost:8000. All other urls will fail.
Django's url routing is completely independent from where your template files are located on your file system. Therefore http://localhost/test/index.html will not be valid, even though there is a template file with that name.
You could make a catch-all route by using this pattern that will match any url path.
url(r'', index, name='index'),

Related

Django not serving text content (Second attempt)

Summary:
I’m writing a Django web app whose purpose is to showcase a writing sample (a ‘post mortem’) which is basically like a blog post for all intents and purposes. Django is not serving the content and I am not sure why. The problem I figure is with either my views.py or template (copied below). I don’t think the issue is with my models or urls.py but I included them anyways.
Details:
This is my second attempt at getting my Django project to serve this template properly. In my prior first attempt, I encountered a similar issue:
Django not serving text content (First attempt)
There in that question, another SO member answered by identifying three mistakes I was making. The problem there was that I was missing a for loop inside my template, I was missing an all() class method inside my views.py and the context dictionary key value pair in views.py was not pluralized.
Those issues have been resolved however my new issue involves Django serving a blank template when I am expecting the Lorem Ipsum content to show.
Django should be pulling all the class objects from my models.py and then be sending them to the alls/landings.html. I am expecting the title, publication date, image and body content to render on my landing page. But instead, my ‘mortems’ app content (a blog post) isn’t showing on the landing page. The only thing that shows is the heading. To illustrate so you can see what I see, here is what my landing page looks like now:
Based on what you people see below, who can tell me what is wrong with my views / landings.html template?
The full source code can be found on my GitHub page. Here is a snapshot of the state of my project (tagged as v0.6.0).
What follows are the code samples where I suspect my issue exists.
Here is my latest views.py:
from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem
def mortems(request):
mortems = Mortem.objects.all().order_by('-pub_date')
context = {'mortems':mortems}
return render(request, 'alls/landings.html', context)
Here is my templates/alls/landings.html:
{% load static %}
<html>
<head>
<title> BLOG </title>
<style> </style>
<!-- <link rel="stylesheet" href="{% static 'redactors/style.css' %}"> -->
</head>
<body>
{% block content %}
<h1> BLOG POST:</h1>
{% for mortem in mortems %}
<h1>{{ mortem.title }}</h1>
<h4>Date: {{ mortem.pub_date_preference }}</h4>
<br />
Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />
<br />
<!-- Body text should go here : -->
Body Text:
<p>{{ mortem.body|safe }}</p>
<br />
<br />
{% endfor %}
{% endblock %}
</body>
</html>
Here my project’s main urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('redactors.urls')),
path('', include('counters.urls')),
path('', include('mortems.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my app’s (mortems) urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.mortems, name='mortems'),
]
Here is my app’s models.py:
from django.db import models
import datetime
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
# Create your models here.
class Mortem(models.Model):
title = models.CharField(max_length=161)
pub_date = models.DateTimeField()
image = models.ImageField(upload_to='media/')
body = models.TextField()
now = datetime.datetime.now()
def __str__(self):
return self.title
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b = self.pub_date.strftime("%A %d %B %Y # %-I:%M:%S %p")
# c = pytz.timezone("US")
return (b)
def summary(self):
return self.body[:1024]
You are using the same path for views.home in redactors.urls and views.mortems in mortems.urls i.e '/'
CC_Redact_Iter3/urls.py you configured in this order
urlpatterns = [
#Django serves urls in the order you gave
path('admin/', admin.site.urls), #1st
path('', include('redactors.urls')), #2nd
path('', include('counters.urls')), #3rd
path('', include('mortems.urls')), #4th
]
redactors/urls.py
urlpatterns = [
path('', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
mortems/urls.py
urlpatterns = [
path('', views.mortems, name='mortems'), #As you can see views.home is also having same path so change the path for home
]
In your case
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx xxxx {}'.format(number[-4:])
return render(request, 'alls/results.html', {'number':number, 'redacted_num':redacted_num})
else:
return render(request, 'alls/landings.html') #this is being rendered instead mortem
Change your CC_Redact_Iter3/urls.py and redactors/urls.py as shown below
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mortems.urls')),
path('', include('redactors.urls')),
path('', include('counters.urls')),
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = [
path('home/', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
And the date format in you mortems/models.py is Invalid (%-I)
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b= self.pub_date.strftime("%A %d %B %Y # %I:%M:%S %p") #try something like this
# c = pytz.timezone("US")
return (b)
Courtesy of #MeL in the comments, the solution is to include ‘mortems’ as the first argument inside my path() function inside the mortems app’s urls.py. This file looks like this now:
urlpatterns = [
path('mortems', views.mortems, name='mortems'),
]
Now when I navigate to http://127.0.0.1:8000/mortems, the landings.html template renders exactly as intended, with all the content present. To see, here is my mortems page now:
So that is the solution I guess. But I remain flummoxed and curious: why? With the path parameter empty ’’, I’d expect Django to serve the landings.html template on the home page / landing page at this location: http://127.0.0.1:8000/. Django serves the template but all the content is missing. Only after adding a string as an argument the content shows. Why is that?
If someone could kindly answer why, I’d be happy to update this answer here with more information.

django template just reloads when clicking a link pointing to another template

the template home in my django contains a url pointing to another page but when clicking this link , the home template just reloads here is the code for the urls.py, views.py and home.html
this is urls.py
from django.conf.urls import include, url
from django.contrib import admin
from pizza import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'',views.home,name='home'),
url(r'order/',views.order,name='order'),
]
this is views.py
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request,'pizza/home.html')
def order(request):
return render(request,'pizza/order.html')
this is home.html
<h3>
Nandias Garder
</h3>
order a pizza
your urls formatting is wrong. you should try this:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',views.home,name='home'),
url(r'^order/',views.order,name='order'),
]
if you notice here I used ^$ to make sure the home url only catches the empty url.
in your urls, the second url (home url) will match with every string. you can go to admin, because it's defined before home url.

Putting Python code in HTML files using 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).

how to send a parameter from html to django view.py

I am a beginner and did a lot of search but every time I got only "django to html" as search result every time. I am following this tutorial:
http://www.djangobook.com/en/2.0/chapter07.html
but on the way I am not able to pass paramter from html to view.py.
Here is my directory:
directory: mysite:
directory: books
directory: templates
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
def search_form(request):
return render(request, 'books/search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
urls.py for books
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.search_form,name='search_form'),
url(r'^$', views.search,name='search'),
]
and urls.py in mysite directory
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', include('books.urls')),
]
Now the problem is when I type: http://127.0.0.1:8000/books/
it successfully shows the form's textbox and submit button but when I press submit it shows me this:
Firstly, you need two different regexes for the search_form and search results. For example:
url(r'^$',views.search_form,name='search_form'),
url(r'^search/$', views.search,name='search'),
Next, you need to update the form's action to point to the search view. Since you have included your books/urls.py with the /books/ prefix, you need:
<form action="/books/search/" method="get">
It is better to use the url tag instead of hardcoding your urls. In this case, you would do:
<form action="{% url 'search' %}" method="get">
In addition to the answer of Alasdair I would use "books:search" for clear namespace:
<form action="{% url 'books:search' %}" method="get">
The url /search/ doesn't exist, you didnt define that it should exist.
It would be /books/ judging from that URLs file you showed. Also on a side note, don't use http://www.djangobook.com/en/2.0/index.html
They have a warning on the main page that it is no longer up to date.
Use masteringdjango.com and other up to date resources.

Django NoReverseMatch error, reverse function not work with no arguments

this NoReverseMatch error is driving me nuts. I'm using Django 1.6 and I have checked through my urls and it just doesn't work. Please kindly guide me on this.
I basically want to do something deadly simple, just when I submit a html form, I get the data I want and then redirect to a result page, but it just doesn't work...
Here is my index.html file
<form name="input" action="{% url 'whatspring:sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="usrname">
<br>
<input type="submit">
</form>
<br>
my view.py
def index(request):
return render(request,'springsend/index.html')
def sending(request):
var = request.POST['usrname']
doSomethinghere()
return HttpResponseRedirect(reverse('whatspring:results'))
def results(request):
return render(request,'springsend/send_results.html')
then my app urls.py
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
)
and the main urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^send/', include('springsend.urls', namespace="whatspring")),
)
I have tried to look into the problem and it seems that the reverse function cannot get the name for the reverse url that I want (i.e. 'results' under the namespace 'whatspring'....)Am I missing something something trival? Please kindly help.
Your urls.py (springsend one) doesn't seem to have a url for the sending view, that's probably why {% url 'whatspring:sending' %} can't find it.
Simply change it to
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
url(r'^sending/$', views.sending, name='sending'), # this line
)
Every accessible view needs a url. The user's browser needs to have some address to send things. If it would just send it to your domain without url, Django would have no way to tell which url is requested. Django does not auto-generate these urls (which is probably good).
(The user himself does not need to know this url; you don't need to place any ` links anywhere.)

Categories

Resources