I'm creating a product review website through web2py and have encountered difficulty whilst adding a search feature. Here's the code I have so far:
def index():
rows = db(db.reviews).select()
name_default = request.vars.name
body_default = request.vars.body
objects_default = request.vars.objects
form = SQLFORM.factory(
Field("Item Name", default = name_default),
Field("Body", default = body_default),
Field("Objects", default = objects_default),
formstyle = 'divs'
submit_button = "Search"
)
query = db.db1.id_user == auth.user_id
if form.process().accepted:
name = form.vars.name
body = form.vars.body
objects = form.vars.objects
count = db(query).count()
results = db(query).select(orderby=~db.db1.data)
msg = T("%s registers" % count)
return dict(form=form, msg=msg, results=results)
return locals()
The error I'm getting is a syntax error on line 23 character 28 (the submit_button = "Search" line).
Related
I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py
def faculty_registration(request):
data = {}
form = FacultyRegisterForm()
activetab = 'list'
if request.method == 'POST':
activetab = 'add'
form = FacultyRegisterForm(request.POST)
if form.is_valid():
userdata = User()
if User.objects.filter(username=request.POST.get('email')).exists():
messages.error(request, f"This email already exists.")
return redirect('/faculty/faculty_registration')
else:
userdatafirst_name = request.POST.get("first_name")
userdata.username = request.POST.get('email')
userdata.email = request.POST.get('email')
try:
fac_ID = Faculty.objects.last().id
except:
fac_ID = 0
LastInsertId = fac_ID+1
print('after_id',LastInsertId)
password = User.objects.make_random_password()
faculty_pw = password+str(LastInsertId)
print("pass",faculty_pw)
userdata.password = make_password(faculty_pw)
print( "teacher_pasword",userdata.password)
userdata.save()
fac = Faculty()
fac.faculty_college_id = request.POST.get("faculty_college")
fac.faculty_programme_id = request.POST.get('faculty_programme')
fac.salutation = request.POST.get("salutation")
fac.first_name = request.POST.get("first_name")
fac.middle_name = request.POST.get("middle_name")
fac.last_name = request.POST.get("last_name")
fac.phone = request.POST.get("phone")
fac.email = request.POST.get("email")
fac.address = request.POST.get('address')
fac.department = request.POST.get('department')
fac.highest_qualification = request.POST.get("highest_qualification")
fac.years_of_experience = request.POST.get('years_of_experience')
fac.previous_institute = request.POST.get('previous_institute')
# fac.documents = request.POST.get("documents")
if 'documents' in request.FILES:
filename = request.FILES['documents']
if str(filename).lower().split('.')[-1] == 'pdf':
if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024):
fac.documents = request.FILES['documents']
else:
messages.warning(request, "please upload a pdf within 3 mb")
navshow = 'add'
return redirect('faculty_registration')
else:
messages.warning(request, "please upload a pdf")
navshow = 'add'
return redirect('faculty_registration')
fac.photo = request.FILES.get('photo', 'faculty_picture/def.png')
fac.created_by_id = request.user.id
fac.user_id = userdata.id
fac.save()
assign_role(userdata, 'teacher')
html_content = render_to_string("email_template.html",{'title':'Kindly Note your Mailid and Password For Login.','to_mail':fac.email,'to_password':faculty_pw})
text_content = strip_tags(html_content)
msg = EmailMessage(
'Welcome to University', #subject
text_content, #content
settings.EMAIL_HOST_USER, #from email
[fac.email], #reclist
)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
# print("send_email",send_email)
messages.success(request, f"Lecturer has been added successfully")
return redirect('/faculty/faculty_registration')
else:
print("\ninvalid form\n")
else:
form = FacultyRegisterForm()
# fac_data = Faculty.objects.order_by('-id')
fac_data = Faculty.objects.order_by(Lower('first_name'))
data['form'] = form
data['faculties'] = fac_data
data['activetab'] = activetab
return render(request, 'faculty_register.html', data)
Also I have added searchbar button to search faculty name.
So I created following function:
def searchbar (request):
data = {}
find = request.GET['find']
res = Faculty.objects.filter(Q(first_name__icontains=find) | Q(middle_name__icontains=find)| Q(last_name__icontains=find))
activetab = 'list'
form = FacultyRegisterForm()
data['form'] = form
data['activetab'] = activetab
data['faculties'] = res
return render(request,"faculty_register.html",data)
I have also added 'add' functionality to add faculty.
Now my problem is when I click search button, I am not able to add faculty because I think i am rendering the same page 'faculty_register.html' in both return function. So how can I get same page data even after clicking 'search button'.
URLs:
urlpatterns = [
path('faculty_registration', views.faculty_registration, name='faculty_registration'),
path('faculty/searchbar', views.searchbar, name= 'searchbarf')]
I've tried to add searchbar function in faculty_registration but not able to solve this.
I am trying to build a simple numeric captcha for my contact page in Flask. The contact page end-point loads in GET mode and initializes the values of the captcha verification. When I submit the form in POST mode, I expect my user-entered form value to match the captcha value. However, it is not working as expected. I did some troubleshooting with print statements to see how the values are changing and it appears that the captcha variables are getting re-initialised with the POST operation. Can someone please suggest a workaround? My Python code is shared below:
#bp.route('/contact/', methods=('GET', 'POST'))
def contact():
# Initialize captcha values
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
cap_prod = cap_a * cap_b
print(cap_a, cap_b, cap_prod)
if request.method == "POST":
error = None
log_file = current_app.config['LOGFILE']
full_name = request.form['fullname']
email_addr = request.form['email']
phone_no = request.form['phone']
msg_body = request.form['message']
num_prod = request.form['verifycaptcha']
print(cap_a, cap_b, cap_prod)
print(full_name, email_addr, phone_no, msg_body, num_prod)
if not full_name:
error = 'Full name is required.'
elif not email_addr:
error = 'Email address is required.'
elif not msg_body:
error = 'Message body is required.'
if num_prod != cap_prod:
error = 'Incorrect captcha verification.'
if error is None:
# Perform some operations
pass
try:
with current_app.app_context():
mail = Mail()
mail.init_app(current_app)
mail.send(msg)
error = 'Mail sent successfully!'
except:
error = 'Mail engine error encountered. Please retry after some time.'
f = open(log_file, "a")
f.write('['+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'] '+error+'\n')
f.close()
flash(error)
return render_template('contact.html',num_a = cap_a, num_b = cap_b)
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
cap_prod = cap_a * cap_b
these are 2 random numbers and you are creating cap_prod. You are not saving the cap_prod anywhere. You are instead calculating it again when POST request comes (this time it will be 2 new random numbers)
You need to save the captcha that you created during the GET, and then when the POST comes , compare with the value that was originally sent.
If you are going to support refresh-captcha image in the future (you need to have an API call that will generate a new captcha and save it)
I figured out the solution by storing the captcha variables in the session dictionary of Flask and checking for its existence before re-initialising the values.
def contact():
# Initialize captcha values
if 'product' not in session:
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
session['captcha_a'] = cap_a
session['captcha_b'] = cap_b
session['product'] = cap_a * cap_b
else:
cap_a = session.get('captcha_a')
cap_b = session.get('captcha_b')
if request.method == "POST":
pass
# Rest of the code
Working examples of the above solution can be found at Fadmeter.com and FadURL.com.
I am trying to query a unique document using its ObjectId. However the error comes up:
DoesNotExist: Route matching query does not exist
When, upon passing this to my view as request, it prints out the corresponding ObjectId in ObjectId typeform. Therefore there shouldn't be a problem with the line route_test = Route.objects.get(id=_id).
I have the following code:
views.py
def update(request):
if request.method == "POST":
_id = request.POST.get('_id',ObjectId())
print(_id)
route_id = request.POST.get('route_id','')
geometry = request.POST.get('geometry', '')
properties = request.POST.get('properties','')
#r = Route.objects.get(route_id='LTFRB_PUJ2616') --> I cannot use this
#because it has 5 instances (Not Unique)
#print (r["id"],r["properties"])
test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6'))
print (test["id"], test["properties"])
try:
route_test = Route.objects.get(id=_id)
print(route_test)
Route.objects.get(id=_id).update(set__geometry=geometry, set__properties=properties)
return HttpResponse("Success!")
except:
return HttpResponse("Error!")
ajax
var finishBtn = L.easyButton({
id:'finish',
states: [{
icon:"fa fa-check",
onClick: function(btn){
selectedFeature.editing.disable();
layer.closePopup();
var editedFeature = selectedFeature.toGeoJSON();
alert("Updating:" + editedFeature.route_id);
$.ajax({
url: "/update/",
data: {id:editedFeature.id,
route_id: JSON.stringify(editedFeature.route_id),
geometry: JSON.stringify(editedFeature.geometry),
properties: JSON.stringify(editedFeature.properties)
},
type: 'POST'
});
}
model.py
from __future__ import unicode_literals
from mongoengine import *
class Route(Document):
type = StringField(required=True)
route_id = StringField(required=True)
geometry = LineStringField()
properties = DictField()
meta = {'collection':'routes'}
What should be done? Even the line test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6')) where I directly supplied the incoming _id has the same error...
I am trying to create multiple payment profiles for my customers auth net profile using the this method.
def createAuthnetPaymentProfile(profileID, tries = 3):
profile = client.factory.create("CreateCustomerPaymentProfile")
profile.merchantAuthentication = merchantAuthentication
profile.customerProfileId = profileID
profile.paymentProfile = getAuthnetProfile(profileID, tries).paymentProfiles
payment_simple_type = client.factory.create('PaymentType')
card_simple_type = client.factory.create('CreditCardSimpleType')
payment_simple_type.creditCard = card_simple_type
profile.payment = payment_simple_type
profile.payment.creditCard = card_simple_type
profile.validationMode.value = "none"
profileResult = makeAuthnetCall(client.service.CreateCustomerPaymentProfile, profile, tries)
checkForError(profileResult)
return profileResult.customerPaymentProfileId
However this returns this error AuthnetError: E00029: Payment information is required.
What might be the problem with my code.
I get a syntax error when trying to insert into a datastore, the exact same line of code worked in another project
B = db_Person(nafn='Alex')
Here is the rest of the code:
http://pastebin.com/bW37aUuT
def post(self):
q = db.Query(db_Person)
message = "Innsetning tokst"
in_kennitala = int(self.request.get('p_kennitala'))
in_nafn = self.request.get('p_nafn')
in_heimili = self.request.get('p_heimili')
in_postnumer = self.request.get('p_postnumer')
in_stadur = self.request.get('p_stadur')
in_land = self.request.get('p_land')
in_simi = int(self.request.get('p_simi'))
in_gsm = int(self.request.get('p_gsm') # <- missing right parenthesis
B = db_Person(nafn='Alex') # <- parser gets confused here
B.put()
template_values = {
'message': message
}
template = jinja_environment.get_template('breyta.html')
self.response.out.write(template.render(template_values))
This is the fixed code:
def post(self):
q = db.Query(db_Person)
message = "Innsetning tokst"
in_kennitala = int(self.request.get('p_kennitala'))
in_nafn = self.request.get('p_nafn')
in_heimili = self.request.get('p_heimili')
in_postnumer = self.request.get('p_postnumer')
in_stadur = self.request.get('p_stadur')
in_land = self.request.get('p_land')
in_simi = int(self.request.get('p_simi'))
in_gsm = int(self.request.get('p_gsm'))
B = db_Person(nafn='Alex')
B.put()
template_values = {
'message': message
}
template = jinja_environment.get_template('breyta.html')
self.response.out.write(template.render(template_values))