Get Form values in Python using Django framework - python

My question here is without using Model or forms.Form can we get form values on submit using Django request object.
Here is small example to explain problem.
HTML Code :
<form action="/login/" method="post">
{% csrf_token %}
<input type="text" id="USERNAME" class="text" value="USERNAME" >
<input type="password" id="Password" value="Password" >
<div class="submit">
<input type="submit" onclick="myFunction()" value="LOGIN">
</div>
<p>Forgot Password ?</p>
</form>
views.py Code :
def dologin(request):
print('i am in do login')
print(request.method)
print(request.POST)
for key, value in request.POST.iteritems():
print(key , value)
return render(request,'webapp/login.html')
So here my key values are empty always. I have learned and capable enough to create html forms using Model and forms:Form. But to add more style changes I need to map this forms:Form object to html defined form.
Thanks in advance.

Assign a name to each input
<form action="/login/" method="post">
{% csrf_token %}
<input type="text" id="USERNAME" class="text" name="USERNAME" value="USERNAME" >
<input type="password" id="Password" value="Password" name="Password" >
<div class="submit">
<input type="submit" onclick="myFunction()" value="LOGIN">
</div>
<p>Forgot Password ?</p>
</form>

HTML form elements always need a name attribute, otherwise the browser won't have any way of sending them to the backend. It's that attribute that is the key in the POST dict.
Note that any formatting you can do with HTML on its own you can also do with Django forms; you really should use them in most circumstances.

Please add the HTML attribute using name for every form component.

Related

Why request.method is not getting invoked?

