Page is opening but search is not working when i am using {% for i in kitty_list %} but in case of {% for i in kitty %} then NoReverseMatch error - django

In the below scenario, the page is opening but search functionality is not working when i am using {% for i in kitty_list %} in the template. However, when i am using {% for i in kitty %} then I get a NoReverseMatch error.
Url: path('kitty_view',views.kitty_view,name='kitty_view')
View: kitty_list = kitty_list.filter(status = status1)
kittys = kitty.objects.all()
ctx = {'kitty': kitty_list,'kitty_code':kittys}
return render(request, 'kitty/kitty_view.html', ctx)
This is the HTML page which is giving NoReverseMatch error when {% for i in kitty %} is used. When i am using {% for i in kitty_list %} then the page is rendering but the search button is not working.
template:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<form class="form-signin" action="{% url 'kitty_view' %}" method="get">
{% csrf_token %}
<div class="form-row">
<div class="mb-3">
<select class="custom-select center-block" name="code1" id="code1">
<option value="">Choose Kitty...</option>
{% for j in kitty_code %}
<option value="{{ j.code }}"> {{ j.code|add:' - '|add:j.name }} </option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="stat" id="stat" placeholder="Status">
<option value="">Choose Status...</option>
<option>A</option>
<option>I</option>
</select>
</div>
<div class="mb-3">
<button type="submit" class=" btn btn-info " role="button">Search</button>
</div>
</div>
</form>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Kitty Code</th>
<th scope="col">Name</th>
</tr>
</thead>
{% if kitty %}
{% for i in kitty_code %}
<tbody>
<tr>
<td>{{ i.id }} </td>
<td>{{ i.code }} </td>
<td>{{ i.name }} </td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
{% endblock %}

Inside the template file, you need to modify the below line. {% url 'kitty_view' %} to {% url '<app_name>:kitty_view' %}. If this would not work then, please give me an error in more detail.

Related

DJANGO - access form data in javascript in template

How can I access form data in javascript in template?
I have a bootstrap 4 tabbed interface.
Each tab renders a dynamic django form.
Each form has dynamic 'command' buttons.
All form field and button data is coming from a json file.
So something like this...
The command buttons are handled by ajax, which basically calls a url based on the button clicked.
All of the tab forms are rendered by a single template.
How can I access the form data (different for each tab) in the javascript function?
( In the js function, look at 'SAVE FORM DATA HERE' and 'PASS FORM DATA HERE' )
template
{% load static %}
<table class="" id="tabCmdTbl">
<div class="btn-group">
<tr>
{% for btn in btns %}
<td width="125px">
{% if btn.btnText != "" %}
{% if btn.btnText == "End" %}
{% comment %}
<!-- Handle the exit button, its an anchor, all the other tabs are ajax -->
{% endcomment %}
<a type="button" class="btn btn-sm btn-outline-secondary w-100" target="_blank" href="/frontOffice">End</a>
{% else %}
<button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="tabBtn('{{btn.btnCmd}}')">
{{ btn.btnText }}
</button>
{% endif %}
{% endif %}
</td>
{% endfor %}
</tr>
</div>
</table>
<div id="tabloading" style="height:50px">
<p><img src="{% static 'FhHRx.gif' %}" /> Please Wait</p>
</div>
<hr>
<table id="tabDataTbl" border="1px" style="background-color:rgb(225, 229, 238)" >
{% for field in form.visible_fields %}
{% ifchanged field.field.row %} {% comment %} if the row changed {% endcomment %}
{% if field.field.row != 1 %} </tr> {% endif %} {% comment %} unless its the first row, end the row {% endcomment %}
<tr> {% comment %} rowchanged, not first row, start new row {% endcomment %}
{% endifchanged %}
{% ifchanged field.field.col %}
{% if field.field.col != 1 %} </td> {% endif %}
<td style="padding:5px">
{% else %}
{% ifchanged field.field.row %}
{% if field.field.row != 1 %} <td style="padding:5px"> {% endif %}
{% endifchanged %}
{% endifchanged %}
{{ field.label }}</td><td> {{ field }} </td>
{% endfor %}
</table>
<script>
$('#tabloading').hide();
function tabBtn(datap) {
$('#tabloading').show();
// alert(datap);
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
if (datap.includes("Save")) {
------ SAVE FORM DATA HERE ------
alert('x')
}
$.ajax({url:datap, //url,
data: { provider_code: '{{form.provider_code.value}}',
patient_number: '{{form.patient_number.value}}',
account_number: '{{form.account_number.value}}',
insurance_number: '{{form.insurance_number.value}}',
------ PASS FORM DATA HERE ------
},
type:"POST",
success:function(tabdata){
// alert(tabdata);
$('#tabloading').hide();
$("#tab-content").html(tabdata);
}
});
}
</script>

