NoReverseMatch at / Error during template rendering - python

When I open http://127.0.0.1:8000/ which is home.html, I am getting:
NoReverseMatch at / and Reverse for 'exam-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['exam/(?P[^/]+)$']
I think the error is due to <str:pk> in urls.py.
The urls.py file is below:
from . import views
from .views import ExamListView, ExamDetailView
app_name='map'
urlpatterns = [
path("", ExamListView.as_view(), name='map-home'),
path("exam/<str:pk>", ExamDetailView.as_view(), name="exam-detail"),
path("login_student/", views.login_student, name='map-login'),
path("register_student", views.register_student, name='map-register'),
path('add_student/', views.add_student, name='add_student'),
path('front/', views.front, name="front"),
]
models.py:
subject = models.TextField(primary_key = True, unique = True)
def __str__(self):
return self.subject
home.html
{% extends "map/base.html" %}
{% block content %}
<p>WELCOME HOME</p>
{% for exam in exams %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'map:exam-detail' exam.subject %}">{{ exam }} </a>
</div>
</div>
</article>
{% endfor %}
{% endblock content %}
base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'map/main.css' %}">
{% if title %}
<title>{{ title }}</title>
{% else %}
<title> MAP PAGE </title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="/">Project M.A.P</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'map:map-home' %}">Home</a> <!-- no hardcoded links -->
<a class="nav-item nav-link" href="{% url 'map:map-home' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
<a class="nav-item nav-link" href="{% url 'map:map-register' %}">Student</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>[enter image description here][1]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.urls import reverse
from . models import Student, Exam
from django.views.generic import ListView, DetailView
def home(request):
context = {
'exams': Exam.objects.all()
}
return render(request, 'map/home.html', context)
class ExamListView(ListView): #class based views
model = Exam
template_name = 'map/home.html' #<app>/<model>_<viewtype>.html
context_object_name = 'exams'
ordering = ['subject'] #['-exam']
class ExamDetailView(DetailView):
model = Exam

You missed exam.pk in the home.html
Update your code in this manner,
<div class="article-metadata">
<a class="mr-2" href="{% url 'map:exam-detail'
exam.pk %}">{{ exam }} </a>
</div>
</div>

In
python manage.py shell
from my_app_name.models import Exam
exam = Exam()
exam.subject = ""
exam.save()
I have executed these lines. and I also created exams for subject like "google", "english",..
Now Exam.objects.all() returns
<QuerySet [<Exam: google>, <Exam: english>, <Exam: >]>
The problem is due to having a string of length zero as subject for one of the exam object. Now I deleted that exam using Exam.objects.get(subject="").delete(). Problem solved.
{% url 'map:exam-detail' exam.subject %}
or
{% url 'map:exam-detail' exam %}
or
{% url 'map:exam-detail' exam.pk %}
all these are working now because all are returning the subject. But {% url 'map:exam-detail' exam.id %} won't work. Because I have made subject as primary_key in the Exam model, so Exam model don't have an attribute id(which is added by default when no primary_key is mentioned).
thinking about why it has accepted the empty string as a subject, though I have defined it as primary_key.
Then I wanna read about django.db.models.TextField and just keyed help(TextField) and got
TextField(verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=<class 'django.db.models.fields.NOT_PROVIDED'>, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None)
Now tried validators...
The follow up problem link
Thank you all
Mounika

Related

Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']

