Add href in OnClick attribute in html form - javascript

I want to redirect to the python flask route home after showing the alert window.
<input type="submit" value="Register" onclick="call(); log();"></input>
Here are both functions.
<script>
function call()
{
window.alert("Congragulations! You Registerd Sucessfully ");
}
</script>
<script>
function log()
{
<a href="/home" > </a>
}
</script>

If I understood your project correctly, you want to forward the user after he has registered. At the same time, a message should appear that the process was successfully completed.
I think your javascript approach is not sufficient for this, since the data must first be sent from the client to the server so that the process is complete. Here the inputs should also be validated and will likely be processed or stored in some way.
I have written a small example for you, which accepts form data and checks it. If the verification is successful, the user is redirected and a message appears. To forward and display the message I use redirect and flash from the flask package.
Python Flask
import re
from flask import Flask
from flask import (
flash,
redirect,
render_template,
request,
session,
url_for
)
app = Flask(__name__)
app.secret_key = b'your secret here'
#app.route('/')
def home():
return render_template('index.html')
#app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
if username and re.match(r'^[a-z0-9\_\-]+$', username, re.IGNORECASE):
session['username'] = username
flash('Congragulations! You Registerd Sucessfully.')
return redirect(url_for('home'))
return render_template('register.html')
HTML (index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<ul style="list-style: none;">
<li>Register</li>
</ul>
</nav>
{% with messages = get_flashed_messages() -%}
{% if messages -%}
<ul class="flashes">
{% for message in messages -%}
<li>{{ message }}</li>
{% endfor -%}
</ul>
{% endif -%}
{% endwith -%}
<h1>Welcome {{ session.get('username', 'Guest') }}!</h1>
</body>
</html>
HTML (register.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<form method="post">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</div>
<input type="submit" value="Register" />
</form>
</body>
</html>

Related

How to grab the value from the drop-down menu using flask

I am trying to grab the value from the drop-down menu after clicking the submit button for which the UI looks like this :
The code for the above is as follows :
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
return render_template('feba.html', colours=colours)
if __name__ == "__main__":
app.run()
index.html is in the templates folder
<!DOCTYPE html>
<html lang="en">
<style>
body {text-align:center}
</style>
<head>
<meta charset="UTF-8">
</head>
<body>
<img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
<h1>KARDFINDER</h1>
<h2>json file generator for banks</h2>
<select name="colour" method="GET" action="/">
<option value="{{colours[0]}}" selected>{{colours[0]}}</option>
{% for colour in colours[1:] %}
<option value="{{colour}}">{{colour}}</option>
{% endfor %}
</select>
<input type= "submit" name="submitbutton" value ="Submit"></body>
</html>
logo_1.jpg is in the static folder
My main aim to post this question is to get a solution with the help of which I can grab the value from the drop-down menu after the submit button is clicked and I want that value stored in a variable in the app.py file
Please Help me with this.
below code works on me,
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
return render_template('feba.html', colours=colours)
#app.route('/dropdown', methods = ['POST'])
def dropp():
dropdownval = request.form.get('colour')
print(dropdownval)
return redirect("/", code=302)
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html lang="en">
<style>
body {text-align:center}
</style>
<head>
<meta charset="UTF-8">
</head>
<body>
<img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
<h1>KARDFINDER</h1>
<h2>json file generator for banks</h2>
<form method="POST" action="/dropdown">
<select name="colour">
<option value="{{colours[0]}}" selected>{{colours[0]}}</option>
{% for colour in colours[1:] %}
<option value="{{colour}}">{{colour}}</option>
{% endfor %}
</select>
<input type="submit" value ="Submit">
</form>
</body>
</html>
you should learn http requests, html forms and ajax
You could also just combine the index and drop down pages into one:
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET','POST'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
if request.method=='POST':
var = request.form['var']
return render_template('feba.html', colours=colours)
if __name__ == "__main__":
app.run()
This is a bit simpler. You can use the same html code as Mert Celik but change action="/dropdown" to action="/"

Why can I not change a html element with JS?

I'm trying to get a JS script to insert HMTL on a python flask server and it doesn't seem to want to run.
File Structure:
project
static
css
style.css
templates
demo.html
download.html
index.html
wrongLink.html
main.py
Here is the flask code that runs the webserver:
from flask import Flask, render_template, send_file
from flask import request, redirect
app = Flask(__name__)
#app.route('/')
def main():
return render_template('demo.html')
I also render some templates like this:
return render_template('download.html',
thumb=thumb, title=title, options=options, counter=counter)
I realised that I'm having trouble specifically with one piece of JS in the download.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link href="{{ url_for('static', filename='css/style.css') }}"
rel="stylesheet" type="text/css">
</head>
<body>
<div>
<form action="/getVideo" method="post">
<input type="text" name="Link" value="{{ Link }}">
<input type="submit" value="Convert">
</form>
<img src="{{ thumb }}" alt="Thumbnail" width="480" height="270">
<p>{{ title }}</P>
<p id="demo"></p>
<form id="options">
<input type="submit" value="Download">
</form>
</div>
<script type="text/javascript">
window.alert("JS works");
var i;
var options = JSON.parse{{options | tojson}};
for (i = 0; i < options.length; i++) {
out += '<input type="radio" value="' + options[i]["res"] += '"><br>';
}
document.getElementById("demo").innerHTML = "hi";
</script>
</body>
</html>
Neither the alert window or the element edit execute so I'm not sure what's happening there.

Getting MultiValueDictError in fetch POST data django

I am trying to fetch GET data receiving from an HTML form.
But it is giving me MultiValueDictError.
It is also saying
During handling of the above exception, another exception occurred:
My HTML code :
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<form action="home_redirect/fd" id="redirect" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" value={{user}} name="user">
<input type="submit">
</form>
<script>
document.getElementById("redirect").submit()
</script>
</body>
</html>
My views.py :
def home(request):
user = request.POST['user']
return render(request, 'main.html', {'login': user})
In you html i remove action and script. Like this:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<form id="redirect" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" value={{user}} name="user">
<input type="submit">
</form>
</body>
</html>
Here we checking the method is POST then redirect to your url.
def home(request):
user = request.POST
if request.method =="POST":
return redirect('home_redirect') # home_redirect is the redirected url
return render(request, 'afl_announcement/main.html', {'login': user})
In your <form> you specify:
<form action="home_redirect/fd" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" value={{user}} name="user">
<input type="submit">
</form>
so you make a POST request, and the data is encoded in the payload of the request. You access this data through request.POST:
def home(request):
user = request.POST['user']
return render(request, 'main.html', {'login': user})

Modal popup to delete object in django

I am using django generic DeleteView() for deleting object from my database. The deleteview is working fine. But I want a alert message before deleting the object.
I have a ListView for showing the objects list in a table. In that table i have a trash icon, when user presses the trash icon it redirects to delete url and deletes the object. But i dont want to go a different page for my deletion instead I want to stay on that list page and want a popup alert message if i want to delete the object. if i click the yes button it deletes the object staying on that page and refreshes the list table.
I have tried several codes for this.
<button action="{% url 'employee:employee-delete' employee.id %}" type="button" name="button" class="btn btn-dnager" onclick="document.getElementById('deleteEmployee').style.display='block'">
<span data-feather="trash"></span>
</button>
<div id="deleteEmployee" class="modal">
<span onclick="document.getElementById('deleteEmployee').style.display='none'" class="close" title="Close Modal">×</span>
<div class="modal-content">
<h1>Delete Account</h1>
<p>Are you sure you want to delete your account?</p>
</div>
{% block footer%}
{% include 'employee/employee_delete.html' %}
{% endblock footer %}
</div>
currently I have above code for popup message and trash icon. when the icon is clicked a modal opens.
employee_delete.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
</head>
<body>
{% block footer%}
<form id="deleteForm" action="" method="post">
{% csrf_token %}
<div class="clearfix">
<button type="button" onclick="document.getElementById('deleteEmployee').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" action="" onclick="document.getElementById('deleteForm').submit();" class="deletebtn">Delete</button>
</div>
</form>
{% endblock footer%}
</body>
</html>
above code is for my delete form. Everything is fine but when I click delete button nothing happens, doesnt delete the object and gives Method Not Allowed (POST) this error.
views.py:
class EmployeeDeleteView(DeleteView):
"""
Deletes a created employee
"""
template_name = 'employee/employee_delete.html'
context_object_name = 'employees'
model = Employee
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(Employee, id=id_)
def post(self, request, *args, **kwargs):
employee = self.get_object()
#print(employee.errors)
return render(request, 'employee/employee_delete.html', {'employee': employee})
def get_success_url(self):
return reverse('employee:employee-list')

Django, calendar widget doesn't work with ModelForm and Form Media

I found one blog. It explains how apply calendar widget with form media. It is what I exactly want to make. so I followed instructions.
But js and css files doesn't work in widget. I tried to figure out this problem. I spent quite much time by searching and reading stuffs. But I can't get what's wrong in my situation exactly. Well, It could be very easy question but I will appreciate if you can give me any hint to figure out this!
model.py
class Birthday(models.Model):
birthday = models.DateField(null=True)
views.py
def register_birthday(request):
if request.method == 'POST':
form = BirthdayForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success')
else:
form = BirthdayForm()
return render(request, 'sale/registerbirthday.html', {'form':form})
forms.py
class DateUIWidget(forms.TextInput):
def _media(self):
return forms.Media(css = {
"all": ("tiny-date-picker.css",)
},
js = ("tiny-date-picker.js", "date-init.js",))
media = property(_media)
class BirthdayForm(forms.ModelForm):
class Meta:
model = Birthday
fields = ('birthday',)
widgets = {
"birthday" : DateUIWidget(attrs={'class':'dateuiwidget', 'id':'id_birthday'}),
}
actually I wrote at first like below. but I changed to check if it works when I use media as a dynamic property.
class DateUIWidget(forms.TextInput):
class Media:
css = {
"all": ("tiny-date-picker.css",)
}
js = ("tiny-date-picker.js", "date-init.js",)
forms.py first
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{{ form.medai}}
I changed it because I read that I should read this when I changed.
As we have already seen, the string representation of a Media object is the HTML required to include the relevant files in the <head> block of your HTML page.
<html>
<head>
{{ form.media }}
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
under myapp/static/date-init.js
$(".dateuiwidget").each(function(){
return TinyDatePicker(this);
});
I copied two files(tiny-date-picker.js,tiny-date-picker.css) under myapp/static/.
I got two files from here
it shows widget in a form without error. I assume that somehow js, css file didn't apply to this widget.
html source code
<html>
<head>
<link href="/static/tiny-date-picker.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/static/tiny-date-picker.js"></script>
<script type="text/javascript" src="/static/date-init.js"></script>
</head>
<body>
<form action="." method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='VC8ahwDLBOsy4IlAzf1iIiukK7ZvTcGDQjL9RxywlauCOX3c8rG7DVJ1ClozHEEW' />
<p><label for="id_birthday">Birthday:</label> <input class="dateuiwidget" id="id_birthday" name="birthday" type="text" required /></p>
<input type="submit">
</form>
</body>
</html>

Categories

Resources