Passing data between veiws.py and template.html in django - python

I am new in Django. I want to write a very simple code to create a string in views.py and shows in an html file in templates.:
views.py
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
F = 100
response = str(F + 10)
response1 = {"Main": response}
template_name = "homepage.html"
return render(request, template_name, response1)
urls.py
urlpatterns = [
path('', views.index, name='homepage.html'),
path('admin/', admin.site.urls)]
homepage.html
<html>
<head>
<h1>User Information</h1>
</head>
<h2>Answer: {{response1}}</h2>
</html>
What I get on webpage is the headers without {{response1}}

<html>
<head>
<h1>User Information</h1>
</head>
<h2>Answer: {{Main}}</h2>
</html>
Use this

Related

Django - Recursion Error with static main.css

Running into a max recursion error when hitting my static main.css file in django. Need help identifying the issue and how to correct it.
Had no issues when my login/sign up pages were within my single dbManagementApp. After adding those to a new app (accounts) then adding the templates into a specific folder for each app, I received the below error message.
Debugger
In template ###, error at line 7
maximum recursion depth exceeded while calling a Python object
1 <!DOCTYPE html>
2 <html lang="en" dir="ltr">
3 <head>
4 <meta charset="utf-8">
5 <title>HOME</title>
6 {% load static %} <!-- load the static folder for css-->
7 <link rel="stylesheet" href="{% static 'main.css' %}">
Traceback
File "C:\Users\lukep\anaconda3\envs\djangoenv\lib\site-packages\django\template\base.py", line 766, in __init__
self.literal = float(var)
ValueError: could not convert string to float: "'main.css'"
My main urls.py:
from django.contrib import admin
from django.urls import path, include
from dbManagementApp import dbmviews
from accounts import accviews
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('dbManagementApp.dbmurls')),
path('accounts/', include('accounts.accurls'))
]
dbManagementApp/dbmurls.py
from django.urls import path
from . import dbmviews
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', dbmviews.home, name='home'),
path('aboutus/', dbmviews.aboutUs, name='aboutUs'),
path('pricing/', dbmviews.pricing, name='pricing'),
path('contact/', dbmviews.contact, name='contact'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
dbManagementApp/dbmviews.py
from django.shortcuts import render, redirect
from django.views import View
from .models import Doc
from .forms import DocumentForm
from django.contrib import messages
from django.http import HttpResponse
from django.http import JsonResponse
# Create your views here.
def home(request):
return render(request, 'dbmapp/index.html')
templates/dbmapp/index.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>HOME</title>
{% load static %} <!-- load the static folder for css-->
<link rel="stylesheet" href="{% static 'main.css' %}">
accounts/accurls.py
from django.urls import path
from . import accviews
urlpatterns = [
path('register/', accviews.register, name='register'),
path('login/', accviews.login, name='login')
]
accounts/accviews.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form':form})
def login(request):
return render(request, 'registration/login.html')
I'm not fully understand your problem, but I'd change 3 things
{% load static %} should be at the top of the html file
Move path('', include('dbManagementApp.dbmurls')), first (before admin)
Remove dir attribute in html.
Just a question, are you using {% extends 'whatever.html' %}?, it cause error from duplicating tags.

I can access fatimatestpro.pythonanywhere.com but not fatimatestpro.pythonanywhere.com/help/

I am working on PythonAnywhere and made my first project. I am trying to access many views (HTML pages) from my views.py. Here is my project tree:
emailpro
--emailpro
----url.py
--emailapp
----urls.py
----views.py
--templates
----emailapp
------index.html
------help.html
Code inside my emailpro>emailpro>urls.py is
from django.conf.urls import url, include
from django.contrib import admin
#from emailapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
#url(r'^$', views.index, name='index'),
url('', include('emailapp.urls')),
]
Code inside my emailpro>emailapp>urls.py is:
from django.conf.urls import url
from emailapp import views
urlpatterns=[
url('', views.index, name='index'),
url(r'^help/$', views.help, name='help'),
]
Code inside my emailpro>emailapp>views.py is
from django.shortcuts import render
#from django.http import HttpResponse
# Create your views here.
def index(request):
my_dict={'insert_me': "Hi I am index coming from views.py"}
return render(request, 'emailapp/index.html', context=my_dict)
def help(request):
help_dict={'help_insert': "HELP PAGE"}
return render(request, 'emailapp/help.html', context=help_dict)
My emailpro>templates>emailapp>index.html is
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<h1>Index page</h1>
{{ insert_me }}
</body>
</html>
Code inside my emailpro>templates>emailapp>help.html is
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title> Help </title>
</head>
<body>
<h1>This is my Help HTML</h1>
{{ help_insert }}
</body>
</html>
Now when I run my site and access http://fatimatestpro.pythonanywhere.com/, it shows me my index.html page which means it is going inside my emailpro>emailapp>urls.py to get its view from views.py but when I try to access http://fatimatestpro.pythonanywhere.com/help/, it shows the same page as index.html.
Please help me to send it to different view.
Thanks in advance
your index url is matching before it reaches the help url.
try:
urlpatterns=[
url(r'^help/$', views.help, name='help'),
url('/', views.index, name='index'),
]

form action not working to redirect in django v2

