Django - Else Syntax Error - python

I have the following code on my views.py
def visao_produto(request, produto_visualizado, categoria_produto):
produto = Camisa.objects.get(slug=produto_visualizado)
categoria_desejada = categoria_produto.replace("_"," ")
if request.method == 'POST':
form = LojaForm(request.POST)
if form.is_valid():
add_to_cart(request, produto_visualizado.id, produto_visualizado.tipo, produto_visualizado.categoria)
get_cart(request)
else:
print form.errors
else:
form = LojaForm()
return render_to_response('loja/produto_visualizado.html', { 'produto' : produto, 'categoria_desejada' : categoria_desejada, 'form' : form }, context_instance = RequestContext(request))
But my template is returning the following error:
SyntaxError at /loja/Minecraft/minecraftsteve/
invalid syntax (views.py, line 34)
Line 34, on this case, is the line of the last else, before "print form.errors", which is there because i was trying to solve this problem. I'm not sure if the rest of the code is correct, but right now i'm just stuck on this problem.
I have imported everything and i really don't know what is possible to be wrong in an else statement.
Thanks for your help

Indentation error is my best guess, right above the else line in question. Django sometimes spits these out as simple syntax issues. Immediate other things to check (that don't seem present) are a missed closing quote, comma or parentheses, though I really don't see any of those (which leads me to indent errors).
I've gone over your code and even copied/pasted with some dummy stuff into my test server, and I can't find anything "wrong" with what shows up here on screen. So I'd start by making sure there's not an issue where you used 4 spaces instead of tab or vice versa. That would be covered up by Stack's HTML formatting so we can't necessarily see that.

Related

int() argument must be a string, a bytes-like object or a number, not 'NoneType' Django

Why am i getting this error here? It very wierd, sometimes it works and sometimes it does not. Can someone explain if they understand.
The error accures in my views.py file:
fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister")
kalkuler = ProduktKalkureing.objects.all()
beregning = {}
if request.method == "POST":
omkrets = request.GET.get('omkrets')
for i in kalkuler:
kalk = math.ceil((int(omkrets)/i.lengde)*1000)
add = ({'produkt_tittel': i.produkt.produkt_tittel,
'produkt_bilde': i.produkt.produkt_bilde,
'produkt_info': i.produkt.produkt_info,
'produkt_link': i.produkt.produkt_link,
'pris_heltall': i.produkt.pris_heltall,
'antall_kalk': kalk,
'total_kost': kalk * i.produkt.pris_heltall
})
beregning.update(add)
What im trying to do is get the value from a POST request and calculate based on that value. Also i would like to put all the values into a dictionary, also having trouble with that. All i would like to put all the information in the add dictionary and display that on my template. Thanks for any answers, im just trying to understand how python operates.

Replacing django decorator commit_manually with non_atomic_requests

I have a Django view which imports an Excel file, and if exceptions occur I would like to catch them and report them all, and roll back any saves. I'm getting a TransactionManagementError even though I have used the non_atomic_requests decorator.
As I'm also using the login_required decorator I thought they might be interfering with each other. First I reversed the order then I removed the login required. No change.
I've tried disabling automatic transactions globally. Maybe I didn't do it right but it's not the solution I want anyway.
I removed the offending line of code (see below) but the same error occurred when I tried to rollback
It is running on Python 3.7.3 with the latest Django and using SQLlite. I'm running it as a unit test right now, although perhaps I'm abusing the term. Suffice to say it's running as a Django TestCase.
#transaction.non_atomic_requests
#login_required(login_url='/accounts/login/?next=/finance/gl_upload/')
def gl_upload(request):
transaction.set_autocommit(False)
if upriv(request.user, ['admin', 'finance']) == 'admin':
if request.method == 'POST':
... file processing here ...
except Exception as e:
errs.append(format('Exception "{1}" at row {0}\n'.format(p['rownum'], e)))
if errs:
transaction.rollback()
rows_deleted = 0
rows_inserted = 0
print(''.join('Error: {0}\n'.format(e) for e in errs))
else:
transaction.commit()
rows_deleted = Gldata.objects.filter(item='Actual', period_gte=older, period_lte=newest).delete()
rows_inserted = Gldata.objects.filter(item=temp_item).update(item='Actual')
transaction.set_autocommit(True)
print('Deleted: {0}, inserted: {1}'.format(rows_delete, rows_inserted))
return render(request, 'gl_upload.html', {'inserted': rows_inserted, 'removed': rows_deleted, 'errors': errs})
else:
return render(request, 'gl_upload.html', {'form': form})
else:
form = uploadForm()
return render(request, 'gl_upload.html', {'form': form})
I receive a TransactionManagementError on the set_autocommit indicating that an atomic block is active even though I understood that the decorator would disable it. A few years back I used the old commit_manually decorator which worked just fine.
File "C:\Users\csullivan\responsive\finance\views.py", line 25, in gl_upload
transaction.set_autocommit(False)
File "C:\Users\csullivan\responsive\env\lib\site-packages\django\db\transaction.py", line 30, in set_autocommit
return get_connection(using).set_autocommit(autocommit)
File "C:\Users\csullivan\responsive\env\lib\site-packages\django\db\backends\base\base.py", line 394, in set_autocommit
self.validate_no_atomic_block()
File "C:\Users\csullivan\responsive\env\lib\site-packages\django\db\backends\base\base.py", line 433, in validate_no_atomic_block
"This is forbidden when an 'atomic' block is active.")
django.db.transaction.TransactionManagementError: This is forbidden when an 'atomic' block is active.
I think that the atomic()
decorator/context manager provides exactly what you need
--it commits the transaction if the underlying code succeeds and rolls back
when there's an exception.
So in your case I would just do:
with atomic():
process_xls_files()
You shouldn't need to call transaction.set_autocommit() and similar low-level methods manually,
unless you have very specific needs and the "normal" transaction handling is not enough.

