Django - Items not showing up in Products page - python

I'm trying to create a basic e-commerce site in Django. I have created a products page and when I open the page, my products are not showing up. I'm new to Django and have no idea what to do.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('products', views.products)
]
views.py
from django.shortcuts import render
from products.models import Product
def index(request):
products = Product.objects.all()
return render(request, 'index.html', {'products': products})
def products(request):
return render(request, 'products.html')
index.html file in templates folder
<!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.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>{% block title %}{% endblock title %}PyShop</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">PyShop</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/products">Products</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
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.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</body>
</html>
products.html file in the same templates folder
{% extends 'base.html' %}
{% block content %}
<h1 class="my-2">Products</h1>
<div class="row">
{%for p in products%}
<div class="col">
<div class="card" style="width: 18rem;">
<img src="{{Product.image_url}}" class="card-img-top" alt="{{Product.name}}">
<div class="card-body">
<h5 class="card-title">{{Product.name}}</h5>
<p class="card-text">${{Product.price}}</p>
Add to cart
</div>
</div>
</div>
{%endfor%}
</div>
{% endblock content %}
I also debugged the NameError for my Product model. Now the products are not showing up.
I had encountered this problem in another project as well. Not knowing what to do, I created that project from scratch once more. The problem still continues.

I think your are confusing !
do the following instruction :
1-remove this code
def products(request):
return render(request, 'products.html')
2- in products.html remove
{% extends 'base.html' %}
add this code :
{% extends 'index.html' %}

I think your mistake in for loop check the
products = Product.objects.all()
return render(request, 'index.html', {'products': products}) #products is send to index.html and the the for loop syntax is for name_of_params in para
Your for loop is wrong.
Yours: {%for p in products%}
Solution: {%for product in p %}

Related

Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'

I have visited these answers too Running Flask environment using HTML:receiving error message of expected else statement and How to fix jinja2 exceptions Template SyntaxError: but could not solve the problem.
I am a beginner at Flask and tried using jinja2 template inheritance. Here are my files.
index.html
{% extends "layout.html" %}
{% block body %}
<!-- Page Header-->
<header class="masthead" style="background-image: url('{{ url_for('static',filename='assets/img/home-bg.jpg') }}')">
<div class="container position-relative px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="site-heading">
<h1>Clean Blog</h1>
<span class="subheading">A Blog Theme by Start Bootstrap</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content-->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<!-- Divider-->
<hr class="my-4" />
<!-- Pager-->
<div class="d-flex justify-content-end mb-4"><a class="btn btn-primary text-uppercase" href="#!">Older Posts →</a></div>
</div>
</div>
</div>
{% endblock body %}
layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<link href="{{ url_for('static',filename='css/styles.css') }}" rel="stylesheet" />
</head>
<body>
<!-- Navigation-->
<nav class="navbar navbar-expand-lg navbar-light" id="mainNav">
<div class="container px-4 px-lg-5">
<a class="navbar-brand" href="index.html">Start Bootstrap</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fas fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto py-4 py-lg-0">
<li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/">Home</a></li>
<li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/about">About</a></li>
</ul>
</div>
</div>
</nav>
{% block body %} { % endblock % }
<!-- Footer-->
<footer class="border-top">
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<ul class="list-inline text-center">
<li class="list-inline-item">
<a href="#!">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</footer>
<!-- Bootstrap core JS-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
I want to inheritent the template from layout.html to index.html. But I am getting this error:
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
I have surfed a lot of websites to solve it but could not. Any help would be highly appreciated.
Finally! I just got the reason for the error. The error was generated at this line:
{% block body %} { % endblock % }
After figuring it out, I came to know that there should be no space between the braces and the % sign. And the code should look like this.
{% block body %} {% endblock %}

How to display images from the static folder uploaded in S3 to your Flask app

