request.method getting defaulted to GET in Flask - python

I have created a form in Flask, and want to submit certain values which need to be processed.But the method used is getting defaulted to GET even though I have specified the method as post in my form
These are the the relevant code files:
app.py
#app.route('/test',methods=["GET","POST"])
def test():
print(request.method)
error = None
try:
if request.method == "POST":
first_name = request.form['firstname']
last_name = request.form['lastname']
flash(first_name)
flash(last_name)
return render_template("test.html")
else:
return "Wrong"
except Exception as e:
return str(e)
test.html
<form method="post" class="text-center" style="color: #757575;" action="">
<div class="form-row">
<div class="col">
<!-- First name -->
<div class="md-form">
<input type="text" name="firstname" value="{{request.form.firstname}}" class="form-control">
<label for="materialRegisterFormFirstName">First name</label>
</div>
</div>
<div class="col">
<!-- Last name -->
<div class="md-form">
<input type="text" name="lastname" value="{{request.form.lastname}}" class="form-control">
<label for="materialRegisterFormLastName">Last name</label>
</div>
</div>
</div>
<!-- File Upload -->
<div class="md-form">
<input type="file" id="fileupload" class="form-control">
</div>
<input class="btn btn-info btn-block" type="submit" value="Submit">
</form>
The method is getting defaulted to post and the response "Wrong" on loading 127.0.0.1:5000/test. The method is always GET

<form method="post" class="text-center" style="color: #757575;" action="/test" method="post">
<div class="form-row">
<div class="col">
<!-- First name -->
<div class="md-form">
<input type="text" name="firstname" value="{{request.form.firstname}}" class="form-control">
<label for="materialRegisterFormFirstName">First name</label>
</div>
</div>
<div class="col">
<!-- Last name -->
<div class="md-form">
<input type="text" name="lastname" value="{{request.form.lastname}}" class="form-control">
<label for="materialRegisterFormLastName">Last name</label>
</div>
</div>
</div>
<!-- File Upload -->
<div class="md-form">
<input type="file" id="fileupload" class="form-control">
</div>
<input class="btn btn-info btn-block" type="submit" value="Submit">
</form>
By adding the "route" to the action attribute and defining the method of submission of form, you can perform the desired objective.

Related

I am getting an error in Django while trying to submit the details in my form, what should I do?

Basically I am filling in the details in my form in Django and clicking on submit but the error is appearing. What should I do?
My Error-
TypeError at /contact
Contact() got unexpected keyword arguments: 'name', 'email',
'phone','desc', 'date'
My models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=122)
phone = models.CharField(max_length=122)
email = models.CharField(max_length=122)
desc = models.TextField()
My contacts.html
<h1 class="text-center">
Contact Us
</h1>
<form method="post" action="/contact">
{% csrf_token %}
<div class="form-group my-3">
<label for="Name" class="form-label">Name</label>
<input type="Name" class="form-control" id="Name">
</div>
<div class="form-group my-3">
<label for="phone" class="form-label">PhoneNumber</label>
<input type="phone" class="form-control" id="phone" name="phone" placeholder="Enter your Phone Number">
</div>
<div class="form-group my-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="form-group my-4">
<label for="desc" class="form-label">Tell us about Yourself</label>
<input type="desc" class="form-control" name="desc" id="exampleDecription1">
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
{% endblock body %}

Data is not getting stored in a database through a customer form

I made a customer feedback form with rating stars. But problem is, not getting stored data in database. Where the actual problem occured? What is the relevent solution? I tried many time.
forms.py:
class FeedBackForm(forms.Form):
feedBACK = forms.CharField(widget=forms.Textarea, required=True)
rating = forms.CharField(widget=forms.NumberInput)
models.py:
class ProductREVIEWS(models.Model):
rating = models.IntegerField(blank=True, null=True)
feedBACK = models.TextField(blank=True, null=True)
views.py:
def quick_view(request, quick_view_id):
form = FeedBackForm()
if request.method == "POST" and request.user.is_authenticated:
form = FeedBackForm(request.POST)
if form.is_valid():
ProductREVIEWS.objects.create(
feedBACK=form.cleaned_data.get('feedBACK'),
rating=form.cleaned_data.get('product_rating'),
)
template:
<form action="#!" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off">
{% csrf_token %}
<div class="radio-toolbar d-flex">
<input type="radio" id="one_star" name="product_rating" value="1" checked>
<label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label>
<input type="radio" id="two_star" name="product_rating" value="2">
<label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label>
<input type="radio" id="three_star" name="product_rating" value="3">
<label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label>
<input type="radio" id="four_star" name="product_rating" value="4">
<label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label>
<input type="radio" id="five_star" name="product_rating" value="5">
<label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label>
</div>
<div class="mb-3 mt-2">
<textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px; text-transform: lowercase;" type="email" class="form-control" name="feedBACK" value="" required></textarea>
</div>
Since, you are not doing anything with FeedBackForm, so you can simply get the names of fields through POST request in view as:
from django.shortcuts import redirect
def quick_view(request, quick_view_id):
if request.method == "POST" and request.user.is_authenticated:
ProductREVIEWS.objects.create(
feedBACK=request.POST.get('feedBACK'),
rating=request.POST.get('product_rating')
)
return redirect('success')
return render(request, 'some_folder_name/index.html')
def success(request):
return render(request, 'some_folder_name/success.html')
Note: Its a good practice to redirect after dealing with POST data.
Template file:
<form method="POST" class="needs-validation mt-3" style="font-size: 13px;" autocomplete="off">
{% csrf_token %}
<div class="radio-toolbar d-flex">
<input type="radio" id="one_star" name="product_rating" value="1" checked>
<label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label>
<input type="radio" id="two_star" name="product_rating" value="2">
<label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label>
<input type="radio" id="three_star" name="product_rating" value="3">
<label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label>
<input type="radio" id="four_star" name="product_rating" value="4">
<label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label>
<input type="radio" id="five_star" name="product_rating" value="5">
<label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label>
</div>
<div class="mb-3 mt-2">
<textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px; text-transform: lowercase;" type="email" class="form-control" name="feedBACK" value="" required></textarea>
</div>
<input type="submit" value="save">
</form>
urls.py
urlpatterns = [
...
path('success/',views.success,name='success')
]
success.html
<body>
<h2>Form successfully submitted.</h2>
</body>
Your code isn't actually utilising the functionality of Django forms. Firstly, I would suggest using a model form rather than just a normal form - it will automatically do some of the lifting to connect the form with your model.
https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#modelform
Secondly, you are validating the form using is_valid() but you are then manually creating the object - you can instead using save() to create the model.

