I just created a django form using this following documentation:https://docs.djangoproject.com/en/1.8/topics/forms/
My Forms.py is similar to this:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
My Html template is similar to this (from django doc):
<dialog id="addForm">
<form action="{% url "listing" %}" method="post" >
{% csrf_token %}
{{ form }}
<input id="task_submit" type="submit" value="Submit"/>
</form>
</dialog>
<button onlick="PopUp()">Add Listing </button>
<script>
function PopUp(){
document.getElementByID("addForm").showModal();
}
</script>
However, I want my form to be a pop up dialogue when a user clicks on a button called "add tasks". I do not want the form to show until the user clicks a button called "add tasks". I have not been able to find any methods so far to do so while using Django Forms.
Question: How do I implement a pop up dialogue to display my current django form when a user clicks on a button?
Found the solution I was looking for here:
http://blog.raventools.com/create-a-modal-dialog-using-css-and-javascript/
Related
I have a form like below. if "Cancel Request" is clicked in the form, "delete__product" form element will be destroy. my problem here is that HTMX cannot work without (I hope not) a process like hx-post-get.... is there a solution for this?
<form method="post" id="delete__product">
{% csrf_token %}
<p>Are you sure you want to delete ""?</p>
<button href="javascript:void(1)" hx-trigger="click" hx-target="#delete__product">
Cancel Request
</button>
<button hx-post="{% url 'catalog:DeleteProduct' product.pk %}" hx-target="#delete__product">
Delete
</button>
</form>
Currently working on a Django project where I am stuck in a situation and the scenario is something like that I have two forms in my abc.html page, one is used for input file and second is used to run python script internally. But the issue is even if I don't input the file the submit button "run python script" start's working without submitting a file. Here I want to create a check that submit button "run python script" will run only at one condition when file will submitted otherwise button will disable. It will active only at one condition when user will input the file.
I am sharing the details:
abc.html:
<!--form to input file -->
<form method="post" enctype="multipart/form-data" name="myform">
{% csrf_token %}
<input type="file" id="file" name="doc" class="inputfile" onchange="document.myform.submit()"> </form>
<-- end of input file-->
<!-- form to run python script -->
<form action = "/results/" method="post" id="subform">
{% csrf_token %}
<input type="submit" id="btnSubmit" name="doc" value="run python script" class="btn btn-warning btn-sm" />
</form>
<-- end of form running python script -->
views.py:
def compliance_check(request): #function to upload file
global uploaded_file
if request.method == 'POST':
uploaded_file = request.FILES['doc']
print(uploaded_file.name)
print(uploaded_file.size)
fs = FileSystemStorage()
fs.save(uploaded_file.name, uploaded_file)
messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully")
return render(request, 'enroll/abc.html')
def results(request): #function to run python script
user_id = request.session['user_id']
hash_id, id_exists = compliance(user_id)
request.session['hash_id'] = hash_id
if id_exists:
messages.info(request, "This File has already been analyzed")
return redirect(tables_view)
I have tried multiple ways to create a check but not succeed yet. I hope that everyone will understand the question and the scenario is simple that there should be a check before clicking on run script button that please select the file first. The button should run only at one condition if user upload file.
I wrote an HTML template to send an email using Flask. In the HTML script, I have a form that has a "send" button and once it's clicked, it triggers an email in Flask.
HTML Script
<form class="form-container" action="{{ url_for('send_email') }}">
<div class="form-group">
<label for="to-address">To </label>
<input id= "to-address" name="to-address" type="email"
placeholder="sample#email.com" class="form-input">
</div>
<div class="form-group">
<label for="title">Title</label>
<input id= "email-title" name="email-title" type="text" placeholder="Title"
class="form-input">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id= "email-body" name="email-body" placeholder="Send Message" class="form-
text-area"></textarea>
</div>
<button id="email-send-btn" type ="submit" class="btn btn-primary"> Send </button>
</form>
FLASK
#application.route('/send_email')
def send_email():
to_address = request.args.get('to-address')
subject = request.args.get('email-title')
text = request.args.get('email-body')
msg= Message(
subject,
sender="abc#email.com",
recipients=to_address,
)
msg.html = render_template("email.html", text=text)
mail.send(msg)
return("success")
The email itself is working well but I have an issue with redirecting the page after clicking the "Send" button. Once I click on the Send button, whose id="email-send-btn", I want to stay in the current page, probably showing a notification popup to indicate the email has been sent successfully. I put return('success)` in the last line of my Flask script, because I had to return something to avoid a blank page.
I tried this following to stay in the same page after hitting the Send button. It allows me to stay in the same page, but also blocks the action completely and doesn't send any email. Is there any way to stay in the same page after clicking the send button without blocking the action of sending email?
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return true;
});
});
Historically returning false from a submit handler prevented form submission without needing to call submit event object methods such as preventDefault and/or stopPropagation
With careful reading you may be able to infer that jQuery documentation says the same thing:
If you'd like to prevent forms from being submitted unless a flag variable is set ... [return the value of the flag from the submit handler added using the jQuery .submit(handler) syntax]
means that if the flag variable is set true, form submission is not prevented.
Hence return false instead of true to stay on the page, letting jQuery handle cross browser compatibility issues.
You can use render template + flash message.
https://flask.palletsprojects.com/en/2.2.x/tutorial/templates/
https://flask.palletsprojects.com/en/2.2.x/patterns/flashing/
from flask import render_template, flash
... your code here ...
flash('Email has been sent successfully.')
return render_template('yourtemplate.html')
And in your template you have to put this code, like in documentation:
% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
Of course you can use any HTML tag instead of unordered list with items.
Right now you just use another callback that does something when the form submits but you don't block the standard submitting. In order to achieve that you should managed the event defining that he should "prevent default" actions.
$form.submit(function(e){ //< add here "e" parameter
e.preventDefault(); //< add this
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false; //< change this
});
I am using the following code to 'select all' and 'clear' the checkboxes of my django form in the django template.
<form id="inv_form" method="post" action="{% url 'inventory:create_inventory' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Create Inventory" />
Cancel
<button onclick="select_all()">Select All</button>
<button onclick="deselect_all()">Clear</button>
</form>
function select_all() {
$('input[type=checkbox]').prop('checked', true);
}
function deselect_all() {
$('input[type=checkbox]').prop('checked', false);
}
The problem is the form is getting automatically posted if I press 'check all' button. Same in case of 'clear' button.
So I tried adding preventDefault() to my form submit event.
$("#inv_form").submit(function(event){
event.preventDefault();
});
Now the original problem has been solved, but the submit doesn't works even on clicking at all.
How to make the check all button work without auto posting the django form
I found a simpler solution here.
** stack overflow: disable auto-submit on button click **
It explains that by html5 default a button is type="submit". The solution to the above problem is explained below.
<button type="button" onclick="select_all()">Select All</button>
You probably hate to unbind submit, then you can submit the form.
$('some_form').unbind('submit').submit()
This approach should cancel prevenDefault so you can submit the form.
tml:
<div id="report-liveonly">
<form action="." id="status" method="POST">{% csrf_token %}
<p>{{SearchKeywordForm.status}}Only show LIVE reports</p>
</form>
</div>
I am trying to submit the searchform on checkbox click.It is not working. Onclick also not happening,i checked with alert message.
The total function is to show the live report,if Only show LIVE reports checkbox is checked.
Need help
I found the solution,
class SearchKeyword(Form):
search_keyword = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keyword Search','class':'keyword-search'}))
status = forms.BooleanField(widget=forms.CheckboxInput(attrs={'onclick':'this.form.submit();'}),required=False, label="Status")