I have a read-only textbox which preloaded value from database which upon a button click sends it's value to a method present in backend to perform DELETE query of sql. The problem is occuring when I am click on the button the method is invoked but the request.method condition is not invoked. It is directly going to the end return statement of the method.
#app.route('/home/delete_reminder/<string:id_val>',methods=['GET','POST'])
#is_logged_in
def delete_reminder(id_val):
if request.method=='POST':
desc = request.form['description']
x = desc.split(',')
cur = mysql.connection.cursor()
cur.execute('DELETE FROM set_reminder WHERE DATE=%s,SUBJECT=%s,DESCRIPTION=%s',[x[0],x[1],x[2]])
cur.execute('DELETE FROM recur WHERE RECUR_NEXT=%s',[id_val])
flash('Reminder Deleted','danger')
mysql.connection.commit()
cur.close()
return redirect(url_for('search_reminder_to_delete'))
This is my backend code.
<form method="POST">
{% for data in value %}
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
Delete Reminder
{% endfor %}
</form>
This is the html part.
Your button isn't a button, it's a link. You aren't submitting your form.
If you want to fo that then you need to make you form tag:
<form method="POST" action="/home/delete_reminder/{{data.RECUR_NEXT}}">
and switch your button to be a real button that submits the form:
<div class="button">
<button type="submit" class="btn btn-warning">Send your message</button>
</div>
EDIT: Seeing that you want to have multiple possible routes for your form based on the loop.
You could try and use the formaction attribute, although it isn't going to be supported by every browser version.
<form method="POST">
{% for data in value %}
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
<div class="button">
<button formaction="/home/delete_reminder/{{data.RECUR_NEXT}}" class="btn btn-warning" type="submit" class="btn btn-warning">Delete Reminder</button>
</div>
{% endfor %}
However this will still result in your description field that is passed to the request having every single description from the whole form in a list or possibly just the last one as a single value (I can't quite remember the behaviour of multiple inputs with the same name), which I don't think is what you're expecting to happen.
It may just be easiest to create a separate form for each link in a loop to be honest:
{% for data in value %}
<form method="POST" action="/home/delete_reminder/{{data.RECUR_NEXT}}">
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
<div class="button">
<button class="btn btn-warning" type="submit" class="btn btn-warning">Delete Reminder</button>
</div>
</form>
{% endfor %}

Django with HTML Forms

I know how to set up Django forms to have Django render them. Unfortunately styling forms then becomes a little less straight forward. I am interested in finding a way to have the HTML form pass its entered values to Django. The HTML form is completely programmed in HTML and CSS. Just for context, please find below a list of solutions I dismissed for several reasons:
Set up custom template filter (CSS styling in Django forms)
Use a for loop in order to loop through each form and render each field in turn (How to style a django form - bootstrap)
Reference the form fields directly y using list items https://stackoverflow.com/posts/5930179/revisions
My problem with the first two solutions is that my s inside my form rely on class attributes which sees them assigned into a left or right column (col_half and col_half col_last).
The third doesn't quite work for me since my form is not using list items. If I happen to convert my form into list items, a strange border is added into the form field (see screenshot below).
As such I am wondering whether there is a way to just keep my HTML template and assign its valued to the forms.py one-by-one without getting this strange border (ideally I would like to stick to my input tag)? Any ad advice would be highly appreciated.
Please see the HTML form below:
<form id="register-form" name="register-form" class="nobottommargin" action="#" method="post">
<div class="col_half">
<label for="register-form-name">First Name:</label>
<input type="text" id="register-form-name" name="register-form-name" value="" class="form-control"/>
</div>
<div class="col_half col_last">
<label for="register-form-name">Last Name:</label>
<input type="text" id="register-form-name" name="register-form-name" value="" class="form-control" />
</div>
<div class="col_half">
<label for="register-form-email">Email Address:</label>
<input type="text" id="register-form-email" name="register-form-email" value="" class="form-control" />
</div>
<!-- <div class="clear"></div> -->
<div class="col_half col_last">
<label for="register-form-username">Choose a Username:</label>
<input type="text" id="register-form-username" name="register-form-username" value="" class="form-control" />
</div>
<div class="col_half">
<label for="register-form-phone">Phone:</label>
<input type="text" id="register-form-phone" name="register-form-phone" value="" class="form-control" />
</div>
<!--<div class="clear"></div> -->
<div class="col_half col_last">
<label for="register-form-phone">Country</label>
<input type="text" id="register-form-phone" name="register-form-phone" value="" class="form-control" />
</div>
<div class="col_half">
<label for="register-form-password">Choose Password:</label>
<input type="password" id="register-form-password" name="register-form-password" value="" class="form-control" />
</div>
<div class="col_half col_last">
<label for="register-form-repassword">Re-enter Password:</label>
<input type="password" id="register-form-repassword" name="register-form-repassword" value="" class="form-control" />
</div>
<div class="clear"></div>
<div class="col_full nobottommargin">
<button class="button button-3d button-black nomargin" id="register-form-submit" name="register-form-submit" value="register">Register Now</button>
</div>
</form>
Ok, I figured it out.
The trick was to realize that Django will already render its form tags (i.e. {{form.firstName}}) to an input tag. We can then add class attributes to this tag in in forms.py where we define this form:
HTML:
<form id="register-form" name="register-form" class="nobottommargin" action="#" method="post">
<div class="col_half">
<label for="register-form-name">First Name:</label>
{{ form.firstName }}
</div>
</form>
FORMS.PY:
class newUserRegistration(forms.Form):
firstName = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id':'register-form-name', 'name':'register-form-name', 'value':"", 'class':'form-control'}))
class Meta:
# specify model to be used
model = model_name
exclude = ()
THIS RENDERS THE HTML AS FOLLOWS
<form id="register-form" name="register-form" class="nobottommargin" action="#" method="post">
<div class="col_half">
<label for="register-form-name">First Name:</label>
<input type="text" id="register-form-name" name="register-form-name" value="" class="form-control" />
</div>
</form>
By adding the attributes to forms.py we are essentially rendering the input tag into the HTML.

How to post data via form HTML?

I want to post the data to the server via form. How can I do this?
<div class="panel-body">
<form role="form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sender-email" class="control-label">Username:</label>
<div class="input-icon"> <i class="icon-user fa"></i>
<input id="sender-email" type="text" placeholder="Username" class="form-control email">
</div>
</div>
<div class="form-group">
<label for="user-pass" class="control-label">Password:</label>
<div class="input-icon"> <i class="icon-lock fa"></i>
<input type="password" class="form-control" placeholder="Password" id="user-pass">
</div>
</div>
<div class="form-group">
<input class="btn btn-primary btn-block" id="authenticate_user" type="submit" value="Submit">
</div>
</form>
</div>
My views.py
#csrf_exempt
def signin(request):
if request.method == 'POST':
print request.POST.get('sender-email') #prints None
username = request.POST['username'] # throws error, username not available.
password = request.POST['password']
How do I post the data without using jquery? I know of a way of posting through AJAX jquery, but dont wanna do that.
The 'name' attribute of input tags is set as keys of request.GET and request.POST.
Add name attribute to all your input tags.
<input name="username" id="sender-email" type="text" placeholder="Username" class="form-control email">
<input name="password" type="password" class="form-control" placeholder="Password" id="user-pass" >
POST data are populated using the name attribute of your input elements. Change your id attributes or add a name one accordingly. E.g:
<input type="password" class="form-control" placeholder="Password" name="user-pass">
You should also consider using a form to handle your data more easily.

How to append string in HTML form

I am new to web development . I am using python django framework for creating my website.I wanted to take username as form Input and call a URL like reco/username/ . But when I am trying to append in the username in URL .I am getting only "/reco/" and user name is not appended in the URL.
This is the code snippet .
<form action= "/reco/"+username method="post">
<label for="username">Username: </label>
<input id="username" type="text" name="username" value="{{ current_name }}">
<input type="submit" value="OK">
{{
</form>
I am not sure what I am doing wrong.How can append input field into the url.
Use javascript in the HTML, something like this:
<script>
function myOnSubmit(myForm)
{
myForm.action = "/reco/" + myForm.username.value;
return true
}
</script>
<form onSubmit="return myOnSubmit(this)" action="/reco/" method="post">
<label for="username">Username: </label>
<input id="username" type="text" name="username" value="{{ current_name }}">
<input type="submit" value="OK">
</form>

How to use CSS with Django forms?

I have a HTML and CSS template done already, and now I have to use Python and Django to give life to the system. But I stuck into something: how to use my css with django forms ?
For example, this is what I have use in Django:
<label for="id_username">Username:</label>
{{ form.username }}
And this is what django generates:
<input id="id_username" maxlength="100" name="username" type="text" />
As the fields in the form are automatically generated by django, how can I apply style for the input field and the others fields too ?
This is my login form for example and I would like to use django with the css done so far, but how ?
<form class="form-signin" action="" method="post">
<h2 class="form-signin-heading">Pydorado</h2>
<div class="login-wrap">
<div class="user-login-info">
<input type="text" class="form-control" placeholder="User ID" autofocus>
<input type="password" class="form-control" placeholder="Password">
</div>
//..
</div>
</form>
I read the django documentation related to this but I couldn't find any solution so far. Any idea or suggestions ?
You can apply your styles in the formfield by adding extra attributes like this:
myfield = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
I also saw a neat solution where someone created a custom template tag where you could add classes in the template itself.

Categories