How to display uploaded pdf file along with machine name and operation number based on select from dropdown

In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row.
This project is working fine but I want above validations.
Please anyone can help me out, this will be great for me. Please..
views.py:
def upload(request):
controlmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines})
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machinename', '')
operation_no = request.POST.get('operationname','')
choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no)
cmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine})
def index(request):
if request.method == 'POST':
form = ControlmachineForm(request.POST, request.FILES)
if form.is_valid():
model_instance = form.save()
model_instance.save()
else:
form = ControlmachineForm()
controlmachiness = Controlmachine.objects.all()
return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness})
upload.html:
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
view file
{% endfor %}
</td>
{% endfor %}
</tr>
control_uploadfile.html:
<html>
<head>
<title>Master File Upload</title>
</head>
<body>
<p><h1>Control File Upload</h1></p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button> <br><br>
</form>
</body>
</html>
control_show.html:
{% extends "master/control_base.html" %}
{% block title %}Control File{% endblock title %}
{% block content %}
<div class="col-md-12">
<div class="table-responsive">
<table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>ID</th>
<th>Machine Name</th>
<th>Operation Number</th>
<th>File</th>
<th>Delete</th>
</thead>
<tbody>
{% for control in controlmachines %}
<tr>
<td><input type="checkbox" class="checkthis" /></td>
<td>{{ control.id }}</td>
<td>{{ control.machine_name }}</td>
<td>{{ control.operation_no }}</td>
<td>{{ control.control_uploadfile }}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"></span></p></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock content %}
models.py:
class Controlmachine(models.Model):
machine_name = models.CharField(max_length=100)
operation_no = models.IntegerField()
control_uploadfile = models.FileField(upload_to='documents/')
class Meta:
db_table = "controlmachine"
forms.py:
class ControlForm(forms.ModelForm):
class Meta:
model = Controlmachine
fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }),
'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }),
'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }),
}
Do this: Here I have added if condition that is used to connect machine name to uploaded file.
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
{% if file == choice and file == choice %}
view file
{% endif %}
{% endfor %}
</td>
{% endfor %}
</tr>

how to update django databsae from html?

I want to only update the brand. So I want to see if I can get the post from the input.
print(request.POST.get('brand')) didn't print anything, but I can get print(request.POST.get('url')). Does anyone know why?
Here is my base.html code.
<form action="{% url 'script' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group w-75">
<input type="text" name="url" id="url" class="form-control">
</br>
<button type="submit" class="btn btn-success btn-lg btn-block">submit</button>
</div>
</br>
{% if alldata %}
<table class="table table-striped table-sm" id="">
<thead>
<tr>
<th>Price</th>
<th>Asin</th>
<th>Rank</th>
<th>Brand</th>
<th>CPU</th>
<th>Update</th>
</tr>
</thead>
<tbody>
{% for data in alldata %}
<tr>
<td>{{ data.price }}</td>
<td> {{ data.asin }} </td>
<td>{{ data.rank }}</td>
<td>
<div>
{{ data.brand }} <input type="text" name="brand" id="brand" value="{{data.brand}}">
<button type="submit">Update</button>
</div>
</td>
<td>cpu</td>
<td><button type="submit">Update</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</form>
To check All data in request.POST:
print(request.POST)
to print only one 'field'
print(request.POST['field'])

How to display multiple object data in html table in django template