I am working on a Small Django Blog project but got stuck with this error:-
NoReverseMatch at /
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.0.8
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']
Exception Location: /home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
Python Executable: /home/manish/Videos/open-source/Blog-Env/bin/python
Python Version: 3.8.2
Python Path:
['/home/manish/Videos/open-source/Blogger/mysite',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages']
Server time: Sat, 22 Aug 2020 14:40:46 +0530
Here's the Django codes:-urls.py
from django.urls import path
from .views import (
PostDetailView,
PostUpdateView,
PostDeleteView,
PostListView,
about,
post_create,
Profileview
)
urlpatterns = [
path("", PostListView.as_view(), name="blog-home"),
path("about/", about, name="blog-about"),
path("profileview/<name>", Profileview, name="blog-profile"),
path("post/<int:pk>/", PostDetailView.as_view(), name="post-detail"),
path("post/<int:pk>/update/", PostUpdateView.as_view(), name="post-update"),
path("post/<int:pk>/delete/", PostDeleteView.as_view(), name="post-delete"),
path("post_create/", post_create, name="post_create"),
]
Here's the views.py file:-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Post
from django.views.generic import ListView
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import DetailView, UpdateView, DeleteView
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import PostForm
from django.db.models import Q
class PostDetailView(DetailView):
model = Post
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
............
............
Here's the base.html file:-
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="stylesheet" href="{% static 'blog/main.css' %}" type="text/css">
<title></title>
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
<a class="nav-item nav-link" href="/about">About</a>
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'post_create' %}">Post Create</a>
{% endif %}
<!--Search Bar-->
<div class="search-bar">
<form method="GET" action="/" style="display:inline-block; line-height:24px; border-radius: 80px">
<input type="text" placeholder=" Search Blogs..." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = ' Search Blogs...';}" name ="q" required="" size="29" style="border-radius: 80px">
</form>
</div>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<!--Slider Start-->
{% block slider%}
{% endblock %}
<!--Slider End-->
<span style="display:inline-block; width: 3px;"></span>
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for messages in messages %}
<div class="alert alert-{{ message.tags }}">
{{ messages }}
</div>
{% endfor %}
{% endif %}
{% block content %}
{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
I think something has to be done with the urls.py or in some changes in the base.html file. Since the problem is arising in the root URL. I have tried doing changes here and there nothing seems to be fixing this issue.
here's the home.html file:-
{% extends 'blog/base.html' %}
{% block slider%}
<div class="slider">
<input name="input-slider" id="input-slide-0" type="radio" class="input-slide input-slide-num" style="display: none;" />
<input name="input-slider" id="input-slide-1" type="radio" class="input-slide input-slide-num" style="display: none;" />
<input name="input-slider" id="input-slide-2" type="radio" class="input-slide input-slide-num" style="display: none;" />
<input name="input-slider" id="input-slide-3" type="radio" class="input-slide input-slide-num" style="display: none;" />
<input name="input-slider" id="input-slide-autoplay" type="radio" class="input-slide" checked style="display: none;" />
<ul>
<li class="slide-0"></li>
<li class="slide-1"></li>
<li class="slide-2"></li>
<li class="slide-3"></li>
</ul>
<div class="slide-description">
<label class="slide-0">
<h1 class="text-slide">{{ mostliked1.title }}</h1>
<h5>{{mostliked1.content|truncatechars:70}}</h5>
Read More
</label>
<label class="slide-1">
<h1 class="text-slide">{{ mostliked2.title }}</h1>
<h5>{{mostliked2.content|truncatechars:70}}</h5>
Read More
</label>
<label class="slide-2">
<h1 class="text-slide">{{ mostliked3.title }}</h1>
<h5>{{mostliked3.content|truncatechars:70}}</h5>
Read More
</label>
<label class="slide-3">
<h1 class="text-slide">{{ mostliked4.title }}</h1>
<h5>{{mostliked4.content|truncatechars:70}}</h5>
Read More
</label>
</div>
<div class="slider-dot">
<label class="slide-0" for="input-slide-0"></label>
<label class="slide-1" for="input-slide-1"></label>
<label class="slide-2" for="input-slide-2"></label>
<label class="slide-3" for="input-slide-3"></label>
</div>
</div>
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% endblock%}

Error appear after runing my flask code : jinja2.exceptions.TemplateSyntaxError

when i run the below code i have this error:
jinja2.exceptions.TemplateSyntaxError: unexpected '%'
please note that i copied this code from you-tuber which working with him properly
i review my code and checked the syntax but i did not find any error so please any one can help
this is the python file:
from flask import Flask, render_template, url_for
app = Flask(__name__)
posts = [
{
'author': 'Corey Schafer',
'title': 'Blog Post 1',
'content': 'First post content',
'date_posted': 'April 20, 2018'
},
{
'author': 'Jane Doe',
'title': 'Blog Post 2',
'content': 'Second post content',
'date_posted': 'April 21, 2018'
}
]
#app.route("/")
#app.route("/home")
def home():
return render_template('home.html', posts=posts)
#app.route("/about")
def about():
return render_template('about.html', title='About')
if __name__ == '__main__':
app.run(debug=True)
and this is the html files:
home.html:
{% extends "layout.html" %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<h2><a class="article-title" href="#">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}
about.html:
{% extends "layout.html" %}
{% block content %}
<h1>About Page</h1>
{% endblock content %}
layout.html:
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
{% if title %}
<title>Flask Blog - {{ title }}</title>
{% else %}
<title>Flask Blog</title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="/">Flask Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="/">Home</a>
<a class="nav-item nav-link" href="/about">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
<a class="nav-item nav-link" href="/login">Login</a>
<a class="nav-item nav-link" href="/register">Register</a>
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
as far as I know, template inheritance goes something like this
{% block content %}
your content
{% endblock %}
maybe you are ending the blocks wrong like {% endblock content %}
look here for more explanation

