How to delete a bootstrap card on button click? - html

I am new bootstrap & flask.
I am getting response from flask api of 20 rows & displaying using bootstrap card like this -
<div class="row">
{% for item in data %}
<div class="card" style="width: 25rem;">
{% if item[6] == '' or item[6] == ' ' %}
<img src='static/pic_not_avl.png' class="card-img-top" alt="pic"><i class="bi bi-person-circle"></i></img>
{% else %}
<img src='static/{{item[6]}}' class="card-img-top" alt="pic"><i class="bi bi-person-circle"></i></img>
{% endif %}
<div class="card-body">
<h5 class="card-title text-center">{{item[0]}}</h5>
<p class="card-text text-center">{{item[7]}}</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><strong>State : </strong>{{item[1]}}</li>
<li class="list-group-item"><strong>Salary : </strong>{{item[2]}}</li>
<li class="list-group-item"><strong>Grade : </strong>{{item[3]}}</li>
<li class="list-group-item"><strong>Room : </strong>{{item[4]}}</li>
<li class="list-group-item"><strong>Telnum : </strong>{{item[5]}}</li>
</ul>
<div class="card-body text-center">
<button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#updateModal">Update</button>
<!-- <button type="submit" class="btn btn-danger">Delete</button> -->
<a class="btn btn-danger" href="/deleteDatail?dname={{item[0]}}" role="button">Delete</a>
</div>
</div>
{% endfor %}
</div>
Now i want to delete a card (one data) on button click.
tried like this -
<a class="btn btn-danger" href="/deleteDatail?dname={{item[0]}}" role="button">Delete</a>
But I am getting error Method not allowed
How can I resolve this?

/deleteDatail?dname={{item[0]}} implies a GET call to your flask route. The error Method not allowed means your route does not support a GET. You have to do something like
#app.route("/deleteDetail/")
def deleteDetail():
dname = request.values.get("dname", None)
or you can do
#app.route("/deleteDetail/", methods = ["GET", "POST"])
def deleteDetail():
if request.method == 'POST':
dname = request.values.get("dname", None)

Related

Is there any way to edit django template?