I passed two queryset objects from views to template both have product data with its features now the main problem is how to show this both objects data simultaneously in HTML table?
table structure:
features1 | product1 features value 1 | product2 feature value 1
features2 | product1 features value 2 | product2 feature value 2
...
<tbody>
{% for a in product_data %}{% for b in product_data_2 %}
<tr class="row" style="line-height: 3">
{% if forloop.counter == forloop.parentloop.counter %}
{% for feature_data in a.product_features.all %}{% for feature_data_1 in b.product_features.all %}
<td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: left; font-weight: bold;">
{{ feature_data.feature.feature_name }}
</td>
<td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;">
{{ feature_data.product_feature_value }}
</td>
<td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;">
{{ feature_data_1.product_feature_value }}
</td>
{% endfor %}{% endfor %}
{% elif forloop.counter < forloop.parentloop.counter %}
something
{% elif forloop.parentloop.counter < forloop.counter %}
something
{% endif %}
</tr>
{% endfor %}{% endfor %}
</tbody>
please try to answer i tried but nothing work
Depending on your purpose you can use access by index and with:
{% with first_obj=product_data.0 %}
{% with second_obj=product_data.1 %}
...
{% for feature_data in first_obj.product_features.all %}
...
{% endfor %}
{% for feature_data in second_obj.product_features.all %}
...
{% endfor %}

display data in tables in django