How to add comment without refreshing the page itself in django

I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

How to pass bootstrap modal input data from HTML to Python Flask

I have a modal popup that allows users to input data. I want to pass that data to Flask so that I can put it in my database. For some reason, no data is being passed. I am printing out request.form and it logs "ImmutableMultiDict([])", when it should contain my form's inputs. I have been trying to use POST, but I'm open to other ideas. This is happening on Heroku, I haven't tested it locally.
HTML
<!-- Modal -->
<div class="modal fade" id="newProjectModal" tabindex="-1" aria-labelledby="newProjectModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="newProjectModalLabel">Create Project</h5>
<button type="button" class="btn-close" aria-label="Close"></button>
</div>
<form action="/createproject/" name="createProjectForm" id="createProjectForm" method="POST">
<div class="modal-body">
<div class="mb-3">
<label for="projectNameInput" class="form-label">Project Name</label>
<input type="text" class="form-control" id="projectNameInput" name="projectName" placeholder="New Project">
</div>
<div class="mb-3">
<label for="projectDescriptionInput" class="form-label">Project Description</label>
<textarea class="form-control" id="projectDescriptionInput" name="projectDescription" rows="3"></textarea>
</div>
<label for="selectUsersInput" class="form-label">Assign Personnel</label>
<select class="form-select" id="selectUsersInput" name="selectUsers" multiple aria-label="multiple select example">
{% for user in users %}
<option value="{{ user }}">{{ user }}</option>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary">Close</button>
<button class="btn btn-primary" type="submit" name="submit" value="Submit">Create Project</button>
</div>
</tr>
</form>
</div>
</div>
</div>
Python
#app.route('/createproject/', methods=['POST'])
def createproject():
if request.method == 'POST':
print(request.form)
project_name = request.form.get('projectName')
project_description = request.form.get('projectDescription')
return '''
<h1>The name value is: {}</h1>
<h1>The description value is: {}</h1>'''.format(project_name, project_description)
project_name and project_description are always "None" instead of the entered value

Django template context won't render

Hi I am trying to make a form submission app that just displays the entered information back to the user underneath the form they submitted. Unfortunately, I can't seem to load the context on the front end within the template.
Template:
You'll see under the form there is a for loop that is supposed to iterate the context, but nothing displays. I tried it with just email for now, but it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Form Practice</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form style="margin-top: 600px;" method="post" action="/form">
{% csrf_token %}
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label" >Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-2 col-form-label" >Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Radios</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
<label class="form-check-label" for="gridRadios1">
First radio
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">
<label class="form-check-label" for="gridRadios2">
Second radio
</label>
</div>
</div>
</div>
</fieldset>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1" name="check">
<label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div>
<select class="custom-select mr-sm-2 custom-select-lg mb-3" name="select" id="inlineFormCustomSelect">
<option selected>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio1" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio1">Toggle this custom radio</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio2" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio2">Or toggle this other custom radio</label>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="customFile" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" class="btn-block btn btn-primary my-1">Submit</button>
</form>
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
</div>
<div class="col-md-2"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
views.py
def index(request):
try:
email = request.POST['email']
print(email)
password = request.POST['password']
print(password)
radio = request.POST['gridRadios']
print(radio)
select = request.POST['select']
print(select)
except:
print("error")
context = {'context': {'email': email, 'password': password, 'radio': radio, 'select': select}}
print(context)
return render(request, 'form.html', context)
Replace this:
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
To:
<h1>{{ context.email }}</h1>

Categories

Resources