Django search view not generating html page I set

I am having trouble getting my search form to work in Django. When I search anything in the search bar I have set, I get an html page that just has the words Search on it. It's not the html page I set, though. My search template is in my projects templates directory. I am trying to search through my blog posts, and have attached my views and urls code.
This portion of my base template is within a navbar I grabbed from a sample Bootstrap blog template. This is the sample template. I've changed some things within my form.
base.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet" type='text/css'>
{% load static %}
<!-- Navbar here -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="{% url 'index' %}">ChairBlog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'index' %}active{% endif %}" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'project_index' %}active{% endif %}" href="{% url 'project_index' %}">Projects </a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'blog_index' %}active{% endif %}" href="{% url 'blog_index' %}">Blog </a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="GET">
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search blog posts...">
<button class="btn my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- Jumbotron stuff here -->
<div class="jumbotron d-flex align-items-center" style="margin-top: 56px;">
<div class="container text-center">
{% block jumbo_content %}
{% endblock %}
</div>
</div>
<!-- Main content goes here -->
<div class="container" style="padding-bottom: 200px;">
{% block page_content %}{% endblock %}
</div>
<!-- Footere here -->
<footer style="position: relative;">
<div class= "page-footer bg-dark" style="padding-top: 20px; margin-top: 50px;">
<div class="container" style="display: flex; justify-content: center;">
<div class= "row">
<div class="mb-10 flex-center">
<a class="github" href="https://github.com/ChairMane"><i class="fa fa-github-square fa-2x"></i></a>
</div>
</div>
</div>
<div class="footer-copyright text-center py-3" style="color: white;">Chair Birds Co.</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
Nothing within my blocks shows up when I view it. The tags <p>TEST</p> and <p>Is this working?</p> are not showing up. Neither is the block for the jumbo_content. I have set those correctly in my base.html, because they work with my other pages. It's just the search page it doesn't work on.
search.html
{% extends "base.html" %}
{% load static %}
{% block jumbo_content %}
<h1 class="display-4">Search Results</h1>
{% endblock %}
{% block page_content %}
<p>TEST</p>
{% if query %}
{% if results %}
<ul>
{% for post in results %}
<p>Is this working?</p>
<li>
{{ post.title }}, {{ post.body }}
</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
{% endif %}
{% endif %}
{% endblock %}
app/views.py
...
def search_posts(request):
query = request.GET.get('q', '')
if query:
queryset = (Q(title__icontains=query) | Q(body__icontains=query))
results = Post.objects.filter(queryset).distinct()
else:
results = []
context = {
'results' : results,
'query' : query
}
return render(request, 'search.html', context)
...
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_index, name='blog_index'),
path('<int:pk>/', views.blog_detail, name='blog_detail'),
path('<category>/', views.blog_category, name='blog_category'),
path('search/', views.search_posts, name='search'),
]
Here is how the search template is being viewed, I believe. My issues are as shown in the image. The inspector shows nothing within the blocks I've set. I have jumbo_content and page_content, and yet none of what I set within each block shows up.
Can anyone see anything immediately wrong here? I've tried this tutorial as well, and the same thing happens.
EDIT It seems my search_posts(request) function in my views is not even being called when I search something in the search bar. I tried tracebacks, and printing and nothing showed up in my terminal. Am I not correctly calling search_posts(request)?
I finally got my answer. I looked at this post and decided to try something. Apparently, if I change my app/urls.py line from this:
path('search/', views.search_posts, name='search'),
to this:
path('search', views.search_posts, name='search'),
then my whole view works.
Can anyone explain why that is? I had no idea removing a / could help.