I have narrowed down to the following , if anyone can help me pointing out how i can convert the following into table view that would be awesome. Following html is extended from the base.html
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}"
class="btn btn-primary">
Read More
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Need help with displaying data in gridview . I m new to all this. I m able to read and display the data on a page from mongodb but need to display in a table.
million $ question for me now is where should i be adjusting the following snippet in my code to give me gridview
<table>
<tr>
<th>Field 1</th>
<th>Field N</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.field1 }}</td>
...
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
My urls.py
from django.urls import path
from .import views
urlpatterns = [
path("",views.project_index, name = "project_index"),
path ("<project_detail>/",views.project_detail, name = "project_detail"),
#path("<int:pk>/", views.project_detail, name = "project_detail"),
]
My model.py
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100,primary_key=True)
desc = models.CharField(max_length=100)
urls = models.CharField(max_length=100)
#image = models.FilePathField(path="/img")
class Meta:
db_table = "spiderCollection1"
additional tables.py
import django_tables2 as tables
from .models import Project
import itertools
class ProjectTable(tables.Table):
class Meta:
model = Project
template_name = "django_tables2/bootstrap.html"
title = tables.Column("title")
desc = tables.Column("desc")
urls = tables.Column("urls")
following is views.py
from django_tables2 import SingleTableView
from django.shortcuts import render
from projects.models import Project
from projects.tables import ProjectTable
# Create your views here.
class ProjectListView(SingleTableView):
model = Project
table_class = ProjectTable
template_name = '/projects.html'
def project_index(request):
projects = Project.objects.all()
context = {
"projects":projects
}
return render (request, 'project_index.html',context)
#return render (request, 'project_index.html',locals())
def project_detail(request, pk):
#project = Project.objects.get(pk=pk)
project = Project.objects.all()
context = {
"project": project
#'personal_portfolio':project
}
return render(request, 'project_detail.html',context)
my main base.html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="{% url 'project_index' %}">Portfolio</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="{% url 'project_index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Blog</a>
</li>
</ul>
</div>
</div>
<!--<style>
h1 {
border: 5px solid red;
}
h2 {
border: 4px dotted blue;
}
div {
border: double;
}
</style>
-->
</nav>
<div class="container">
{% block page_content %}
{% endblock %}
</div>
<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>
and now project_index.html
{% extends "base.html" %}
{%load render_table from django_tables %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}"
class="btn btn-primary">
Read More
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
If the goal is to display a table without using the django-table2 package follow the first part of the answer. If the goal is to use django-table2 then jump to Part II:
Part I
Based on your colde, let us use the example snippet, and edit it in order to display your project data in an HTML table...
Starting with your project_index.html, we need create the skeleton of the html table using <table>, <thead>, <tbody> and <th> tags, and then to loop over the passed projects context variable and add entries to the table using the <td> tag. And because you are using the bootstrap framework, we will need the row and the column divss to display the table correctly.
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
<div class="col-md-4">
<table class="table table-striped table-hover">
<thead>
<th>#</th>
<th>title</th>
<th>description</th>
</thead>
<tbody>
{% for project in projects %}
<td><strong>{{ forloop.counter }} </strong></td>
<td><strong>{{ project.title}</strong></td>
<td>{{ project.description} Read More </td>
{% endfor %}
</tbody>
</table>
<div>
</div>
{% endblock %}
Make sure that your url.py points to the function project_index
To learn more check:
https://www.w3schools.com/html/html_tables.asp
https://getbootstrap.com/docs/4.4/content/tables
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#for
Part II
Django-table2 is a package that provides an app and middleware to generate html tables. In order to use it in your app make the following changes to your project_index.html:
{% extends "base.html" %}
{% load render_table from django_tables %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
<div class="col-md-4">
{% render_table projects %}
</div>
</div>
{% endblock %}
The code above will use the html template provided by django-table2 for rendering tables, defined in your class ProjectTable
class ProjectTable(tables.Table):
class Meta:
model = Project
template_name = "django_tables2/bootstrap.html"
...
If you want to use a custom rendering you will need to set the template_name of the ProjectTable to your custom.html:
class ProjectTable(tables.Table):
class Meta:
model = Project
template_name = "custom.html"
...
Now create custom.html and add the code that will actually iterate over the items of the projects context variable. Maybe something like this (copied from the django_tables2/semantic.html)... Make changes you want to this template.
{% load django_tables2 %}
{% load i18n %}
{% block table-wrapper %}
<div class="ui container table-container">
{% block table %}
<table {% render_attrs table.attrs class="ui celled table" %}>
{% block table.thead %}
{% if table.show_header %}
<thead {{ table.attrs.thead.as_html }}>
<tr>
{% for column in table.columns %}
<th {{ column.attrs.th.as_html }}>
{% if column.orderable %}
{{ column.header }}
{% else %}
{{ column.header }}
{% endif %}
</th>
{% endfor %}
</tr>
</thead>
{% endif %}
{% endblock table.thead %}
{% block table.tbody %}
<tbody {{ table.attrs.tbody.as_html }}>
{% for row in table.paginated_rows %}
{% block table.tbody.row %}
<tr {{ row.attrs.as_html }}>
{% for column, cell in row.items %}
<td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
{% endfor %}
</tr>
{% endblock table.tbody.row %}
{% empty %}
{% if table.empty_text %}
{% block table.tbody.empty_text %}
<tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
{% endblock table.tbody.empty_text %}
{% endif %}
{% endfor %}
</tbody>
{% endblock table.tbody %}
{% block table.tfoot %}
<tfoot {{ table.attrs.tfoot.as_html }}>
{% if table.has_footer %}
<tr>
{% for column in table.columns %}
<td {{ column.attrs.tf.as_html }}>{{ column.footer }}</td>
{% endfor %}
</tr>
{% endif %}
{% block pagination %}
{% if table.page and table.paginator.num_pages > 1 %}
<tr>
<th colspan="{{ table.columns|length }}">
<div class="ui right floated pagination menu">
{% if table.page.has_previous %}
{% block pagination.previous %}
<a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}" class="icon item">
<i class="left chevron icon"></i>
</a>
{% endblock pagination.previous %}
{% endif %}
{% if table.page.has_previous or table.page.has_next %}
{% block pagination.range %}
{% for p in table.page|table_page_range:table.paginator %}
{% if p == '...' %}
{{ p }}
{% else %}
<a href="{% querystring table.prefixed_page_field=p %}" class="item {% if p == table.page.number %}active{% endif %}">
{{ p }}
</a>
{% endif %}
{% endfor %}
{% endblock pagination.range %}
{% endif %}
{% if table.page.has_next %}
{% block pagination.next %}
<a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}" class="icon item">
<i class="right chevron icon"></i>
</a>
{% endblock pagination.next %}
{% endif %}
</div>
</th>
</tr>
{% endif %}
{% endblock pagination %}
</tfoot>
{% endblock table.tfoot %}
</table>
{% endblock table %}
</div>
{% endblock table-wrapper %}
Here make sure your urls.py includes:
...
path("projects/", ProjectListView.as_view())
...
for more refer to:
https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html
https://github.com/jieter/django-tables2/blob/master/django_tables2/templates/django_tables2/semantic.html
<div class="center">
<table class="table table-bordered " border="1">
<tr>
<th>Name</th>
<th>Game</th>
</tr>
{% for i in user_data %}
<tr>
<td>{{i.name}}</td>
<td>{{i.favorite_game}}</td>
</tr>
{% endfor %}</table>