Broken modal in flask - html

on my page I do cms for individual chapters that I have in the menu and on the page and I want new ones to be added and those that already exist so that they can be edited. I'm just doing it via jquery and bootstrap modal dialog but it doesn't want to work every time I click edit so my modal dialog doesn't appear and I get a 404 error. When adding chapters, nothing appears there at all, no error, no message or nothing in debug mode. I need help with that. Thank you in advance for your help.
PS: Deleting chapters works for me
HTML Code (updated):
{% extends "base.html" %} {% block content %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
{%if session["group"] == "Admin"%}
<div class="container">
<div class="row">
<div class="col md-12">
<h2>Kapitoly</h2>
<button type="button" class="btn btn-success pull-right" data-toggle="modal" data-target="#myModal">Přidat kapitolu</button>
<br>
<br>
{%with messages = get_flashed_messages()%}
{%if messages%}
{% for message in messages %}
<div class="alert alert-success alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label ="close">
<span aria-hidden="true">×</span>
</button>
{{message}}
</div>
{%endfor%}
{%endif%}
{%endwith%}
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Ročník</th>
<th>Název</th>
<th>Akce</th>
</tr>
{% for row in chapters %}
<tr>
<td>{{row.0}}</td>
<td>{{row.1}}</td>
<td>{{row.2}}</td>
<td>
<a type="button" class="btn btn-primary" data-toggle="modal" data-target="#modaledit{{row.0}}">Upravit</a>
Smazat
</td>
</tr>
<div id="modaledit{{row.0}}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upravit kapitolu</h4>
</div>
<div class="modal-body">
<form action="{{ url_for('update') }}" method="POST">
<div class="form-group">
<label>Ročník:</label>
<input type="hidden" name="id" value="{{row.0}}">
<input type="text" class="form-control" name="year" value="{{row.1}}">
</div>
<div class="form-group">
<label>Název:</label>
<input type="text" class="form-control" name="title" value="{{row.2}}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="sbumit">Upravit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<div class="back">
Vrátit se zpátky.
</div>
</div>
</div>
</div>
{% endfor %}
</table>
</div>
</div>
<!-- Modal -->
<div id="mymodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Vytvořit kapitolu</h4>
</div>
<div class="modal-body">
<form action = "/add_chapter" method="POST">
<div class="form-group">
<label>Ročník:</label>
<input type="text" class="form-control" name="year" required="1">
</div>
<div class="form-group">
<label>Název:</label>
<input type="text" class="form-control" name="title" required="1">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Vytvořit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{%endif%}
Flask code (updated):
#app.route("/manager_chapter")
#isLoggedIn
def manager_chapter():
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM chapters")
data = cur.fetchall()
cur.close()
return render_template('manager_chapter.html', chapters=data, id_data=id)
#app.route("/add_chapter", methods=["POST"])
#isLoggedIn
def add_chapter():
if request.method == "POST":
flash("Kapitola je uspěšně přidaná.")
year = request.form['name']
title = request.form['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO chapters (year, title) VALUES (%s, %s)", (year, title))
mysql.connection.commit()
return render_template('manager_chapter.html')
#app.route('/update_chapter/<string:id_data>', methods=['POST','GET'])
#isLoggedIn
def update(id_data):
if request.method == 'POST':
id_data = request.form['id']
year = request.form['year']
title = request.form['title']
cur = mysql.connection.cursor()
cur.execute("""
UPDATE chapters
SET year=%s, title=%s
WHERE id=%s
""", (year, title, id_data))
flash("Kapitola je uspěšně upravená.")
mysql.connection.commit()
return redirect(url_for('manager_chapter'))
#app.route('/delete_chapter/<string:id_data>', methods=['GET'])
def delete(id_data):
flash("Kapitola je uspěšně smazána.")
cur = mysql.connection.cursor()
cur.execute("DELETE FROM `chapters` WHERE id=%s", (id_data,))
mysql.connection.commit()
return render_template('manager_chapter.html')
Example 404 error after clicking edit in one of the chapters:

Next time, please translate your source code before posting it, if you are posting to English speakers. Based on your comments, I'm going to assume your edit button is this one
Upravit
You have both an href and data-target attribute. The latter is for the modal dialog. I don't believe you can have both and have them point to different urls. According to [bootstrap][1] documentation, you should use the href link and its value should be the id of your modal target. So I think your code should be
Upravit
or
<a type="button" class="btn btn-primary" data-toggle="modal" data-target="#modaledit{{row.0}}">Upravit</a>
If we assume your modal is not being triggered because it is being seen as a straight hyperlink and so the url in the href is being triggered, it opens up a second problem. Your flask route for that url has code only for a POST. You need to add code for the GET bit. In addition, your route has a variable for id_data but that variable is not part of your route i.e. you should have
#app.route('/update_chapter/<string:id_data>', methods=['POST','GET'])
#isLoggedIn
def update(id_data):
UPDATES - Based on comments by OP
Your button code now calls the modal.
The modal has a form and the form has a hidden field for the chapter id. Based on this, your route should now be
#app.route('/update_chapter', methods=['POST'])
#isLoggedIn
def update():
if request.method == 'POST':
id_data = request.values.get("id", None)
# I prefer to use request.values.get so that I don't
# have to worry about if my method is a POST or GET
[1]: https://getbootstrap.com/docs/4.1/components/modal/

Related

How to prevent Modal from hiding when submitting if there is an error in the form?

when I click the Add User button the modal is hiding even if the form has errors. If I reopen the modal the error messaged are there, I need to show the error messaged and not close the modal if the there is an error message.
I think I can use the {{form.errors}} to verify if there is an error message. But I don’t know how?
<div class="card-body d-flex justify-content-between">
<h4 class="box-title">Users</h4>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#add_user" data-whatever="" >Add a user</button>
<div class="modal fade" id="add_user" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="h3 mb-3 fw-normal text-center" id="exampleModalLabel">Create Account</h1>
</div>
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="form-floating">
{{ form.username }}
<span class="text-danger">{{ form.errors.username }}</span>
</div>
<div class="form-floating">
{{ form.email }}
<span class="text-danger">{{ form.errors.email }}</span>
</div>
<div class="form-floating">
{{ form.password1 }}
<span class="text-danger">{{ form.errors.password1 }}</span>
</div>
<div class="form-floating">
{{ form.password2 }}
<span class="text-danger ">{{ form.errors.password2 }}</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class=" btn btn-primary" type="submit" >Add User</button>
</div>
</div>
</form>
</div>
</div>
</div>
I used to the Django form for validation and error messages.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username','class': 'form-control mb-3',}))
email = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email','class': 'form-control mb-3',}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password','class': 'form-control mb-3',}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password','class': 'form-control mb-3',}))
my function in views.py looks like this
#login_required(login_url= 'login')
#staff_member_required(login_url='home')
def dashboard(request):
User = get_user_model()
users = User.objects.all()
form = CustomUserCreationForm()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('dashboard')
context = {
'users' : users,
'form': form
}
return render(request, 'dashboard.html', context)
is there any solutions for this?
Simplest way to do it is to add if statement in modal div class:
<div class="modal fade {% if form.errors %}show{% endif %}" ...>
Sorry this is wrong! I did it withouth thinking. Sorry.
Correct answer:
Add this to your template (on bottom or top):
{% if form.errors %}
<script>
$(document).on('ready', function(){
$('#add_user').modal('show');
});
</script>
{% endif %}
This will invoke show on your modal at page load.
Another way to do it is somekind of validation with ajax or maby htmx(without reloading page)

HTML form inside modal POST is working but not writing to database Django

I am new to the Django framework. I have developed a page with a table and Add button. When the Add button clicks, it will open the form inside a modal. Here the problem is when I first tried, the data in the form filled to the table as expected. But after, when I did the same thing, it gave 200 for POST, and nothing filled in the table. And no errors showing.
This is my sample code.
<!--modal for Create record-->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<form method="POST" class="modal-dialog modal-md" action=".">{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"><strong>Add Company</strong></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-group row">
<label for="companyName" class="col-12 col-md-4"><strong>Company Name</strong></label>
<div class="col-12 col-md-10">
<input type="text" class="form-control" id="companyName" name="companyName" placeholder="Company Name">
</div>
</div>
<div class="form-group row">
<label for="address" class="col-12 col-md-4"><strong>Address</strong></label>
<div class="col-12 col-md-10">
<input type="text" class="form-control" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary">Reset</button>
<button type="submit" class="btn btn-primary">Add</button>
<button type="close" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
And here is the code in views.py
def addcompany(request):
if request.method == 'POST':
if request.POST.get('companyName') and request.POST.get('address'):
saverecord = company()
saverecord.CompanyName = request.POST.get('company')
saverecord.Address = request.POST.get('address')
saverecord.save()
return render(request, 'newapp/companypage.html')
else:
return render(request, 'newapp/companypage.html')
I would be very grateful if anyone can help me to solve this problem. Thank you.
I think the error in the company name you should write it like this:
saverecord.CompanyName = request.POST.get('companyName')
You can also read more about how to build forms from models with Django

Cannot retrieve data from my flask CRUD application from mysql table even though its getting inserted without any error

Here's the python snippet
#app.route('/oxygenadmin')
#is_logged_in
def oxygenadmin():
cur=mysql.connection.cursor()
cur.execute("SELECT * FROM oxygen")
data =cur.fetchall()
cur.close()
return render_template('oxygenadmin.html', oxygen=data)
#app.route('/insert', methods=['POST'])
#is_logged_in
def insert():
if request.method == 'POST':
name = request.form['name']
contact = request.form['contact']
email = request.form['email']
place = request.form['place']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO oxygen(name, contact, email, place) VALUES (%s, %s, %s, %s)",(name,contact,email,place))
mysql.connection.commit()
flash("Data inserted successfully", 'success')
return redirect (url_for('oxygenadmin'))
return render_template ('oxygenadmin.html')
And here's the html snippet
<div class="row">
<div class="col md-12">
<h2> Oxygen Details <button type="button" class="btn btn-success pull-right" data-toggle="modal" data-target="#mymodal">Enter New Data</button> </h2>
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact No.</th>
<th>Email</th>
<th>Place</th>
<th>Action</th>
</tr>
{% for row in oxygen %}
<tr>
<td>{{row.0}}</td>
<td>{{row.1}}</td>
<td>{{row.2}}</td>
<td>{{row.3}}</td>
<td>{{row.4}}</td>
<td>
Edit
Delete
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
and...
<div id="mymodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please insert data!</h4>
</div>
<div class="modal-body">
<form action="{{url_for('insert')}}" method="POST">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" name="name" required='1'>
</div>
<div class="form-group">
<label>Contact No. :</label>
<input type="text" class="form-control" name="contact" required='1'>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Place</label>
<input type="text" class="form-control" name="place" required='1'>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Insert Data</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I somehow just cant get it to appear on my page
Here's how it looks
in the website itself
But it's getting inserted in the actual database though
Didnt paste the entire picture because there are some personal details
The table name is oxygen, I probably think it's doing something with the name itself , I just cant get it
Changing this...
{% for row in oxygen %}
<tr>
<td>{{row.0}}</td>
<td>{{row.1}}</td>
<td>{{row.2}}</td>
<td>{{row.3}}</td>
<td>{{row.4}}</td>
<td>
Edit
Delete
</td>
</tr>
{% endfor %}
to
{% for row in oxygen %}
<tr>
<td>{{row["id"]}}</td>
<td>{{row["name"]}}</td>
<td>{{row["contact"]}}</td>
<td>{{row["email"]}}</td>
<td>{{row["place"]}}</td>
<td>
Edit
Delete
</td>
</tr>
{% endfor %}
solves the issue

How to catch the displayed image ID in Laravel

I'm displaying a images from the database and i need to catch the image id from the controller .I'm trying to save image ID to Database
This is the image tag with contain image id
What we need to do is : When the user click the one of image and submit need to catch that selected id from the controller
$kudos->receiveuserid = $request->get('categories');
$kudos->imageid = 'how can i get image ID'
Try something like this and customize according to your requirement
#foreach($categories as $category)
<div>
<img src="{{$category->image}}" class="imgRating">
<input type="radio" value="{{$category->id}}" class="imgId" name="imageid">
</div>
#endforeach
Now in write a little jQuery
$(".imgRating").click(function(){
$(this).parent().find(".imgId").prop( "checked", true );
});
Finally, add CSS
.imgId{
display:none !important;
}
Now in your controller you will get the selected image id by $request->imageid
try this it should work. the idea here is that when you click on the image, the javascript function gets the id and assign it to a modal form then you submit. you can modify it to suit your preference.
<!-- modal to get image id store it in hidden field-->
<div id="imgModal" class="modal fade" >
<div class="modal-dialog box box-default" role="document" style="color:black;font-size:12.5px;">
<div class="modal-content">
<div class="modal-header">
<p class="modal-title">Image Form</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form class="form-horizontal" action="{{ url('img/addid/') }}" method="post" role="form">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group" style="margin: 0 10px;">
<input type="hidden" class="form-control" id="imgid" name="imgid" value="">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary btn-xs">Submit</button>
<button type="button" class="btn btn-danger btn-xs" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<!-- display image code-->
<div class="col-sm-3">
<div class="form-group">
#foreach($category as $category)
<a onclick="imgfunc('{{ $category->id}}')"><img class="boxicon" src="{{ asset('kudosupload/badges/'. $category->image)}}" name="img" ></a>
<br>
#endforeach
</div>
</div>
<!-- javascript to get image id when click on image-->
<script type="text/javascript">
function imgfunc(r)
{
document.getElementById('imgid').value = r;
$("#imgModal").modal('show')
}
</script>
//controller to get input and store in database
public function saveImage(Request $request){
$this->validate($request, [
'imgid' => 'required|string',
]);
$imgid=$request->input('imgid');
$datasave=DB::table('imgtable')->insert([
'id'=>imgid,
]);
return redirect('url')->with('message','Image saved!');
}
//route
Route::post('img/addid','controller#saveImage');

Input button in modal not submitting external form

I have created an inline formset with Django. Once the form is filled out and the user clicks Submit I have coded in a Bootstrap modal that pops up a reminder. The footer of the modal contains an HTML input so the external form can be submitted from the modal.
The problem I am having is that the submit buttons does not submit the form so it can be saved to the database and emailed. Is there a way do accomplish this using a modal?
Template:
{% extends "reports/base.html" %}
{% load static %}
{% block body_block %}
<font color="green">
<h4 >Company</h4>
</font>
<h3>Please enter your nightly reports in the form below.</h3>
<br>
<p>If you would like to add a new line to a category, select <font color="blue">add New Line Item</font> under each category.
When finished, click on <strong><font color="gray">Save and Email to Corporate</font></strong> button at the bottom of the form.</h4>
Once the form is sent, the form will refresh with the information you have entered. If you notice an error after you sent the form, edit the error and click the <strong><font color="gray">Save and Email to Corporate</font></strong> button again to update and resend.</p>
<br>
<h5>If you would like a blank form, click <font color="green"> here</font>.</h5>
<br>
<br>
<div class="container-fluid">
<form class="form-inline" action="" method="post">
{% csrf_token %}
{{ form }}
<table class="table">
{{ formset_new.management_form }}
<div>
<br><h4><strong>New</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_new formset_class_name='new' prefix="new" %}
</div>
</table>
<table class="table">
{{ formset_renewal.management_form }}
<div>
<br><h4><strong>Renewals</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_renewal formset_class_name='renewal' prefix="renewal" %}
</div>
</table>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<br>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"><strong>Submit</strong></button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Before You Submit!!</h4>
</div>
<div class="modal-body">
<p>Please review and make sure that all line items are correct and that the <strong>"Check if No New Items"</strong> is checked if there are no new items for that catagory. If all is correct, please select the <strong>Save and Email</strong> button.</p>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Save and Email to Corporate">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
After researching the HTML input element, I found that you can use the id attribute to id the <form> element and call the id using the form attribute in the <input> element that is coded in the Bootstrap Modal. The relevant updated code is below.
<div class="container-fluid">
<form id="formset" class="form-inline" action="" method="post"> <!--added id="formset" to the form element-->
{% csrf_token %}
{{ form }}
<table class="table">
{{ formset_new.management_form }}
<div>
<br><h4><strong>New</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_new formset_class_name='new' prefix="new" %}
</div>
</table>
<table class="table">
{{ formset_renewal.management_form }}
<div>
<br><h4><strong>Renewals</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_renewal formset_class_name='renewal' prefix="renewal" %}
</div>
</table>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<br>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"><strong>Submit</strong></button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Before You Submit!!</h4>
</div>
<div class="modal-body">
<p>Please review and make sure that all line items are correct and that the <strong>"Check if No New Items"</strong> is checked if there are no new items for that catagory. If all is correct, please select the <strong>Save and Email</strong> button.</p>
</div>
<div class="modal-footer">
<input type="submit" form="formset" class="btn btn-primary" value="Save and Email to Corporate"><!--added form id, form="formset" , to input element-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Hopefully this will help others who use SO as a research tool.