How to fix: Django forms: {{ form }} is not working in a dynamic html page

I've created a dorm in Django:
#forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
number = forms.FloatField()
eail_user = forms.EmailField()
and imported in in views.py
#views.py
from django.shortcuts import render
from .models import Cards
from cards.forms import ContactForm
def index(request):
cards = Cards.objects.all()
return render(request,'card.html', {'cards':cards})
def contact(request):
form = ContactForm()
return render(request,'name.html', {'form': form})
I have created three html files, name.html, base.html and card.html. The form is showing up in name.html properly, however, in cards.html, it just shows a single button and it omits {{ form }} tag. Any idea how to solve the issue?
Thanks.
#name.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</body>
</html>
This is base.html
#base.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="{% static 'css/stylesheet.css' %}" rel="stylesheet" type="text/css">
<!------ Include the above in your HEAD tag ---------->
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<section id="team" class="pb-5">
<div class="container">
<h5 class="section-title h1">OUR TEAM</h5>
<div class="row">
{% block content %}
{% endblock %}
</div>
</div>
</section>
</body>
</html>
And this is card.html which extends from base.html
#card.html
{% extends 'base.html' %}
{% block content %}
<!-- Team -->
{% for card in cards %}
<!-- Team member -->
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip">
<div class="frontside">
<div class="card">
<div class="card-body text-center">
<p><img class=" img-fluid"
src="https://sunlimetech.com/portfolio/boot4menu/assets/imgs/team/img_01.png"
alt="card image"></p>
<h4 class="card-title">{{ card.name }}</h4>
<p class="card-text">{{ card.description }}</p>
<i class="fa fa-plus"></i>
</div>
</div>
</div>
<div class="backside">
<div class="card">
<div class="card-body text-center mt-4">
<h4 class="card-title">{{ card.name }}</h4>
<!--<p class="card-text"> {{ card.back_description }}-->
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<!--</p> -->
<ul class="list-inline">
<li class="list-inline-item">
<a class="social-icon text-xs-center" target="_blank" href="#">
<i class="fa fa-facebook"></i>
</a>
</li>
<li class="list-inline-item">
<a class="social-icon text-xs-center" target="_blank" href="#">
<i class="fa fa-twitter"></i>
</a>
</li>
<li class="list-inline-item">
<a class="social-icon text-xs-center" target="_blank" href="#">
<i class="fa fa-skype"></i>
</a>
</li>
<li class="list-inline-item">
<a class="social-icon text-xs-center" target="_blank" href="#">
<i class="fa fa-google"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ./Team member -->
{% endfor %}
{% endblock %}
Function index is missing a ContactFrom initialization, that's why it's not showing up. Try this:
def index(request):
cards = Cards.objects.all()
form = ContactForm()
return render(request,'card.html', {'cards':cards, 'form': form})

change size of form post box in Django

Hi I would like to change the size of my form post box (where the placeholder sits), its quite long. I was wondering how I would change it with my code below:
forms.py
from django import forms
from home.models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'How are you feeling?',
}
))
class Meta:
model = Post
fields = ('post',)
home.html:
{% extends 'base.html' %}
{% block body%}
<div class="container">
<br/>
<form method="post">
{% csrf_token %}
{{ form.post }}
<br />
<button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{ post.post }}</h1>
<p>Posted </b> on {{ post.created }}</p>
{% endfor %}
</div>
{% endblock %}
base.html:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% block head %}
<title>anonmy</title>
{% endblock %}
</head>
<body>
<br>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
{% if user.is_authenticated %}
<ul class="nav navbar-nav">
<li><b>anonmy</b></li>
<li><a href='{% url 'home:categories' %}'>categories</a></li>
<li>profile</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>log out</li>
</ul>
{% else %}
<ul class="nav navbar-nav">
<li>anonmy</li>
<li>login</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>forgotten password?</li>
<li>register</li>
</ul>
{% endif %}
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
</div>
{% block body %}
<h1>Base</h1>
{% endblock %}
</body>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
I know how to change a standard html form, but with ginger two templating/django im unsure.Would I have to add a css file to my project then edit it or do something in forms.py?
Thank you
you just edit it like a standard html file by adding a css file and use the class name you entred in the form attrs
Add this under your model form class
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['post'].widget.attrs.update({'size': '20'})
More about this here: Widgets

Categories

Resources