I have coded the below form and controller but when the page is loaded, the page automatically send request to my database. How to change the form or controller and just send request when I clicked create button.
html code:
<form method="POST" action="/conference/create">
<div class="field">
<div class="control">
<input class="input is-large" type="text" name="name" placeholder="Your Name" autofocus="">
</div>
</div>
<input class="input is-large" type="text" name="shortname" placeholder="Your Shortname">
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-large" type="text" name="year" placeholder="Year">
</div>
</div>
<button class="button is-block is-info is-large is-fullwidth">Create</button>
</form>
</div>
</div>
{% endblock %}
controller function:
#main.route('/conference/create', methods=['POST','GET'])
#login_required
def create_conference():
name = request.form.get('name')
shortname = request.form.get('shortname')
year = request.form.get('year')
startdate = request.form.get('startdate')
enddate = request.form.get('enddate')
submissiondeadline = request.form.get('submissiondeadline')
website = request.form.get('website')
tag = request.form.get('tag')
datem = datetime.today().replace(day=1)
conference = Conference(confid="1", creationdatetime=datem, name=name, shortname=shortname, year=year, startdate=startdate,
enddate=enddate, submissiondeadline=submissiondeadline, creatoruser=12, website=website)
conferenceTag = ConferenceTags("1", tag)
db.session.add(conference)
db.session.commit()
db.session.add(conferenceTag)
db.session.commit()
return render_template('create_conference.html')
By the way, I have changed controller's method parameters with just 'POST' when I do that it gives me not allowed methods error.
you should add an if statement to specify if the incoming request is POST or GET and act accordingly.
if request.method=='GET':
#load page
elif request.method=='POST':
#update database
#main.route('/conference/create', methods=['POST','GET'])
#login_required
def create_conference():
if request.method == 'POST':
name = request.form.get('name')
shortname = request.form.get('shortname')
year = request.form.get('year')
startdate = request.form.get('startdate')
enddate = request.form.get('enddate')
submissiondeadline = request.form.get('submissiondeadline')
website = request.form.get('website')
tag = request.form.get('tag')
datem = datetime.today().replace(day=1)
conference = Conference(confid="1", creationdatetime=datem, name=name, shortname=shortname, year=year, startdate=startdate,
enddate=enddate, submissiondeadline=submissiondeadline, creatoruser=12, website=website)
conferenceTag = ConferenceTags("1", tag)
db.session.add(conference)
db.session.commit()
db.session.add(conferenceTag)
db.session.commit()
return 'you want to do.'
return render_template('create_conference.html')
Related
This question already has answers here:
The view didn't return an HttpResponse object. It returned None instead
(7 answers)
Closed last month.
ValueError at /update_department/14
The view management.views.update_department didn't return an HttpResponse object. It returned None instead.Also when added with return statement data is not updating.
Request information
USER
admin
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz'
department_code
'15'
department_name_e
'Finance'
department_name_l
'Finance'
parent_code
''
submit
''
These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.
Models:
class Departments(models.Model):
department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase.
created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase.
created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase.
modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase.
modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase.
class Meta:
db_table = 'Departments'
unique_together = (('department_code'),)
def __str__(self):
return str("self.department_name_e") or ''
View:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
department_code = form.cleaned_data['department_code']
department_name_e = form.cleaned_data['department_name_e']
department_name_l = form.cleaned_data['department_name_l']
parent_code = form.cleaned_data['parent_code']
obj = form.save(commit = False)
obj.is_active = True
obj.created_by = request.user.id
obj.created_date = datetime.today()
obj.modified_by = request.user.id
obj.modified_date = datetime.today()
obj.save()
return HttpResponseRedirect('department_list')
forms:
class DepartmentsForm(forms.ModelForm):
class Meta:
model = Departments
fields = ['department_code','department_name_e','department_name_l','parent_code']
HTML:
{% extends 'base.html' %}
{% block title %}Update Company{% endblock title %}
{% block body %}
<div style="margin-left:22%" class=" top-marg">
<h2 ><strong>Company:</strong></h2><br><br>
<form class="" action="{%url 'update_company' comp_up.company_code %}" method="post">
{% csrf_token %}
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_code}}" class="form-control" id="company_code" name="company_code" placeholder="Company Code" required>
<label style="margin-left:15px" for="company_code">Company Code</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_e}}" class="form-control" id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name English</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_l}}" class="form-control" id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name Local</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.tel}}" class="form-control" id = "tel" name="tel" placeholder="Telephone Number" required>
<label style="margin-left:15px" for="tel">Telephone Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.fax}}" class="form-control" id = "fax" name="fax" placeholder="Enter Fax"required>
<label style="margin-left:15px" for="fax"> Fax Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<textarea name="address" class="form-control" rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
<label style="margin-left:15px" for="address">Address</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<select class="form-control" name="country_id" required>
<option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
{% for con in country %}
<option value="{{con.id}}" >{{con.country_name_e}}</option>
{% endfor %}
</select>
</div>
<br>
<label style = "margin-left:21%; " for="logo">Logo</label>
<div class="form-floating" >
<input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)" required> <br>
<img style = "margin-left:21%;" id="output" >
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
<br><br>
<center>
<button type="submit" class="btn btn-success" name="submit">Update</button>
<button type="button" class="btn btn-primary" onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>
</center>
</form>
</div>
{% endblock body %}
You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
...
return HttpResponseRedirect('department_list')
form = DepartmentsForm()
return render(request, 'template.html', context={'form': form})
This code is very big, in this code I am taking data from forms and I don't know from which form the user has triggered the button. So, in code I am identifying where it has values and where not which has make my code big that's a very awkward and maybe this is not a professional way to do this. If there is another way to minimize/upgrade this code, please let me know.
#app.route('/search', methods=['POST','GET'])
def search():
if request.method=='POST':
"""Fetching all the Inputs"""
isbn = request.form.get('isbn')
title = request.form.get('title')
author = request.form.get('author')
if isbn is None:
if title is None:
if author is not None:
"""Here ONly we have author input"""
info = db.execute("SELECT * FROM books WHERE author = :author",{'author':author}).fetchall()
else:
"""Here no one"""
else:
"""Here title has value"""
if author is not None:
"""here title and author has only value"""
info = db.execute("SELECT * FROM books WHERE author = :author OR title = :title",{'author':author, 'title':title}).fetchall()
else:
info = db.execute("SELECT * FROM books WHERE title = :title",{'title':title}).fetchall()
else:
if title is None:
if author is not None:
"""Here ONly we have author and isbn input"""
info = db.execute("SELECT * FROM books WHERE author = :author OR isbn = :isbn",{'author':author, 'isbn':isbn}).fetchall()
else:
info = db.execute("SELECT * FROM books WHERE isbn = :isbn",{'isbn':isbn}).fetchall()
else:
"""Here title and isbn has value"""
if author is not None:
"""here title, isbn, author has only value"""
info = db.execute("SELECT * FROM books WHERE author = :author OR ibsn = :isbn OR title = :title",{'author':author, 'ibsn':ibsn, 'title':title}).fetchall()
else:
"""here title, isbn has only value"""
info = db.execute("SELECT * FROM books WHERE title = :title OR isbn = :isbn",{'title':title, 'isbn':isbn}).fetchall()
Html code look like this;
<html>
<div class="row" style="margin-top: 15px; padding: 2px;">
<nav class="navbar navbar-light bg-light">
<form class="form-inline" action="{{ url_for('search') }}" method="post">
<input class="form-control mr-sm-2" name="isbn" type="search" placeholder="Enter Isbn" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</nav>
<nav class="navbar navbar-light bg-light">
<form class="form-inline" action="{{ url_for('search') }}" method="post">
<input class="form-control mr-sm-2" name="title" type="search" placeholder="Enter Title" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</nav>
<nav class="navbar navbar-light bg-light">
<form class="form-inline" action="{{ url_for('search') }}" method="post">
<input class="form-control mr-sm-2" name="author" type="search" placeholder="Enter Author" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</nav>
</div>
<div>
<form id="center" action="{{ url_for('search') }}" method="post">
<button type="button" class="btn btn-primary">Search</button>
</form>
</div>
Well in order to do it in an easy and more professional way
you can add a query string to the requested URL for submitting
each form like this simple example:
forms.html
<form action="/reg?f=f1" method="post">
<input type="text" name="username" placeholder="username">
<input type="submit" value="submit">
</form>
<form action="/reg?f=f2" method="post">
<input type="email" name="email" placeholder="email">
<input type="submit" value="submit">
</form>
so the first form and the second one can be ientified because
of the query string, so if the f equals "f1" then it's the first form
otherwise it's the second one
server_app.py
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/reg', methods=['GET', 'POST'])
def sign_up():
# if the method is POST then the user is submitting a form otherwise he's just requesting page content
if request.method == "POST":
# the first form being submitted
if request.args.get("f") == "f1":
print(request.form["username"])
# the second form being submitted
else:
print(request.form["email"])
# always the same page only for testing
return render_template("forms.html")
app.run(host='127.0.0.1',port=8080,debug=True)
I am creating a search feature. where the user will input name and city. results should appear like: name available in that city should show up.
view.py
def search(request):
if request.method == 'GET':
srch = request.GET['srh']
srch1 = request.GET['srh1']
if srch:
match = demo.objects.filter(Q(name__icontains=srch))
if srch1 in match:
match2 = demo.objects.filter(Q(city__icontains=srch1))
if match2:
return render(request, 'listing-search.html', {'sr':match2})
else:
print('no result found')
else:
return HttpResponseRedirect('')
return render(request, 'listing-search.html')
Template
<form action="search/" method="get">
<div class="input-group input-group-1">
<span class="input-group-addon" id="basic-addon1">Find</span>
<input type="text" name= "srh" class="form-control" placeholder="Business Name Type Karo" aria-describedby="basic-addon1" list="find">
</div>
<div class="input-group input-group-2">
<span class="input-group-addon" id="basic-addon2">Location</span>
<input type="text" name="srh1" class="form-control" placeholder="Ex: Shahabad" aria-describedby="basic-addon2" list="suggest-location">
</div>
<button class="btn btn-default" type="submit"><i class="fa fa-search" style="font-size: 25px"></i></button>
<div class="fix"></div>
</form>
Models.py
class demo(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100, null=True,)
def __str__(self):
return self.name
Instead of this:
srch = request.GET['srh']
srch1 = request.GET['srh1']
Use this:
srch = request.GET.get('srh')
srch1 = request.GET.get('srh1')
So I made a form but after i clicked Submit button, it not redirected at all. I don't know if the form is actually submitted or not, because after i clicked submit, the url just added /submit, not even redirect to the right page.
Here's my views:
def submit_company_profile(request):
if request.session['status'] == "employer":
form = CompanyProfileEdit(request.POST or None)
if(request.method == 'POST' and form.is_valid()):
company_creator_profile_id = request.session['profile_id']
country = request.POST.get('country', False)
province = request.POST.get('province', False)
city = request.POST.get('city', False)
company_name = request.POST.get('company_name', False)
company_description = request.POST.get('company_description', False)
company_website = request.POST.get('company_website', False)
company_logo = request.POST.get('company_logo', False)
query = Company.objects.filter(company_creator_profile_id=request.session['profile_id'])
query_size = query.count()
if query_size > 0:
company = query[0]
company.country = country
company.province = province
company.city = city
company.company_name = company_name
company.company_description = company_description
company.company_website = company_website
company.company_logo = company_logo
company.save()
else:
Company.objects.create(
company_creator_profile_id=request.session['profile_id'],
country = country,
province = province,
city = city,
company_name = company_name,
company_description = company_description,
company_website = company_website,
company_logo = company_logo
)
return redirect(reverse('app_employer:company_profile'))
Here's my HTML
<form method="POST" action="{% url 'app-employer:submit-company-profile' %}">
{% csrf_token %}
{% for field in company_form %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{field}}
</div>
{% endfor %}
<div class="upload">
<p><strong>Upload your company logo</strong></p>
<div class="row">
<div class="col-sm-4">
<button class="btn btn-block btn-default">Choose File</button>
</div>
<div class="col-sm-4">
<div class="text-file-name">
<p style="color:#999">No file chosen</p>
</div>
</div>
</div>
</div>
<div class="btn-padding-form">
<input id="submit" type="submit" class="btn btn-info btn-md btn-block" value="Submit">
</div>
</form>
The upload logo button can't be use yet. So i'm gonna submit form without uploading the logo.
Hi I am new and I am attempting to update (or insert using upsert) an item, called "faq" to MongoDB using python (including Jinja templates) and Bootstrap forms with my html. I keep receiving a POST 500 Server Error and just want to be able to successfully update/upsert a document in MongoDB. I am using Mongo 2.6 an python 3.4 - Any help would be greatly appreciated!
My Bootstrap form/ html is as follows:
<form role="form" action="" method="POST">
<div class="form-group">
<label for="category">Category (select one):</label>
<select class="form-control" id="category" name="category">
{% for one in catList %}
<option>{{ one }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="question">Question:</label>
<input type="text" class="form-control" id="question" name="question"/>
</div>
<div class="form-group">
<label for="answer">Answer:</label>
<textarea class="form-control" rows="5" id="answer" name="answer"></textarea>
</div>
<div class="form-group">
<label for="ordinalNum">Ordinal Number</label>
<input type="text" class="form-control" id="ordinalNum" name="ordinalNum">
</div>
<p>This is used to determine the order in which questions are displayed.</p>
<br /><br />
<input type="submit" name="Submit" value="Submit" id="Submit" class="btn btn-primary" />
</form>
My python is as follows:
#app.route('/faqtemp', methods=['GET', 'POST'])
#nocache
def faqtemp():
"""Renders the faqtemp page."""
user = g.user
cat = Category.objects.filter(isDeleted=False)
catList = {}
for thing in cat:
if thing.category not in catList:
catList[thing.category] = thing.ordinalNum
catList = sorted(catList, key=lambda key: catList[key])
links = []
for name in catList:
name = name.replace(" ", "")
links.append(name)
stuff = FAQ.objects.filter(isDeleted=False)
if request.method == 'GET':
return render_template('faqtemp.html',
title='faqtemp',
message='practice',
catList=catList,
stuff=stuff,
user = user,
year = datetime.now().year)
elif request.method == 'POST':
# read form data and save it
category = request.form['category']
question = request.form['question']
answer = request.form['answer']
ordinalNum = request.form['ordinalNum']
aFAQ = FAQ(userUUID=user, category=category, question=question, answer=answer, ordinalNum=ordinalNum)
aFAQ.save()
#FAQ.update(category, question, answer, ordinalNum, user)
return render_template('faqtemp.html',
title='faqtemp',
message='practice',
catList=catList,
stuff=stuff,
user = user,
year = datetime.now().year)
else:
return("<h2>Invalid request</h2>")
And I have created a class Document for an FAQ using python:
from mongoengine import *
import datetime
class FAQ(Document):
question = StringField(required=True)
answer = StringField(required=True)
category = StringField(required=True)
ordinalNum = IntField(required=True)
isDeleted = BooleanField(required=True, default=False)
userUUID = StringField(required=True)
createTS = DateTimeField(required=True, default=None)
def __init__(self, *args, **kwargs):
Document.__init__(self, *args, **kwargs)
if not self.createTS:
self.createTS = datetime.datetime.utcnow()
# def get(self):
def delete(self):
self.isDeleted = True
self.save()
def update(self, category, question, answer, ordinalNum, user):
self.category = category
self.question = question
self.answer = answer
self.ordinalNum = ordinalNum
self.isDeleted = False
self.userUUID = user
self.createTS = datetime.datetime.utcnow()
self.save()