CRUD IN THE SAME PAGE DJANGO - django

I am trying to do a CRUD using only one html page with django, but I have already encountered the first problem, when using nav-tabs I am not able to load the form when I click on the Create / Edit tab, maybe it has something to do with urls, but I don't know.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Ordens de Serviço</h2>
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#list">Ordens de Serviço</a></li>
<li><a data-toggle="tab" href="#create-update">Criar/Editar</a></li>
<li><a data-toggle="tab" href="#detail">Ver</a></li>
</ul>
<div class="tab-content">
<div id="list" class="tab-pane fade in active">
<h3>Ordens de Serviço</h3>
<table class="table">
<thead>
<tr>
<th>Nome</th>
<th>TAG</th>
<th>nivel</th>
</tr>
</thead>
<tbody>
{%for equipamento in equipamentos %}
<tr>
<td>{{equipamento.nome}}</td>
<td>{{equipamento.tag}}</td>
<td>{{equipamento.nivel}}</td>
<td><a><button class="btn btn-primary">Editar</button></a></td>
</tr>
{%endfor%}
</tbody>
</table>
</div>
<div id="create-update" class="tab-pane fade">
<h3>Criar/Editar</h3>
<form method="post">
{% csrf_token %}
{{form}}
</form>
</div>
<div id="detail" class="tab-pane fade">
<h3>Menu 2</h3>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
views.py:
class ArvoreListView(ListView):
queryset = Arvore.objects.all()
template_name = 'example/index.html'
context_object_name = 'equipamentos'
class ArvoreCreateView(CreateView):
form_class = ArvoreModelForm
model = Arvore
template_name = 'example/create.html'
urls.py
urlpatterns = [
path('', ArvoreListView.as_view(), name='list'),
path('create/', ArvoreCreateView.as_view(), name='create'),
]
when I click on the second tab the form does not render

Related

Django Python DetailView not working as expected. I get an issue when I try and view a specific note