Not receiving a return message in python 2 code

I'm pretty new to python and just learning to ropes. In the code bellow I have a function taking several inputs from a json string. I'm attempting to have a return output in the specified strings. Problem? when I run the file I get nothing... I'm sure I'm missing something incredibly simply, but for the life of me I can't figure out what. I've attempted to use return as well as print at the end of the function. No cheese.
Help?
Here's what I've got so far:
import datetime, json
def jeeves(request): #defines the function
message=''
if request['type']=='maintainance':
message='Thank you tenant at unit'+str(request['unit'])+', your request for maintenance to deal with '+'"'+str(request['issue'])+'"'+' has been received #2 input'
elif request['type']=='purchase':
message='Thank you tenant at unit'+str(request['unit'])+'your request to purchase a'+str(request['commodity'])+ ' has been received'
elif request['type']=='reservation':
startTime=request['date'].split(" ")[1]
startTime=startTime.split('')
time=0;
num=[]
for item in startTime:
if isdigit(item):
num.append(item)
for index in range(len(num)):
time+=num[index]*10**(len(num)-index)
endTime=0
daySplit=''.join(startTime[-2:])
if time+int(request['duration'].split(' ')[0])>12:
endTime=time+int(request['duration'].split(' ')[0])-12
if daySplit=='AM':
endTime=str(endTime)+'PM'
else:
endTime=str(endTime)+'AM'
else:
endTime=endTime+int(request['duration'].split(' ')[0])
endTime=str(endTime)+daySplit
message='Thank you tenant at unit'+str(request['unit'])+'your request to reserve our '+str(request['location'])+' on '+str(request['date'].split(' ')[0])+' from '+str(request['date'].split(' ')[1])+' to '+ endTime+' has been received'
elif request['type']=='complaint':
message='Thank you tenant at unit'+str(request['unit'])+' we will have someone follow up on '+'"'+request['issue']+'"'+' in regards to our '+request['location']
return message
print message
json.dumps(jeeves({"type":"maintenance", "unit":221, "issue":"Air filter needs replacing"}))
ps: I'm new to coding in general. If there is a better, more productive way for me to ask questions, I'm open to feedback. Thank you in advanced.
You have to put return before the print function because when you use return it ends a function. You might also want to check out what return actually does here

A python coded "alert"-like dialog or template