The form action is not redirecting from home.html to password.html in Django 2 even I recheck everything including URL pattern
Below I am sharing the basic code. My apologies if it's a basic question as I am very new to Django that's why I may not able to detect the issue.
urls.py code
from django.urls import path
from generator import views
urlpatterns = [
path('', views.home),
path('password/', views.password),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request, 'generator/home.html')
def password(request):
return render(request, 'generator/password.html')
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Password Generator</h1>
<form action="password" method="get">
<select name="length">
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<input type="button" value="Generate Password">
</form>
</body>
</html>
password.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password</title>
</head>
<body>
<h1>Password page</h1>
</body>
</html>
Error Log
File Structure
First of all give names in urls.py so you can access it by name.
urlpatterns = [
path('', views.home,name="index"),
path('password/', views.password,name="password"),
]
in home.html remove form's action
in views.py
from django.urls import reverse
def home(request):
if request.method == 'POST':
#you can access input items of form by `request.POST.get('attribute_name')`
# your logic
return redirect(reverse('password')
else:
return render(request, 'generator/home.html')
if still not getting error then please share whole code and what you want to achieve

Unable to get Django HttpResponse

A little description of what i m trying to do.
I want to make a User Interface (web/HTML) through which i can send the commands to router and display the result on the Webpage/HTML.
Here's the code i m using:-
Views.py
from django.shortcuts import render
from first_app.forms import CmdForm
from django.http import HttpResponse
def index(request):
my_dict = {'insert_me': ""}
return render(request,'first_app/index.html',context=my_dict)
def form_name_view(request):
if request.method == "POST":
form = CmdForm(request.POST)
if form.is_valid():
from netmiko import ConnectHandler
devices = {
'device_type':'cisco_ios',
'ip':'192.168.50.145',
'username':'me',
'password':'12345',
'secret':'12345',
'port':'22'
}
cmd = request.POST.get('command', '')
netconnect = ConnectHandler(**devices)
#print("connection established with", devices['ip'])
output = netconnect.send_command(cmd)
return render(request,'first_app/forms.html', {'form': form,
'output':output})
else:
form = CmdForm()
return render(request,'first_app/forms.html', {'form': form})
forms.py
from django import forms
class CmdForm(forms.Form):
command = forms.CharField(label='Command to execute')
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from first_app import views
urlpatterns = [
path('Automation_page/', views.form_name_view,name='IP form'),
path('admin/', admin.site.urls),
path('', views.index,name='first'),
path('first_app/',include('first_app.urls')),
]
forms.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>FORMS</title>
</head>
<body>
<h1> IP address form </h1>
<p>Run command:</p>
<form method="POST"> {% csrf_token %}
{{ form }}
<input type="submit" value="Run command!" />
</form><br>
{% if request.POST %}
<p>Command output:</p>
<pre>{{ output }}</pre>
{% endif %}
</body>
</html>
i am getting the error when i visit the Automation_page/
ValueError at /Automation_page/
The view first_app.views.form_name_view didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/Automation_page/
Django Version: 2.2.3
Exception Type: ValueError
Exception Value:
The view first_app.views.form_name_view didn't return an HttpResponse object. It returned None instead.
Exception Location: K:\Work\DevNet\ENV1\lib\site-packages\django\core\handlers\base.py in _get_response, line 126
Python Executable: K:\Work\DevNet\ENV1\Scripts\python.exe
Python Version: 3.7.3
Python Path:
['K:\Work\DevNet\first_project',
'K:\Work\DevNet\ENV1\Scripts\python37.zip',
'K:\Work\DevNet\ENV1\DLLs',
'K:\Work\DevNet\ENV1\lib',
'K:\Work\DevNet\ENV1\Scripts',
'c:\users\karti\appdata\local\programs\python\python37-32\Lib',
'c:\users\karti\appdata\local\programs\python\python37-32\DLLs',
'K:\Work\DevNet\ENV1',
'K:\Work\DevNet\ENV1\lib\site-packages']
Need help on this.
thanku who are willing to help
The last line needs to be moved one indent to the left, so it is hit if the form is invalid.
else:
form = CmdForm()
return render(request,'first_app/forms.html', {'form': form})
I was able to figure out the solution of my problem.
sharing it for others if they can relate. :-)
In views.py
Add the following code, with indent to first if statement.
else:
return render(request,'first_app/forms.html', {})

Django - No redirect on form submission

I'm at the end of my rope trying to figure out why a simple form redirect is not working. I'm submitting a form with one text field via POST request that gets combined with some data from a function in the same views.py file, which is then saved to the model on the database. For some reason, with the redirect schemes that I've set up on submission of the form, I get either a second copy of the form.
feedbackapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import FeedbackForm
from .models import Feedback
def record_feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
feedback = Feedback()
feedback.submitter_ip = get_client_ip(request)
feedback.feedback_text = form.cleaned_data['feedback']
feedback.save()
return HttpResponseRedirect(reverse('feedbackapp:thanks'))
elif request.method == 'GET':
form = FeedbackForm()
return render(request, 'feedbackapp/feedback_form.html', {'form': form})
def thanks(request):
return render(template_name='feedbackapp/thanks.html',request=request)
# https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1] # needs to be the last element in array for Heroku
else:
ip = request.META.get('REMOTE_ADDR')
return ip
feedbackapp/forms.py
from django import forms
class FeedbackForm(forms.Form):
feedback = forms.CharField(label='Feedback', max_length=5000)
feedbackapp/templates/feedbackapp/feedback_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Anonymous Feedback</title>
</head>
<body>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
<p><i>Note: IP addresses are collected with each submission.</i></p>
</body>
</html>
feedbackapp/templates/feedbackapp/thanks.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thanks!</title>
</head>
<body>
<p>Thanks for your feedback.</p>
</body>
</html>
feedbackapp/urls.py
from django.conf.urls import url
from .views import record_feedback, thanks
urlpatterns = [
url('', record_feedback, name='feedback'),
url('thanks/', thanks, name='thanks'),
]
anonfeed/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('feedbackapp.urls'), namespace='feedbackapp'),
]
It is almost as if the thanks view is not associating with the url and the template.
Your empty regex overrides the one for thanks. Change the following line:
url('', record_feedback, name='feedback'),
to
url('^$', record_feedback, name='feedback'),

Categories