Advice required. would someone point me in the right direction?
Using Django 3.1.1 with Pycharm Community 2020.2
I'm working with ListView to show all To-Do notes on one page
allTasks.html
{% extends "app/base.html" %}
{% load static %}
{% block content %}
<body>
<div class="section">
<div class="container" id="heading">
<h3>List of all Tasks to-date</h3>
</div>
<div class="container">
<ul id="taskcontainer">
{% for i in obj %}
<li>
<div class="row">
<div class="col-md-12">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">{{ i.name }}</strong>
<h6 class="mb-0">{{ i.date }}</h6>
<div class="mb-1 text-muted">Team {{ i.team_project }}</div>
<p class="card-text mb-auto">{{ i.notes }}</p>
<p class="card-text mb-auto">Priority: {{ i.urgency }}</p>
<strong class="d-inline-block mb-2 text-danger">Completed? {{ i.completed }}</strong>
<span>
View
Edit
</span>
</div>
</div>
</div>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>
</body>
From here I go into DetailView to each individual note
task_detail.html
{% extends "app/base.html" %}
{% load static %}
{% block content %}
<br>
<div class="row">
<div class="col-md-12">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">{{ object.name }}</strong>
<h6 class="mb-0">{{ object.date }}</h6>
<div class="mb-1 text-muted">Team {{ object.team_project }}</div>
<p class="card-text mb-auto">{{ object.notes }}</p>
<p class="card-text mb-auto">Priority: {{ object.urgency }}</p>
<strong class="d-inline-block mb-2 text-danger">Completed? {{ object.completed }}</strong>
<strong class="d-inline-block mb-2 text-danger">Overdue? {{ object.overdue }}</strong>
</div>
</div>
</div>
</div>
{% endblock content %}
Here is my views.py
def task(request):
form = TasksForm()
if request.method == 'POST':
form = TasksForm(request.POST or None)
if form.is_valid():
form.save()
messages.success(request, 'Task has been saved!')
return render(request, 'app/tasks.html', {'form': form})
else:
return render(request, 'app/tasks.html', {'form': form})
class TaskListView(ListView):
model = Task
template_name = 'app/allTasks.html' # <app> / <model>_<viewtype>.html
context_object_name = 'obj'
ordering = ['-date'] # ordering by date
class TaskDetailView(DetailView):
model = Task
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('task/', views.task, name='tasks'),
path('allTasks/', TaskListView.as_view(), name='allTasks'),
path('task/<int:pk>/', TaskDetailView.as_view(), name='task-detail'),
]
my issue as below
NoReverseMatch at /allTasks/
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task/(?P<pk>[0-9]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/allTasks/
Django Version: 3.1.1
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task/(?P<pk>[0-9]+)/$']
Exception Location: C:\Users\mackm\PycharmProjects\IT6041-Project\venv\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable: C:\Users\mackm\PycharmProjects\IT6041-Project\venv\Scripts\python.exe
Python Version: 3.8.5
Python Path:
['C:\\Users\\mackm\\PycharmProjects\\IT6041-Project\\IT6041_Project_Folder',
'C:\\Users\\mackm\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\mackm\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\mackm\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\mackm\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\mackm\\PycharmProjects\\IT6041-Project\\venv',
'C:\\Users\\mackm\\PycharmProjects\\IT6041-Project\\venv\\lib\\site-packages']
Server time: Mon, 12 Oct 2020 03:48:26 +0000
Error during template rendering
In template C:\Users\mackm\PycharmProjects\IT6041-Project\IT6041_Project_Folder\app\templates\app\base.html, error at line 22
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task/(?P<pk>[0-9]+)/$']
12 <link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/album/">
13
14 <!-- Bootstrap core CSS -->
15 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
16 integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
17 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
18 integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
19 crossorigin="anonymous"></script>
20 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
21 integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
22 crossorigin="anonymous"></script>
23 <script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
24 integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
25 crossorigin="anonymous"></script>
26
27 <style>
28 .bd-placeholder-img {
29 font-size: 1.125rem;
30 text-anchor: middle;
31 -webkit-user-select: none;
32 -moz-user-select: none;
base.html
{% load static %}
<!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="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Jekyll v4.1.1">
<title>My Project App</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/album/">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<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.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link rel="stylesheet" href="{% static 'app/album.css' %}" type="text/css">
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/admin/">Admininstration</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'tasks' %}">To-Do</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Meeting Minutes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reflectives</a>
</li>
</ul>
<form class="form-inline">
<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>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% block content %}
{% endblock %}
</div>
</div>
</main>
<footer class="text-muted">
<div class="container">
<p class="float-right">
Back to top
</p>
<p>This is a Bootstrap Album example, reconfigured to suit my project. </p>
<p>New to Bootstrap? Visit the homepage or read our getting started guide.</p>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../assets/js/vendor/jquery.slim.min.js"><\/script>')</script>
<script src="../assets/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
I would appreciate any assistance with this. Thank you in advance
in your allTasks.html you use {% url 'task-detail' task.id %}
but you don't have task object.
Earlier you define loop - {% for i in obj %}, so your url should be {% url 'task-detail' i.id %}

Form not displaying on Django site

I have just started learning Django and I have hit a little snag and was hoping someone could help.
Problem:
My form is not displaying in my main HTML template (ingredior.html) but the form will display in my test HTML template (test.html) which is just a boiler plate HTML file with the {{form1}} tag in the body. I am changing "return render(request, 'ingredior/ingredior.html', context)" in the views.py file manually to test the two different HTML templates.
ingredior.html
test.html
Question:
Why is the form working in the test.html and not the ingredior.html file when changed?
Please keep in mind that I am swapping this line of code "return render(request, 'ingredior/ingredior.html', context)" with "return render(request, 'ingredior/test.html', context)" to test between the two.
CODE---------
Forms.py
from django import forms
class UserInput(forms.Form):
base_search_ingredient = forms.ChoiceField(choices=[('vegan', 'Vegan'), ('vegatarian', 'Vegatarian')])
views.py
from django.shortcuts import render
import requests
from .local_api_key import Key
from .forms import UserInput
def index (request):
app_id = Key.app_id
app_key = Key.app_key
search_from = 0
search_to = 100
form1 = UserInput()
test = []
if request.POST.get('search'):
test2 = request.POST.get('search')
intolerance = test2
url = requests.get(f"https://api.edamam.com/search?q={intolerance}&excluded=egg&excluded=beef&excluded=dairy&excluded=tomato&excluded=cherry%20tomatoes&excluded=rice&excluded=corn&excluded=soy&excluded=onion&from={search_from}&to={search_to}&health={intolerance}&app_id={app_id}&app_key={app_key}").json()
recipe_length = (len(url['hits']))
else:
intolerance = 'vegan'
url = requests.get(f"https://api.edamam.com/search?q={intolerance}&excluded=egg&excluded=beef&excluded=dairy&excluded=tomato&excluded=cherry%20tomatoes&excluded=rice&excluded=corn&excluded=soy&excluded=onion&from={search_from}&to={search_to}&health={intolerance}&app_id={app_id}&app_key={app_key}").json()
recipe_length = (len(url['hits']))
for urls in range(recipe_length):
recipe_name = (url['hits'][urls]['recipe']['label'])
recipe_url = (url['hits'][urls]['recipe']['url'])
recipe_image = (url['hits'][urls]['recipe']['image'])
recipe_healthLabels = (url['hits'][urls]['recipe']['healthLabels'])
recipe_ingredients = (url['hits'][urls]['recipe']['ingredientLines'])
test.append((recipe_name, recipe_url, recipe_image, recipe_healthLabels, recipe_ingredients))
context = {'test': test, 'form1': form1}
return render(request, 'ingredior/ingredior.html', context)
ingredior.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Nake Recipes</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href=>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style>
.card {
width: 300px;
height: 700px;
overflow: scroll;
float: left;
margin: 13px;
}
.list {
line-height: 2em;
text-align: left;
}
.card-content ul {
height: 100px
overflow-y: scroll;
}
.container h1 {
text-align: center;
}
</style>
</head>
<body>
<nav>
<div class="container nav-wrapper">
Naked Recipes
<ul id="nav-mobile" class="right">
<li>Home</li>
</ul>
</div>
</nav>
<div class="container">
<h1 style="text-align: c">What intolerance do you have?</h1>
<div class="row">
<div class="col s4">
<!-- Promo Content 1 goes here -->
<div class="center">
<i class="large material-icons" style="color: #EE6E73">flash_on</i>
<p></p>
<p class="light center"></p>
</div>
</div>
<div class="col s4">
<!-- Promo Content 2 goes here -->
<div class="center">
<i class="large material-icons" style="color: orange">camera</i>
<p></p>
<p class="light center"></p>
</div>
</div>
<div class="col s4">
<!-- Promo Content 3 goes here -->
<div class="center">
<i class="large material-icons" style="color: blue">chrome_reader_mode</i>
<p></p>
<p class="light center"></p>
</div>
</div>
</div>
<br>
<form action="" method="post">
{% csrf_token %}
{{ form1 }}
</form>
<br>
<div class="row">
{% for item in test %}
<div class="col_s2">
<div class="card">
<div class="card-image">
<img src= {{ item.2 }} alt="">
</div>
<div class="card-content scroll">
{{ item.0 }}<br><br>
<p>
<b>Ingredients</b><br>
</p>
<ul class="list">
{% for litem in item.4 %}
<li>- {{ litem }}</li>
{% endfor %}
</ul>
<ul class="list">
<p>
<b>Allergies</b>
</p>
{% for litem in item.3 %}
<li>- {{ litem }}</li>
{% endfor %}
</ul>
</div>
<div class="card-action">
<a href={{ item.1 }}>Get Full Recipe </a>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" >
{% csrf_token %}
{{ form1 }}
</form>
</body>
</html>
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
]
Thank you in advance 😅
** UPDATE **
On further investigation :
Inspection Image ingredior.html
Inspection Image test.html
They are the same.