update 0:
There is a subtle, but serious, error in my code and in my explanation below because I cannot only compare the name on the template with the hiddenname on the template (that much only tells me that the user has made a change like a checkbox change would tell me, but purposely there are no checkboxes), I also need to compare name to the status of name in the datastore of reservations to see if someone else has already reserved the time slot. So I cannot use javascript and I have to rewrite some of the code below to make the correct comparison, too. And may original question remains as suggested by the Title of this question. (In one of the comments I erroneously said that javascript would work.)
update 0:
I am trying to write a sort of "alert" in the way that this code suggests where I use the Trans model and the gae datastore (further below) to communicate between my main app and the "alert template". I have a few problems.
Initially I had my need for this alert in an another part of my code in an else: clause, not in an elif: clause. When I tried to use the simpler version of my alert in the elif code, python seemed to ignore the self.response.out.write(template.render(path, template_values)) and just went on to this code which ended my conditionals: return webapp2.redirect("/read/%s" % location_id). So, as you can see in my code I have commented out the ignored former code line and attempted to replace it with something more like the latter code line, but with that latter line directed to unexpected instead of read. You can see from my code it is still a mix between the two approaches and I could use help sorting that out. Is there really something different about else: and elif: regarding this?
Originally I had not anticipated my desire to call the same html template and Trans model from so many places in my code, so I did not design a key or ID or key_name into the design of using Trans. And now I am having trouble implementing a version with such detail.
I have been looking for an example of how such "alert templates" can be made in python. They are so easy in javascript, but I am trying to do the user input validation in my python code. Any pointers to examples or docs would be greatly appreciated.
weekday_key = db.Key.from_path('Locations',location_id,'Courts', court_id,'Days',weekday)
if name == hiddenname:
pass
elif name != hiddenname and hiddenname == "":
reservation = Reservations.get_or_insert(time[2],parent=weekday_key)
reservation.hour = time[0]
reservation.minute = time[1]
reservation.year = int(year)
reservation.nowmonth = int(nowmonth)
reservation.day = int(day)
reservation.nowweekday = int(nowweekday)
reservation.name = name
reservation.put()
elif name != hiddenname and name!="":
reservation = Reservations.get_by_key_name(time[2],parent=weekday_key)
reservation.hour = time[0]
reservation.minute = time[1]
reservation.year = int(year)
reservation.nowmonth = int(nowmonth)
reservation.day = int(day)
reservation.nowweekday = int(nowweekday)
reservation.name = name
reservation.put()
reason='This was in that time slot already: '
trans = Trans(parent=reservation.key().name()) #this line is iffy
trans.reason=reason
trans.name=hiddenname
trans.put()
iden = trans.key().id() # this is part of the iffy just above
template_values = {'trans':trans}
path = os.path.join(TEMPLATE_DIR, 'unexpected.html')
#self.response.out.write(template.render(path, template_values))
return webapp2.redirect("/unexpected/%s/%d" % (time[2],iden) #more iffy
else:
pass
My model for Trans in next.
class Trans(db.Model):
reason = db.StringProperty()
name = db.StringProperty()
My jinja2 equipped unexpected.html template is as follows.
{% extends "base.html" %}
{% block content %}
This unexpected result occurred. {{ trans.reason }}:<emph style="font-weight: bold">{{ trans.name }}</emph>
<br /><br />
<div id="inputdata">
<label>Click the "Ok" button to go back to the previous page so you can elect to edit your entry, or not.
</label>
<button onclick="window.history.back()">Ok</button>
</div>
{% endblock content %}
This question is answered here. It could have been answered in this question, but apparently there was too much information given and no one saw the answer.

if statement invalid syntax

I'm trying to execute the following code, but I'm getting
SyntaxError: invalid syntax
at the if statement. I'm sure it's related to html as it worked previously without the preceding html; I'm having some difficulty understanding how to go in and out with html and Python as you can see.
class MainPage(webapp.RequestHandler):
def get(self):
#preceding ("""<html><head> tags...
</head>
<body>""")
self.response.out.write(today.strftime("""<html><body><p style='color:#3E3535'>%A, %d %B</p>""")
if mon <= 3:
var1 = "winter"
Thanks in advance for suggestions; the if/elifs are indented properly on page.
If this is your code, then you're missing a close-paren to close out your last function call.
Change it to the following:
self.response.out.write(today.strftime("""<html><body><p style='color:#3E3535'>%A, %d %B</p>"""))

Categories

Resources