In the last part of the code there exists a for loop which helps in constructing the boostrap crousel , but to make the website responsive i need to remove that forloop .
So is there any way achive responsiveness?
<div class="carousel-item active">
{% for i in products %}
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="card align-items-center" style="width: 18rem;">
<img src='/media/{{i.image}}' class="card-img-top mt-2" alt="...">
<div class="card-body">
<h5 id="productName{{i.id}}" class="card-title">{{i.product_name}}</h5>
<p id="productPrice{{i.id}}" class="card-text">₹ {{i.price}}</p>
<span id='button{{i.id}}'>
<div id='product{{i.id}}' class="btn btn-primary cart">Add to cart</div>
</span>
<a href="/shop/productView/{{i.id}}" id="quickView{{i.id}}"
class="btn btn-primary ml-3">Quick view</a>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %}
</div>
<div class="carousel-item">
{% endif %}
{% endfor %}
</div>
</div>
I don't have any solution to remove code from template (JS can probably make it work but I don't have any skills in it).
Instead, here's an idea to make your template a bit more responsive using Django.
You can get the user agent in your views:
views.py
user_agent = request.META['HTTP_USER_AGENT']
If you print it you'll get something like that:
>> print(user_agent)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/**.*.****.***
Safari/537.36
You can then set a list of keyword to check if the user agent is referring to a mobile device and assign a value to a variable in your context:
views.py
keywords = ['Mobile','Opera Mini','Android']
if any(word in user_agent for word in keywords):
context['is_mobile'] = True
else:
context['is_mobile'] = False
Finally set an if statement in your template:
your_page.html
{% if is_mobile == False %}
<div class="carousel-item active">
{% for i in products %}
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="card align-items-center" style="width: 18rem;">
<img src='/media/{{i.image}}' class="card-img-top mt-2" alt="...">
<div class="card-body">
<h5 id="productName{{i.id}}" class="card-title">{{i.product_name}}</h5>
<p id="productPrice{{i.id}}" class="card-text">₹ {{i.price}}</p>
<span id='button{{i.id}}'>
<div id='product{{i.id}}' class="btn btn-primary cart">Add to cart</div>
</span>
<a href="/shop/productView/{{i.id}}" id="quickView{{i.id}}"
class="btn btn-primary ml-3">Quick view</a>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %}
</div>
<div class="carousel-item">
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
You can find valuable informations that may help you as well on this topic.

Integrating Collapse functionality of Bootstrap with Django Backend. How to use for loops?

I'm struggling with a task in Django.
I have my database up and running with information on resellers. (name, address, region etc...)
and I want to implement Bootstrap collapse functionality where each card is a region. I was able to do that hardcoding the handling of the region. So in my base.html file I have:
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Region1
</button>
</h2>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
{% block content_Region1 %}
{% endblock %}
</div>
</div>
</div>
and in the block content of Region1 I use the home.html template as follow:
{% extends "base.html" %}
{% load static %}
{% block content_Veneto %}
<div class = "container">
{% for reseller in resellers %}
{% if reseller.region == "Veneto" %}
<div class="reseller_name">
<a href="{% url 'reseller_detail' reseller.id %}">
<p>{{reseller.name}} - {{reseller.cityname}}</p>
</a>
</div>
{% endif %}
{% endfor %}
</div>
What I would like to have is a list containing all the regions that are present in by database and then, in the base.html file I would like to do something like:
{% for region in list_regions %}
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
region
</button>
</h2>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
{% block content_region %}
{% endblock %}
</div>
</div>
</div>
{% endfor %}
so that I do not have to write the same code multiple times. Any idea?
The issue is that I'm not sure how to get the region_list out of the database.
Thanks and sorry for the long post!
Instead of blocks use the include template tag:
{% for region in list_regions %}
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
region
</button>
</h2>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
{% include "template_name.html" %}
</div>
</div>
</div>
{% endfor %}
Change template_name.html with your template which you want to include.

"NoReverseMatch" when in button that refers to a page with parameter in the url

I have this error:
"NoReverseMatch at /home/2/
Reverse for 'calendar_new' with arguments '('',)' not found. 1 pattern(s) tried: ['home/(?P<group_id>\d+)/calendar/new/$']"
in a button. In the ulr I have a "group_id" parameter which I need to use as a filter parameter. I don't understand what's wrong, because if I write the path manually in the url I don't have any problem and it opens the page correctly.
"group_id" is already a parameter present in the url.
In calendar.html:
<div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column">
<main class="inner cove border" role="main" style="background-color: white;">
<h1 class="cover-heading mt-3">Lista Calendari di {{ nome }}</h1>
<div class="mt-5">
<ul class="list-group">
{% for calendar in object_list %}
<li class="list-group-item list-group-item-action">{{ calendar.name }}</li>
{% empty %}
<li class="list-group-item">Non ci sono calendari disponibili per questo edificio</li>
{% endfor %}
</ul>
</div>
</main>
<!-- NUOVO CALENDARIO -->
<a class="btn btn-primary btn-lg active mt-5 mb-5" href="{% url 'cal:calendar_new'%}">Aggiungi Calendario</a>
</div>
In urls.py:
url(r'^home/(?P<group_id>\d+)/$', views.CalendarsOfGroupView.as_view(), name='group_view'),
url(r'^home/(?P<group_id>\d+)/calendar/new/$', views.calendar, name='calendar_new'),
Assuming you have group in context
<a class="btn btn-primary btn-lg active mt-5 mb-5" href="{% url 'cal:calendar_new' group.id %}">Aggiungi Calendario</a>
As your url requires group_id parameter to be matched

MultiValueDictKeyError at /search/, Why am I getting this error?

I am very beginner at django, And fall onto this error MultiValueDictKeyError, I've got this error earlier, And I solved it after adding the name tag to HTML file, but this time I am not able to figure it out. please help me fix this error
views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def main(request):
return render(request, "blog/index.html", {"Posts":Post.objects.all()})
def viewpost(request, pk):
return render(request, "blog/viewpost.html", {"Posts":Post.objects.get(id = pk)})
def search(request):
if request.method == "GET":
search = request.GET["search"]
for post in Post.objects.all():
if search in post.Title:
return render(request, "blog/search.html")
else:
return render(request, "blog/search.html", {
"message": "Not Found"
})
Index.html I am sorry this file is quite too big but its on the third block. I have commented out that block.
{% extends 'blog/layout.html' %}
{% load static %}
{% block body %}
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<h1 class="my-4">Page Heading
<small>Secondary Text</small>
</h1>
<!-- Blog Post -->
{% for post in Posts %}
<div class="card mb-4">
<img class="card-img-top" src="http://placehold.it/750x300" alt="Card image cap">
<div class="card-body">
<h2 class="card-title">{{ post.Title }}</h2>
<p class="card-text">{{ post.Description }}</p>
Read More →
</div>
<div class="card-footer text-muted">
Posted on {{ post.Date }} by
{{ post.Author }}
</div>
</div>
{% endfor %}
<!-- Pagination -->
<ul class="pagination justify-content-center mb-4">
<li class="page-item">
<a class="page-link" href="#">← Older</a>
</li>
<li class="page-item disabled">
<a class="page-link" href="#">Newer →</a>
</li>
</ul>
</div>
<!-- Sidebar Widgets Column -->
<div class="col-md-4">
**<!-- Search Widget -->
<div class="card my-4">
<h5 class="card-header">Search</h5>
<div class="card-body">
<form action="{% url 'search' %}" method="GET">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for..." name="search">
<span class="input-group-append">
<button class="btn btn-secondary" type="button" >Go!</button>
</span>
</div>
</form>**
</div>
</div>
<!-- Categories Widget -->
<div class="card my-4">
<h5 class="card-header">Categories</h5>
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled mb-0">
<li>
Web Design
</li>
<li>
HTML
</li>
<li>
Freebies
</li>
</ul>
</div>
<div class="col-lg-6">
<ul class="list-unstyled mb-0">
<li>
JavaScript
</li>
<li>
CSS
</li>
<li>
Tutorials
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- Side Widget -->
<div class="card my-4">
<h5 class="card-header">Side Widget</h5>
<div class="card-body">
You can put anything you want inside of these side widgets. They are easy to use, and feature the new Bootstrap 4 card containers!
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
{% endblock %}
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('',views.main, name = 'main'),
path('viewpost/<int:pk>/', views.viewpost, name = 'viewpost'),
path('search/', views.search, name = 'search'),
]
search.html
{% extends 'blog/layout.html' %}
{% load static %}
{% block body %}
<div class="card" style="width: 70vw; margin-left: auto; margin-right: auto; margin-top: 20px; ;">
<div class="card-body">
<h2 class="card-title">Search Results:</h2>
{% for post in posts %}
<h3 class="card-subtitle" style="margin-top: 30px;"><a href="#}" >{{ post.title }}</a></h3>
<p class="card-text" style="margin-left: 1px;">{{ post.description }}</p>
<hr>
{% endfor %}
</div>
</div>
{% endblock %}
You need to change your views and template like this.
Change button type tosubmit and you don't need csrf token in the GET request.
<form action="{% url 'search' %}" method="GET">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for..." name="search">
<span class="input-group-append">
<button class="btn btn-secondary" type="submit">Go</button>
</span>
</div>
</form>**
Now in the views
First get the search query parameter then filter all the posts containing that query using __icontains and return the results to the template in a context
def search(request):
search = request.GET.get ('search', '')
posts = Post.objects.filter(title__icontains=search)
return render(request, "blog/search.html", {'posts':posts})

loop trough foreignKey objects in HTML with UpdateView

I am in process of writing UpdateView Class form , I am using inlineformset_factory to get ForignKey objects and its works , my issue is that i would like to iterate all ForignKey with HTML for displaying all its objects , and i am don't really know how to achieve it , since all objects i refer it , form. as declared in my forms.py so my question is someone could help me with given view and form how to, in HTML should i iterate my ForignKey objects
Please advice
Thanks
my code is shown below
my views.py Update view
class TaskIdUpdateView(UpdateView):
taskidformset = inlineformset_factory(MainTask,ChildTask, fields=('task_description','task_info','task_complete',
'sub_task','task_precent_complete','task_due_date','task_assign'))
model = MainTask
template_name = "taskid_update.html"
form_class = TaskUpdateForm
forms.py class form
class TaskUpdateForm(ModelForm):
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
INPUTֹTIMEֹFORMATS = ['%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y',
'%Y/%m/%d', # '10/25/2006'
'%Y/%m/%d %H:%M',
'%m/%d/%y',
'%Y-%m-%d %H:%M:%S'] # '10/25/06'
#Main Task objects
task_title = forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'}))
global_task_info = forms.CharField(required=True, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'}))
due_date = forms.DateTimeField(required=False, input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
complete = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'type':'checkbox', 'class':'custom-control-input', 'id':'switchcomplete'}))
overall_precent_complete = forms.IntegerField(widget=(forms.NumberInput(attrs={'type':'range', 'min':'0', 'max':'100', 'value':'50', 'class':'range-slider__range', 'id':'PreRange'})))
task_location = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
#Child Tasks objects
task_description = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Sub Task Description'}))
task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Sub Task Description'}))
task_complete = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'type':'checkbox', 'class':'custom-control-input', 'id':'switchcomplete'}))
sub_task = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Sub Task Description'}))
task_precent_complete = forms.IntegerField(widget=(forms.NumberInput(attrs={'type':'range', 'min':'1', 'max':'100', 'value':'50', 'class':'slider', 'id':'myRange'})))
task_due_date = forms.DateTimeField(input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
class Meta:
model = MainTask
fields = ['task_title',
'global_task_info',
'due_date',
'global_task_assign',
'task_status',
'complete',
'overall_precent_complete',
'task_location',
'global_task_assign',
'task_status',]
taskidformset = inlineformset_factory(MainTask,ChildTask, fields=('task_description','task_info','task_complete',
'sub_task','task_precent_complete','task_due_date','task_assign'))
update.html
{% extends 'base.html'%}
{% load static from static %}
{% block content %}
<!--accordion css-->
<link href="{% static 'css/range.css' %}" rel="stylesheet">
<div class="conatainer">
<div class="col text-center py-5">
<form action="" class="" method="POST">
<h3 class="mt-3 text-left">Update Task </h3>
<hr>
<p class="text-muted text-left">Update Itom task</p>
{% csrf_token %}
{% if form.errors %}
</form>
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
<div class="input-group mt-3 mb-3 mr-auto">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-book-medical"></i></span>
</div>
{{ form.task_title}}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pen"></i></span>
</div>
{{form.global_task_info}}
</div>
<!---date time picker-->
<h6 class="text-left">Task Due Date</h6>
<div class="input-group date mb-3 col-3">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
{{ form.due_date }}
</div>
<!--end of date time picker-->
<!---Task Location-->
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-map-marked-alt"></i></div>
{{form.task_location}}
</div>
</div>
<!--End Of Task Location-->
<!---user assign-->
<h6 class="text-left">Assign Task to IT member</h6>
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user-tie"></i></div>
{{form.global_task_assign}}
</div>
</div>
<!--End Of User Assign-->
<h6 class="text-left">Set Task Status</h6>
<div class="input-group mb-3 mt-3 col-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="far fa-caret-square-right"></i></div>
</div>
{{form.task_status}}
</div>
<div class="range-slider mb-4">
<h6 class="text-left">Set Task Global Progress</h6>
{{form.overall_precent_complete}}
<span class="range-slider__value">0</span>
</div>
<h4 class="mt-3 text-left">SubTask Section </h4>
<hr>
<!---subtask section-->
<div id="accordion">
{{formset.task_description }}
<div class="card">
<div class="card-header text-left bg-secondary">
<a class="card-link" data-toggle="collapse" href="#collapseOne">
Collapsible Group Item #1
</a>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
</div>
</div>
</div>
</div>
<!---End subtask section-->
<div class="col text-left">
<button type="submit" value="Save" class="btn btn-primary btn-lg text-white mt-2"><span><i class="fas fa-database"></i></span> Create Task</button>
</div>
</div>
</div>
{% endblock content %}