I am facing issues displaying images in my flask app. below is my code use
This is my main.py
from flask import Flask, render_template, request, session, redirect, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import boto3
local_server = True
app = Flask(__name__)
app.secret_key = 'super-secret-key'
s3 = boto3.client('s3',
aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'),
aws_secret_access_key= os.environ.get('AWS_SECRET_ACCESS_KEY'),
)
BUCKET_NAME='my s3 bucket name'
#app.route("/")
def home():
posts = Posts.query.filter_by().all()
last = math.ceil(len(posts)/int(params['no_of_posts']))
#[0: params['no_of_posts']]
#posts = posts[]
page = request.args.get('page')
if(not str(page).isnumeric()):
page = 1
page= int(page)
posts = posts[(page-1)*int(params['no_of_posts']): (page-1)*int(params['no_of_posts'])+ int(params['no_of_posts'])]
#Pagination Logic
#First
if (page==1):
prev = "#"
next = "/?page="+ str(page+1)
elif(page==last):
prev = "/?page=" + str(page - 1)
next = "#"
else:
prev = "/?page=" + str(page - 1)
next = "/?page=" + str(page + 1)
return render_template('index.html', params=params, posts=posts, prev=prev, next=next)
app.run(debug=True)
this is my html template
layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>{{params['blog_name']}}</title>
<!-- Bootstrap core CSS -->
<link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{{ url_for('static', filename='vendor/font-awesome/css/font-awesome.min.css') }}" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="{{ url_for('static', filename='css/clean-blog.min.css') }}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand" href="/">{{params['blog_name']}}</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fa fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
{% block body %} {% endblock %}
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<ul class="list-inline text-center">
<li class="list-inline-item">
<a href="{{params['tw_url']}}" target="_blank">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li class="list-inline-item">
<a href="{{params['fb_url']}}" target="_blank">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li class="list-inline-item">
<a href="{{params['gh_url']}}" target="_blank">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © TheFlaskBlogger 2021</p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Custom scripts for this template -->
<script src="{{ url_for('static', filename='js/clean-blog.min.js') }}"></script>
</body>
</html>
This is one of my page
index.html
{% extends "layout.html" %}
{% block body %}
<!-- Page Header -->
<header class="masthead" style="background-image: url('{{ url_for('static', filename='assets/img/home-bg.jpg') }}')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>{{params['blog_name']}}</h1>
<span class="subheading">{{params['tag_line']}}</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{% for post in posts %}
<div class="post-preview">
<a href="/post/{{post.slug}}">
<h2 class="post-title">{{ post.title }}
</h2>
</a>
<p class="post-meta">Posted by
Admin
on {{post.date}}</p>
</div>
{{post.content[0:143]}}
<hr>
</li></a>
{% endfor %}
<!-- Pager -->
<div class="clearfix">
<a style="border-radius: 12px;" class="btn btn-primary float-left" href="{{prev}}"> ← Previous</a>
<a style="border-radius: 12px;" class="btn btn-primary float-right" href="{{next}}">Next →</a>
</div>
</div>
</div>
</div>
{% endblock %}
Please help me display the images from my amazon s3 bucket.I tried all the methods but got no success in displaying images from my S3 bucket. Also note my final outcome is to add the flask application to heroku.

Django: Book name and image is not displayed

The code was properly working before bootstrap theme, but now the book name and image are not displayed.
base.html file:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static '/books/style.css' %}" >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<a class="navbar-brand" href="{% url 'books:index' %}">The Bookstore</a>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="">
<a href="{% url 'books:index' %}">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span> Books
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="{% url 'books:book-add' %}">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add Book
</a>
</li>
<li class="">
<a href="{% url 'books:index' %}">
<span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout
</a>
</li>
</ul>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
The following HTML file is supposed to display the book name and image, but instead it displays {{book.name}} and it doesn't display book_image. The database is created and the book stored, but it is not displaying.
index.html file:
{% extends 'books/base.html' %}
{% block body %}
<link rel="stylesheet" href="books/style.css">
<div class=" col-md-12 jumbotron">
<h1>The Bookstore</h1>
<p>Collection of all popular books</p>
</div>
<div class=" col-md-10 jumbotron jumbotron-special" name="fig">
<div class="col-md-12 span-2">
<h2>Popular Books</h2>
</div>
</div>
<ul>
{% for book in object_list %}
<div class="col-lg-3 col-md-4 col-sm-6 " >
<div class = "thumbnail">
<img src = "{‌{book.book_image}}" alt = "Generic placeholder thumbnail">
<div class = "caption">
<h3>{‌{book.name}}</h3>
<p>{‌{book.author}}</p>
<p>
<a href = "{% url 'books:detail' book.id %}" class = "btn btn-primary" role = "button">
Details
</a>
<a href = "#" class = "btn btn-danger" role = "button">
Delete
</a>
</p>
</div>
</div>
</div>
{% endfor %}
</ul>
{% endblock %}
This is the view file where the functions are defined:
from django.views import generic
from .models import Book
from django.views.generic.edit import CreateView
class IndexView(generic.ListView):
template_name = 'books/index.html'
def get_queryset(self):
return Book.objects.all()
class BookCreate(CreateView):
model = Book
fields = ['name', 'author', 'price', 'types', 'book_image']
class DetailView(generic.DetailView):
model = Book
template_name = 'books/detail.html

null entries in databse and when i click them i get TypeError at /admin/users/personal_detail/90/change/ __str__ returned non-string (type NoneType)

