I want to print a list called formulario and I want to paste them into a html file using Django template language, although I'm not able to display that information in <li> tag. Is there sth am I missing?
views.py
from django.template import RequestContext
from django.http import HttpResponse
from django.shortcuts import render
import pandas as pd
formulario = ["Hola", "Hi"]
def formulario(request):
return render (request, "formulario/formulario.html",{
"formulario":formulario
})
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Formulario !</h1>
<ul>
{% for formulario in formulario %}
<li>{formulario}</li>
{% endfor %}
</ul>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("index.html",views.index, name="index"),
path("financierofinanciamiento.html",views.financiamiento, name="financiamiento"),
path("financierobeneficio.html",views.beneficio, name="beneficio"),
path("tecnicoinfra.html",views.infra, name="infra"),
path("tecnicoequipo.html",views.equipo, name="equipo"),
path("tecnicoherramientas.html",views.herramientas, name="herramientas"),
path("tecnicomateriaprima.html",views.materiaprima, name="materiaprima"),
path("formulario.html",views.formulario, name="formulario"),
]
{% for item in formulario %}
<li>{{ item }}</li>
{% endfor %}
Related
In my folder Templates I created 2 html files:
main.html
user.html
The structure of the main.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DJANGO</title>
</head>
<body>
{% block userinfo %}
{% endblock userinfo %}
</body>
</html>
The structure of the user.html is:
{% extends "main.html" %}
{% block userinfo %}
<h2>John Doe</h2>
<p>Explorer of life.</p>
{% endblock userinfo %}
I don't understand why
<h2>John Doe</h2>
<p>Explorer of life.</p>
doesn't appear in the browser when I call main.html
I have tried writing in this way too
{% extends "main.html" %}
{% block userinfo %}
<h2>John Doe</h2>
<p>Explorer of life.</p>
{% endblock %}
without user in the endblock but it does not work.
In settings.py file in Templates list and DIR list I added:
os.path.join(BASE_DIR,'templates'),
and I importend os too.
In views.py file that I've created I have written
from django.shortcuts import render
from django.http import HttpResponse
def main(request):
return render(request,'main.html')
In urls.py file that I've created I have written
from django.urls import path
from . import views
urlpatterns = [
path('main/',views.main,name='')
]
When I call the page with http://localhost:8000/main/
I don't have any error. The only problem is that the page is blank.
And If I try to add some text in main.html it appers on the screen, but the content from user.html doesn't appear.
Can someone help me?
When you render main.html directly, your user.html gets ignored.
If you render user.html from django, you will get expected result.
To inject user.html contents to main.html you should use something like {% include "user.html" %} insead of blocks statement.
Extension in templates follows the same logic that class inheritance, it goes the way down not up.
Once said, main is the base template and you will never see the content of templates in which you are extending, its the opposite, you will see the content of the base template (the one you are extending for) in the child template (the one that has the extends).
I guess the behavior that you are expecting to have is the one that gives the include tag
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DJANGO</title>
</head>
<body>
{% include "user.html" %}
</body>
</html>
user.html
<h2>John Doe</h2>
<p>Explorer of life.</p>
I created a login page, but it seems that the link is not valid, I have tried many ways but it doesn't work
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%25url%20'login'%7D
Using the URLconf defined in mysite.urls
Here is my code
urls.py
from django.contrib import admin
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', views.index),
path('contact/', views.contact, name='contact' ),
path('register/', views.register, name= 'register'),
path( 'login/',auth_views.LoginView.as_view(template_name="pages/login.html"), name="login"),
path('logout/',auth_views.LogoutView.as_view(next_page='/'),name='logout'),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset ="UFT=8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> Documment</title>
</head>
<body>
<form method = "POST" >
{%csrf_token%}
{%for key, value in form.errors.items %}
{{value }}
{% endfor %}
<p> <label>Tài Khoản : </label>{{form.username}}</p>
<p> <label>Mật Khẩu : </label>{{form.password}}</p>
<input type="hidden" name='next' value="/"/>
<input type="submit" value="Đăng nhập"/>
</form>
</body>
</html>
i keep getting an error (404) page when i run my server for a django when i click the link to a post detail. I think nothing is wrong with my code so i need help to locate why i'm getting the error.
this is my views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post
from django.utils import timezone
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date')
return render(request, 'blog2app/home_post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog2app/postdetail.html', {{'post': post}})
this is my blog2app\urls.py
from django.urls import path
from . import views
urlpatterns = [
path(r'^$', views.post_list, name="homepage"),
path(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
this is my blog2/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path(r'^admin/$', admin.site.urls),
path(r'^$', include('blog2app.urls')),
]
this is my home_post_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for post in posts %}
<p><h4>Published: {{ post.published_date }}</h4></p>
<h1><strong> {{ post.title }} </strong></h1><br>
{% endfor %}
</body>
</html>
this is my detailpost.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if post.published_date %}
{{ post.published_date }}
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.body|linebreaksbr }}
</body>
</html>
this is the error page on chrome.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in blog2.urls, Django tried these URL patterns, in this order:
^admin/$
^$
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page
the development server is showing no error.
blog2app is my app name.
blog2 is my projectname.
i am using pycharm idle for development.
i will be very happy if anyone can suggest any tutorial video particularly for creating blogs with django.
i changed my detailpost.html to
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ posts.published_date }}
<h1>{{ posts.title }}</h1>
<p>{{ posts.body|linebreaksbr }}
</body>
</html>
i changed my views.py to
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post
from django.utils import timezone
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date')
return render(request, 'blog2app/home_post_list.html', {'posts': posts})
def post_detail(request, pk=None ):
post = Post.objects.get(pk=pk)
context = {'posts': post}
return render(request, 'blog2app/postdetail.html', context)
i changed my home_post_list.html to
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for post in posts %}
<p><h4>Published: {{ post.published_date }}</h4></p>
<h1><strong> {{ post.title }} </strong></h1><br>
{% endfor %}
</body>
</html>
and i stopped seeing the error.
My conclusion is i was using the post in
post = Post.objects.get(pk=pk)
to call my primary key instead of using posts in
context = {'posts': post}
Max Goodridge django tutorial really helped me.
I'm trying to make to make a django web app which has a form that asks a user to input a phone number and stores that number in a postgres database. The following code is giving me the error:
NoReverseMatch at /main/insert_num/
Reverse for '' not found. '' is not a valid view function or pattern name.
And I can't figure out what the issue is, can someone help?
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="{% url 'insert_my_num' %}" method="post" autocomplete="off">
{% csrf_token %}
<!-- {{ form.as_p }} -->
<input type="submit" value="Send message">
</form>
</body>
</html>
forms.py
from django import forms
from phone_field import PhoneField
from main.models import Post
class HomeForm(forms.ModelForm):
phone = PhoneField()
class Meta:
model = Post
fields = ('phone',)
models.py
from django.db import models
from phone_field import PhoneField
class Post(models.Model):
phone = PhoneField()
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('insert_num/', views.insert_my_num,name='insert_my_num')
]
project/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('main/',include('main.urls'))
]
views.py
def insert_my_num(request: HttpRequest):
phone = Post(request.POST.get('phone'))
phone.save()
return redirect('')
Your views.py is a little off - you aren't rendering your form anywhere. I drafted up a quick app (which I think does what you're looking for) - let me know if this works:
main/templates/index.html
Here, I just set the form's action to "" (that's all you need here) and uncommented the form.as_p line
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>
</body>
</html>
main/views.py
Note the differences here, we are testing the request type and taking appropriate action based on what kind of request is coming in. If it's a POST request we process the form data and save to the database. If not, we need to display a blank form for the user to complete.
from django.shortcuts import render, redirect
from .forms import HomeForm
def insert_my_num(request):
# Check if this is a POST request
if request.method == 'POST':
# Create an instance of HomeForm and populate with the request data
form = HomeForm(request.POST)
# Check if it is valid
if form.is_valid():
# Process the form data - here we're just saving to the database
form.save()
# Redirect back to the same view (normally you'd redirect to a success page or something)
return redirect('insert_my_num')
# If this isn't a POST request, create a blank form
else:
form = HomeForm()
# Render the form
return render(request, 'index.html', {'form': form})
Let me know if that works!
I am trying to access a request.method in a python view, but I'm getting the error
'str' object has no attribute 'method'
The really odd thing is that I can see no difference between how I set up this page and how I set up another similar page; yet that one works fine and this one does not.
The code I am using is as follows:
main/views.py:
from .alphabetize import alphabetize
from .forms import WordListForm
def alphabetize(request):
if request.method == "POST":
form = WordListForm(request.POST)
if form.is_valid():
word_list = alphabetize(form.cleaned_data['word_list'])
return render(request, 'main/alphabetize.html', {'form': form, 'word_list': word_list})
else:
form = WordListForm()
return render(request, 'main/alphabetize.html', {'form': form})
/main/forms.py
class WordListForm(forms.Form):
word_list = forms.CharField(label="Word List")
main/urls.py
from django.conf.urls import url
from main import views
urlpatterns = [
url(r'alphabetize', views.alphabetize, name='alphabetize'),
]
main/alphabetize.py
def alphabetize(s):
word_list = []
for word in s.split(','):
word_list.append(word.strip())
word_list.sort()
return ', '.join(word_list)
templates/main/alphabetize.html
{% extends "base.html" %}
{% block content %}
<form action="/alphabetize" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<p>Your list alphabetized: {{ alpha_list }}</p>
{% endblock content %}
/templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Awesome Django Page</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div class="main">
{% block content %}{% endblock content %}
</div>
</body>
</html>
It seems that for some reason request is a string rather than an HttpRequest object, but I can't figure out why that would be.
You have two different functions called alphabetize; your view, and your utility function. As a result your view is calling itself, rather than the other function.
You should rename one of these.
Your view name overrides imported function alphabetize. Change view name to fix:
from .alphabetize import alphabetize
from .forms import WordListForm
def alphabetize_view(request):