Django formset dynamic add row to table

i have created a formset that is rendering in table and when i add a row the input box only is rendered in the first row and the second row is only the template code appearing.
the table will be a form posted to a view function for Formset process to capture all the data in the added dynamic table with add row.
HTML
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Dashboard - Brand</title>
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i">
<link rel="stylesheet" href="{% static 'assets/css/Navigation-Clean.css' %}">
</head>
<body id="page-top">
<div></div>
<div>
<nav class="navbar navbar-light navbar-expand-sm border rounded shadow-sm navigation-clean">
<div class="container"><a class="navbar-brand" href="#">Company Name</a><button data-toggle="collapse" data-target="#navcol-1" class="navbar-toggler"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse"
id="navcol-1">
<ul class="nav navbar-nav ml-auto">
<li role="presentation" class="nav-item"><a class="nav-link active" href="#">My Startup</a></li>
<li role="presentation" class="nav-item"><a class="nav-link" href="#">Campaigns</a></li>
<li role="presentation" class="nav-item"><a class="nav-link" href="#">Guide</a></li>
<li class="dropdown nav-item"><a data-toggle="dropdown" aria-expanded="false" class="dropdown-toggle nav-link" href="#">Account</a>
<div role="menu" class="dropdown-menu"><a role="presentation" class="dropdown-item" href="#">Edit</a><a role="presentation" class="dropdown-item" href="#">Reset Password</a><a role="presentation" class="dropdown-item" href="#">Log Out</a></div>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div>
<div class="container">
<div class="row"></div>
</div>
</div>
<div>
<div class="container">
<div class="row">
<div class="col-md-12" style="padding-top: 31px;">
<div class="card shadow mb-4" style="padding: 0;padding-top: 2;">
<form id="my-form" method="post"> {% csrf_token %}
<div class="card-body" style="background-color: rgba(255,255,255,0);"><button id="Add" class="btn btn-primary" type="button">+ Add</button>
<div class="table-responsive">
{% for form in formset %}
<table class="table">
<thead>
<tr>
<th style="width: 21px;"></th>
<th style="width: 295px;">Name</th>
<th style="width: 257px;">Position</th>
<th style="width: 59px;">Service</th>
<th style="width: 267px;">Previouse Position</th>
<th style="width: 64px;">Service</th>
</tr>
</thead>
<tbody>
<tr>
<td><button id="Remove" class="btn btn-danger" type="button">-</button></td>
<td>{{form.name}}</td>
<td>{{form.position}}</td>
<td>{{form.service}}</td>
<td>{{form.Previous_Position}}</td>
<td>{{form.service_exp}}</td>
</tr>
<tr></tr>
</tbody>
</table>
{% endfor %}
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="wrapper">
<div class="d-flex flex-column" id="content-wrapper">
<div id="content">
<div class="container-fluid"></div>
</div>
<footer class="bg-white sticky-footer">
<div class="container my-auto">
<div class="text-center my-auto copyright"><span>Copyright © Brand 2019</span></div>
</div>
</footer>
</div><a class="border rounded d-inline scroll-to-top" href="#page-top"><i class="fas fa-angle-up"></i></a></div>
<script src="{% static 'assets/js/jquery.min.js' %}"></script>
<script src="{% static 'assets/js/tt.js' %}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'assets/js/theme.js' %}"></script>
</body>
</html>
JS Code for adding rows:
var html = '<tr><td><button id="Remove" class="btn btn-danger" type="button">-</button></td><td>{{form.name}}</td><td>{{form.position}}</td><td>{{form.service}}</td><td>{{form.Previous_Position}}</td><td>{{form.service_exp}}</td></tr>';
$(function(){
$(document).on('click','#Add', function(){
$('tbody').append(html);
})
});
```````

How use TemplateView with 2 methods (get and post)

I am trying to use Templateview in Django to render a page with options for both adding to the database and retrieving some info from the database and displaying it. I am basing it on the tutorial at https://www.youtube.com/watch?v=VxOsCKMStuw
views.py:
class TestView(TemplateView):
template_name = 'app/sensor_name_tmpl.html'
def get(self, request):
form = SensorForm()
posts = Sensor.objects.all()
args = {'form': form, 'posts': posts}
return render(request, self.template_name, args)
def post(self, request):
form = SensorForm(request.POST)
if form.is_valid():
form.save()
text = form.cleaned_data['post']
form = SensorForm()
return redirect('sensor_name_tmpl:sensor_name_tmpl')
args = {'form': form, 'text': text}
return render(request, self.template_name, args)
urls.py:
urlpatterns = [
path('', views.index, name='index'),
url(r'^form1/$', views.get_sensor_name, name='GiveSensorName1'),
#url(r'^form2/$', TestView.as_view(), name='sensor_name_tmpl.html'),
path('form2/', TestView.as_view(), name='app/sensor_name_tmpl.html'),
url(r'^nested_admin/', include('nested_admin.urls')),
]
HTML template:
<!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">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$('#toggle').click(function() {
$('form').toggle('slow');
});
</script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Hello world!</title>
</head>
<body>
<h3 class="text-success">Add Sensor</h3>
<br>
<!-- <form style="display:none;" method="post">-->
<form method="post">
{% csrf_token %}
<div class="row align-items-center">
<div class="col-sm-8">
<table>
{{ form1.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class = "text-success">Add Sensor View</h3>
<table>
{{ form2.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class="text-success">View Sensors</h3>
<table class="table">
<thead>
<tr>
<th scope="col">Sensor ID</th>
<th scope="col">Sensor Name</th>
</tr>
</thead>
<tbody>
{%for obj in obj%}
<tr>
<td>{{obj.sensor_id}}</td>
<td>{{obj.sensor_name}}</td>
<!-- <th scope="row">1</th>-->
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
</form>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
</body>
</html>
The page renders the template but doesn't populate it with either the formfields or the data from the database.
The problem was with the HTML template where form1 and form2 have now been replaced with form and "obj" in the for loop has been replaced with "posts". The template now looks as follows:
<!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">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$('#toggle').click(function() {
$('form').toggle('slow');
});
</script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Hello world!</title>
</head>
<body>
<h3 class="text-success">Add Sensor</h3>
<br>
<!-- <form style="display:none;" method="post">-->
<form method="post">
{% csrf_token %}
<div class="row align-items-center">
<div class="col-sm-8">
<table>
{{ form.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class = "text-success">Add Sensor View</h3>
<table>
{{ form.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class="text-success">View Sensors</h3>
<table class="table">
<thead>
<tr>
<th scope="col">Sensor ID</th>
<th scope="col">Sensor Name</th>
</tr>
</thead>
<tbody>
{%for obj in posts%}
<tr>
<td>{{obj.sensor_id}}</td>
<td>{{obj.sensor_name}}</td>
<!-- <th scope="row">1</th>-->
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
</form>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
</body>
</html>
Being a beginner Django Developer, I will suggest that it is actually not advisable to use TemplateView class for any kind updating of objects or if your template is having a form. You can read more about this here.

Irrelevant Alert message before performing any image upload in django

i have been working on my image upload portion of my web app and developing it using Django.My Image Upload functionality working absolutely fine.No problem with that.
But in my image upload page i am getting unnecessary alert message at a time such as "You have been singed in","You have been signed out" after making a sign in and sign out and this alert message is appearing after entering in my image uplaod page,which is weired!.
Yeah i have set django message tag in my Image upload template to show alert message if user make any image upload action.But i don't want to get any alert message such as "You have been signed in" or "You have been signed out" or something irrelevant in my image upload page after entering in my image upload page to upload an image.But unfortunately its happening and after making lot's of googling and research ,i can't figure it out.
In mention i am using django form and django message framework.
This is my view for the image upload
def UserImageUpload(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])
newdoc.save()
messages.success(request,'Your Image upload is waiting for Admin approval')
form = DocumentForm
else:
messages.error(request,'Please Complete All Fields or Only upload jpg file,because we are currently accepting only the jpg file!')
else:
form = DocumentForm()
uploaded_image = Photo.objects.all()
return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))
and this is Image upload form template
{% extends 'base.html'%}
{% block title%}User Image Upload {% endblock %}
{%block content%}
<div id="messages" style="margin-top:50px">
{% if messages %}
<!--<div class="row"> -->
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
<!--<p{%if message.tags=="success"%} class="alert alert-success" {%endif%}>{{message}}</p> -->
<button type="button" class="close" data-dismiss="alert"></button>
{{ message }}
</div>
{% endfor %}
<!--</div> -->
{% endif %}
</div>
<div class="container" style="margin-top:5%" ng-app="ImageUpload">
<div class="col-md-4 col-md-offset-4" ng-controller="ImagePreviewCtrl">
<div class="well" ng-show="show">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.photo.label_tag }} {{ form.photo.help_text }}</p>
<ul class = 'unstyled'>
<li class = 'tust'>{{form.name.label}}{{ form.photo.errors }}</li>{{form.name}}<br/>
<li class = 'tust'>{{form.description.label}}{{ form.photo.errors }}</li>{{form.description}}<br/>
<li class = 'tust'>{{form.Image_Keyword.label}}{{ form.photo.errors }}</li>{{form.Image_Keyword}}<br/>
<li class = 'tust'>{{form.Certification.label}}{{ form.photo.errors }}</li>{{form.Certification}}<br/>
{{ form.photo }}
</ul>
<input type="submit" value="Upload" class="btn btn-success" />
</form>
</div>
</div>
</div>
{%endblock%}
UPDATE:
my base.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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<title>{%block title%}Medical Art{%endblock%}</title>
<!-- TEST OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO -->
{%block css%}
<!-- Bootstrap core CSS -->
<link type = 'text/css' href="{{STATIC_URL}}photo/css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<!--<link type = 'text/css' href="{{STATIC_URL}}photo/css/main.css" rel="stylesheet">-->
<link type = 'text/css' href="{{STATIC_URL}}photo/css/font-awesome.min.css" rel="stylesheet">
<link type = 'text/css' href="{{STATIC_URL}}photo/css/main-profile.css" rel="stylesheet">
<link type = 'text/css' href="{{STATIC_URL}}photo/css/car.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Raleway:400,300,700' rel='stylesheet' type='text/css'>
{%endblock%}
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<script src="{{STATIC_URL}}photo/js/angular.min.js"></script>
</head>
<body>
<div>
{%block navi%}
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'home'%}"><strong>Medical Art</strong></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
{% if user.is_authenticated %}
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Photo</li>
<li>Upload</li>
</ul>
<div class="col-sm-3 col-md-3">
<!--<form class="navbar-form navbar-left" action='/search/search_result/' method='post' role="search">-->
<form class="navbar-form" action='/search/search_result/' method='post' role="search">
<div class="input-group">
{% csrf_token %}
<input type="text" class="form-control" placeholder="Search" name="search" id='search_item'>
<div class="input-group-btn">
<button type="submit" class="btn btn-default" ><span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
</div>
<ul class="nav navbar-nav navbar-right">
<li><span style = "color:red; padding-left:5px;"> {{user.username}}!</span></li>
<li class="dropdown">
Picture Management<b class="caret"></b>
<ul class="dropdown-menu">
<li>
Buyer
<li class="divider"></li>
<li>> My Purchased Picture</li>
<li class="divider"></li>
</li>
<li>Contributor
<li class="divider"></li>
<li>> My Pending Pictures</li>
<li class="divider"></li>
<li>> My Approved Pictures</li>
<li class="divider"></li>
<li>> My earnings</li>
</li>
<li class="divider"></li>
<li>Log-Out</li>
</ul>
</li>
<li class="dropdown">
Account Mangement<b class="caret"></b>
<ul class="dropdown-menu">
<li>My Profile</li>
<li>Edit profile</li>
<li>Change password</li>
<li>Change email</li>
<li class="divider"></li>
<li>Log-Out</li>
</ul>
</li>
</ul>
</div>
{%else%}
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
<div class="col-sm-3 col-md-3">
</div>
<ul class="nav navbar-nav navbar-right">
<li>Sign In</li>
<li>Sign Up</span></li>
</ul>
</div>
{% endif %}<!-- /.navbar-collapse -->
</nav>
{%endblock%}
</div>
<div>{% block content%}
<div class="endless_page_template">
{% include 'photo/endless.html' %}
</div>
{% endblock%}
</div>
<br>
{%block footer%}
<div class="footer navbar-fixed-bottom" style="background-color:black; text-align:center">
<h4 style = "color:#ffffff">Powered by- Medical Art - Copyright 2014</h4>
</div>
{%block js%}
<script src="{{STATIC_URL}}photo/js/modernizr.custom.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="{{STATIC_URL}}photo/js/bootstrap.min.js"></script>
<script src="{{STATIC_URL}}photo/js/main.js"></script>
<script src="{{STATIC_URL}}photo/js/masonry.pkgd.min.js"></script>
<script src="{{STATIC_URL}}photo/js/imagesloaded.js"></script>
<script src="{{STATIC_URL}}photo/js/imageupload.js"></script>
<script src="{{STATIC_URL}}photo/js/classie.js"></script>
<script src="{{STATIC_URL}}photo/js/AnimOnScroll.js"></script>
<script src="{{STATIC_URL}}photo/js/jquery.cookie.js"></script>
<script src="{{STATIC_URL}}photo/js/endless.js" type="text/javascript" charset="utf-8"> </script>
<script>$.endlessPaginate({paginateOnScroll: true,paginateOnScrollMargin: 20});</script>
<script>
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
} );
</script>
<script>
$(document).ready(function() {
//Events that reset and restart the timer animation when the slides change
$("#transition-timer-carousel").on("slide.bs.carousel", function(event) {
//The animate class gets removed so that it jumps straight back to 0%
$(".transition-timer-carousel-progress-bar", this)
.removeClass("animate").css("width", "0%");
}).on("slid.bs.carousel", function(event) {
//The slide transition finished, so re-add the animate class so that
//the timer bar takes time to fill up
$(".transition-timer-carousel-progress-bar", this)
.addClass("animate").css("width", "100%");
});
//Kick off the initial slide animation when the document is ready
$(".transition-timer-carousel-progress-bar", "#transition-timer-carousel")
.css("width", "100%");
});
</script>
{%endblock%}
{%endblock%}
</body>
</html>
My guess is that your messages are piling up until you enter your upload page. Then they are displayed all at once.
Moving messages code to your base.html should solve this.
Edit
If you will place messages just before your content block it will solve the issue.
{% if messages %}
<div id="messages" style="margin-top:50px">
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
<button type="button" class="close" data-dismiss="alert"></button>
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
<div id="content">
{% block content%}
<div class="endless_page_template">
{% include 'photo/endless.html' %}
</div>
{% endblock%}
</div>