this is how my base.html looks like,everything was working fine until i did some changes adding jquery
{% 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://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 'pmmvyapp/main.css' %}">
<link href="{% static 'js/jquery.js' %}" rel="stylesheet">
{% if title %}
<title> PMMVY-{{ title }}</title>
{% else %}
<title>PMMVY</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"><img src="{% static 'images/left-logo.png' %}" width="83" height="89" class='d-inline-block' alt=""/>
<span style="color:white"> Ministry of Women & Child Development | GoI</span>
</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">
{% if user.is_authenticated %}
<a class="btn btn-primary mr-4" href="{% url 'aganwadi' %}">Aganwadi</a>
<a class="btn btn-primary mr-4" href="{% url 'applyonline' %}">Apply online</a>
{% else %}
<div class="navbar-nav mr-auto">
<a class="navbar-brand mr-4"><img src="{% static 'images/emblem-dark.png' %}" width="60" height="80" class='d-inline-block' alt=""/> <span style="color:white" >Pradhan Mantri Matru Vandana Yojana</span> </a>
</div>
{% endif %}
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<div class="navbar-nav mr-auto">
<a class="btn btn-primary mr-4" href="{% url 'admin:index' %}"> Admin site </a>
<a class="btn btn-primary mr-4" href="{% url 'logout' %}">Logout</a>
</div>
{% else %}
<div class="navbar-nav mr-auto">
<a class="navbar-brand mr-4" href="{% url 'login' %}"><img src="{% static 'images/pm.png' %}" width="65" height="70" class='d-inline-block' alt=""/> <span class="btn btn-primary" style="color:black mr-4" >Login</span> </a>
</div>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<!--mainsec-->
<main role="main" class="container">
<div>
{% if messages %}
{% for message in messages%}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
</div>
<div class="row">
{% block content %}{% endblock %}
</div>
</main>
<!--end mainsec-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="{% static 'js/custom.js' %}"></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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</body>
</html>
this is how my applyonline.html looks like
<body ng-app="">
{% extends "pmmvyapp/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content%}
<div class="col-md-8">
<form method="post" action="/personal_detail/" enctype="multipart/form-data">
<div class="group">
<div class="hide" id="q1">
</div>
</div>
</div>
<div class="hide" id="q2">two</div>
<div class="hide" id="q3">three</div>
<div class="hide" id="q4">four</div>
</div>
<div style="margin-bottom:10px ">
<button id="next">Next</button> <button id="prev">Previous</button>
</div>
<button type="submit" class="btn btn-primary" style="margin-bottom:10px ">Submit</button>
</form>
</div>
<style>
.hide
{
display : none;
}
</style>
{% endblock %}
</body>
my settings.py
INSTALLED_APPS = [
'jquery',
'captcha',
'users.apps.UsersConfig',
'pmmvyapp.apps.PmmvyappConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
my models.py where I am returning either of the one names
class Personal_Detail(models.Model):
beneficiary_adhaar_name=models.TextField(blank=True, null=True)
adhaarno=models.IntegerField(blank=True, null=True)
adhaarcopy = models.FileField(upload_to='adhaar/')
idcard=models.TextField(blank=True, null=True)
adhaar_eid=models.IntegerField(blank=True,null=True)
beneficiary_id_name=models.TextField(blank=True, null=True)
idno=models.IntegerField(blank=True, null=True)
idcopy=models.FileField(upload_to='identitycard/')
def __str__(self):
return self.beneficiary_adhaar_name or self.beneficiary_id_name
my views.py
#login_required
def ApplyOnline(request):
return render(request,'users/applyonline.html')
#login_required
def personal_detail(request):
# ShowHideExample = request.POST.get('showHideExample',False)
beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name')
adhaarno=request.POST.get('adhaarno')
adhaarcopy = request.FILES.get('adhaarcopy')
idcard=request.POST.get('idcard')
adhaar_eid=request.POST.get('adhaar_eid')
beneficiary_id_name=request.POST.get('beneficiary_id_name')
idno=request.POST.get('idno')
idcopy = request.FILES.get('idcopy')
apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name,adhaarno=adhaarno,adhaarcopy=adhaarcopy,
idcard=idcard,adhaar_eid=adhaar_eid,beneficiary_id_name=beneficiary_id_name,idno=idno,idcopy=idcopy)
apply_online.save()
return render(request,'users/applyonline.html')
I don't know the problem that is causing this it was working fine when suddenly i did some changes with query to create a multi step form and when checked the database I was getting some null entries and when i clicked or tried to delete them I got error.I've included the image of null entries i was getting.
Basically your Model's __str__ method is returning None. Means both of the field's value is None. You need to return a string value from that method. For example:
class Personal_Detail(models.Model):
# rest of the code
def __str__(self):
return self.beneficiary_adhaar_name or self.beneficiary_id_name or str(self.pk)

How to fix: Django forms: {{ form }} doesn't show up any result in html page

I've created a django form:
#forms.py
from django import forms
class NameForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
and in view file:
#views.py
def get_form(request):
print(request.POST)
form = NameForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
return render(request, "name.html", {"title": "Contact us"})
I've imported to a html file inside templates folder:
#templates/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>
However, it doesn't show up any thing just a submit button. I have no idea what is the issue. I'll be so grateful for a solution around this issue.
Update: If I create a new html file, the form is shown there. However, if I use it in my main html including boostarp, it is not showing up. Here is the full code of my 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 %}
It made me crazy for three days. I look forward for a solution. Thanks
Update2:
#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>
#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 %}
change this line on your views.py file:
return render(request, "name.html", {"title": "Contact us"})
into this one:
return render(request, "name.html", {'form': form })

Categories