Getting MultiValueDictError in fetch POST data django - javascript

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})

Related

Add href in OnClick attribute in html form

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>

How to hyperlink to html

Please help, I have provided below three files: application.py, ask.html, and link.html. In ask.html, I'm trying to ask the user to provide me a link. They will then be redirected to link.html where there is a button to take them to that link. But once the button is pressed, it doesn't take me to the link, comes out error 404 not found.
In application.py:
#app.route("/")
def ask():
return render_template("ask.html")
#app.route("/link")
def link():
weblink = request.args.get("weblink")
return render_template("link.html", weblink=weblink)
In ask.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ask</title>
</head>
<body>
<form action="/link">
<input placeholder="weblink here" name="weblink" type="text">
<input type="submit">
</form>
</body>
</html>
In link.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ask</title>
</head>
<body>
Go to Link
</body>
</html>
First, change:
<form action="/link">
to:
<form action="/link" method="post">
Then, in link():
#app.route("/link", methods = [“GET”, “POST”])
def link():
weblink = request.form.get("weblink")
...
Change
<form action="/link">
To
<form action = "{{url_for('link')}}" method = "post">
in application.py
change
#app.route('/link')
to
#app.route('/link', methods=['GET', 'POST'])
def link():
if request.method == 'POST':
weblink = request.form.get('weblink')
return render_template('link.html', weblink=weblink)

I want to Customise the Message Shown when Form Submitted in html. How to to do it?

I have built a Send Email from a Static HTML Form using Google Apps Mail. The problem is that when I submit the form, I see a confirmation message that it was sent like:
{"result":"success","data":"{\"firstname\":[\"Abhay\"]}"}
I want to remove that and besides that I want a clean text after a form submission e.g. "Thanks for submitting". Please correct my code to remove this output.
<!DOCTYPE HTML>
<html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title> contact form </title>
</head>
<body>
<div>
<form id="gform" method="POST"
action="https://script.google.com/macros/s/AKfycbwlSM9z9ELHa1-
X6C_srRrB0j7FUlGgevJw7w7M/exec" >
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.."
required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit" value="Submit"/>
</form>
<div style="display: none;" id="thankyou_message">
<h2> <em>Thanks</em>xfn</h2>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-
without-server/master/form-submission-handler.js"></script>
</body>
</html>
You can make an ajax request instead of submitting the from directly.
<form id="gform" onsubmit="return postMessage()">
In below
<script>
function PostMessage() {
var form = document.getElementById('gform')
fetch('"https://script.google.com/macros/s/AKfycbwlSM9z9ELHa1-
X6C_srRrB0j7FUlGgevJw7w7M/exec', {
method: 'POST',
body: new URLSearchParams(new FormData(a)).toString()
}).then(function(res){ return res.json(); })
.then(function(data){
if(data.result == "success") {
document.getElementById('thankyou_message').style.display = 'block';
}
});
return false;
}
</script>

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>

django form does not propagate data to server side

I have a template in my Django project which uses a combination of HTML and javascript. The template consists of two date and a text field. I am trying to send this across to the server side but with little success. Can someone please advise.
template:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker();
});
$(function() {
$( "#datepicker2" ).datepicker();
});
$(document).ready(
function()
{
$('#myform').ajaxForm({
beforeSubmit: function(arr, $form, options)
{
var field=$('#datepicker').val();
if (field!=null)
{
$('#my_form').ajaxStart( function()
{ alert('loading'); });
return true;
}
else
{
alert
return false;
}
},
success: function(response)
{
}
});
}
);
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
<p>Date: <input type="text" id="datepicker2"></p>
<p>Date: <input type="text" id="my_form"></p>
<form action="" method="post" id="myform">{% csrf_token %}
{{ myform.as_p }}
<input type="submit" name="submit" value="SUBMIT" id="submit" />
</form>
</body>
</html>
view:
def index(request):
template = 'my_site/index.html'
if request.is_ajax():
if request.method == 'POST':
post = request.POST
my_form = GraphForm(request.POST)
if my_form.is_valid():
new = my_form.save(commit=True)
response = { 'status':True, }
else:
response = {'status': str(my_form) }
json = simplejson.dumps(response, ensure_ascii=False)
return HttpResponse(json, content_type="application/json")
context = {'my_form':my_form}
return render_to_response(template, context, context_instance=RequestContext(request))
else:
form = GraphForm()
return render(request,"my_site/index.html", { 'form' : form } )
form:
class GraphForm(forms.Form):
my_form = forms.CharField(label = 'my_form',max_length=100)
start_date = forms.DateField(required=True)
end_date = forms.DateField(required=True)
Your form should look like this
<body>
<form action="" method="post" id="myform">{% csrf_token %}
{{ myform.as_p }}
<p>Date: <input type="text" id="datepicker"></p>
<p>Date: <input type="text" id="datepicker2"></p>
<p>Date: <input type="text" id="my_form"></p>
<input type="submit" name="submit" value="SUBMIT" id="submit" />
</form>
</body>
your input fields:
<p>Date: <input type="text" id="datepicker"></p>
<p>Date: <input type="text" id="datepicker2"></p>
<p>Date: <input type="text" id="my_form"></p>
is out of form so when the form is submitted these are not included in that. Also if you are using django form then you have no need to define fields again. You can call datepicker on your django fields. There id's will be id_start_date and id_end_date. you can apply datepicker on that like
$( "#id_start_date" ).datepicker(); and $( "#id_date_end" ).datepicker();
Your action URL is not set. Where will the POST data go?
<body>
<form action="." method="post" id="myform">
{% csrf_token %}
{{ myform.as_p }}
<p>Date: <input type="text" id="datepicker"></p>
<p>Date: <input type="text" id="datepicker2"></p>
<p>Date: <input type="text" id="my_form"></p>
<input type="submit" name="submit" value="SUBMIT" id="submit" />
</form>
</body>

Categories

Resources