django prevent accessing variable before it's defined on submit - django

I have the following django view that works great except in the instance of clicking the submitted button on the previous view i'm sending the POST information from.
def submitted(request):
# sets the employeentname to the username from the POST of results
owner = ADMirror.objects.get (employeentname=request.POST.get('userpost'))
# sets the firstname of owner
firstname = owner.employeefirstname
# sets the lastname of owner
lastname = owner.employeelastname
# gets the POST list for the report_id values in the checkboxes for application names
checkedlist = request.POST.getlist('report_id')
reportdetail = QvReportList.objects.filter(report_id__in = checkedlist).values_list('report_name_sc', flat = True).distinct()
# gets the timestamp from the system clock when the submit button is pressed
access_request_date = timezone.now()
#### Unused at this time, but we can pull the division CFO and facility CFO based on the tables Gregg created in the SQL server database. We'll let the workflow tool handle this part.
# facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = '34222', active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
# divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = '34222', active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
#print (facilitycfo)
#print (divisioncfo)
# gets the access level ie facility, division, market, group, corporate from the results.html POST request sent to submitted.html
selectedaccesslevel = request.POST.get('accesslevelid')
# sets access level name and organization level name for the submitted page
if request.method == 'POST' and selectedaccesslevel == '3':
accesslevel = 'company-wide access'
orglevelname = ''
if request.method == 'POST' and selectedaccesslevel == '4':
accesslevel = 'group level access'
accesslevelname = request.POST.getlist('blevel')
orglevelname = FacilityDimension.objects.filter(b_level__in = accesslevelname).values_list('group_name', flat = True).distinct()
if request.method == 'POST' and selectedaccesslevel == '5':
accesslevel = 'division level access'
accesslevelname = request.POST.getlist('rlevel')
orglevelname = FacilityDimension.objects.filter(r_level__in = accesslevelname).values_list('division_name', flat = True).distinct()
if request.method == 'POST' and selectedaccesslevel == '6':
accesslevel = 'market level access'
accesslevelname = request.POST.getlist('dlevel')
orglevelname = FacilityDimension.objects.filter(d_level__in = accesslevelname).values_list('market_name', flat = True).distinct()
if request.method == 'POST' and selectedaccesslevel == '7':
accesslevel = 'facility level access'
accesslevelname = request.POST.getlist('zcoid')
orglevelname = FacilityDimension.objects.filter(coid__in = accesslevelname).values_list('coid_name', flat = True).distinct()
# gets the PHI boolean flag from the results.html POST request sent to submitted.html
selectedphi = request.POST.get('phi')
# if statements to define hte datarduce code based on the selected access level sent from the results.html POST
## corporate
if request.method == 'POST' and selectedaccesslevel == '3':
selectlist = "S00001"
# group
if request.method == 'POST' and selectedaccesslevel == '4':
selectlist = request.POST.getlist('blevel')
# division
if request.method == 'POST' and selectedaccesslevel == '5':
selectlist = request.POST.getlist('rlevel')
# market
if request.method == 'POST' and selectedaccesslevel == '6':
selectlist = request.POST.getlist('dlevel')
# facility
if request.method == 'POST' and selectedaccesslevel == '7':
selectlist = request.POST.getlist('zcoid')
selectlist = [f'Z{value}' for value in selectlist]
# nested if/for statement which writes to the [QlikView].[dbo].[QV_FormAccessRequest] table if a corporate access level is selected the datareduce code is set to S00001
if request.method == 'POST':
for i in checkedlist:
if selectedaccesslevel == '3':
requestsave = QVFormAccessRequest(ntname = 'HCA\\'+owner.employeentname, first_name = owner.employeefirstname, last_name = owner.employeelastname, coid = owner.coid, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date, previousdatareducecode = '', datareducecode = 'S00001', facility = owner.facilityname, requestid = '0', requesttype = 'New')# = list(facilitycfo)[0], division_cfo = list(divisioncfo)[0] )
requestsave.save()
# part of the nested if/for statement above which writes to [QlikView].[dbo].[QV_FormAccessRequest] if anything other than corporate user is selected it will chose the correct data reduce code based on the select list if statements above.
else:
for j in selectlist:
requestsave = QVFormAccessRequest(ntname = 'HCA\\'+owner.employeentname, first_name = owner.employeefirstname, last_name = owner.employeelastname, coid = owner.coid, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date,previousdatareducecode = '', datareducecode = j, facility = owner.facilityname,requestid = '0', requesttype = 'New' )# = list(facilitycfo)[0], division_cfo = list(divisioncfo)[0] )
requestsave.save()
args = {'firstname' : firstname, 'lastname' : lastname, 'owner' : owner, 'accesslevel':accesslevel, 'reportdetail':reportdetail, 'orglevelname':orglevelname}
return render(request, 'submitted.html', args)
I have multiple buttons on my form so I can't use required because it will interfere with the action of another so I am using the following javascript validation.
function submitFormSub(action) {
var form = document.getElementById('form1');
form.action = action;
var accesslevelid = document.getElementById('accesslevelid');
if (form.action == 'submitted')
{
if ($('#accesslevelid').val() == "")
{
alert('Please select an access level');
return false;
}
form.submit();
}
}
The validation above works wonderful, as i see the alert, but the form still tries to submit and I'm greeted with the following error.
local variable 'accesslevel' referenced before assignment

A few options:
1) Convert your form to a Django Form so that you can override the validation methods and thus have it kick back the form when its is_valid method is called and fails. That is almost certainly the cleanest. You could also define the different choices using the choices keywords on fields and clean up a LOT of unnecessary code.
2) Call selectedaccesslevel = request.POST.get('accesslevelid', None) and on None skip to rendering a return without the logic of trying to set an access level and not processing the form to create QVFormAccessRequest instances.
To explain:
selectedaccesslevel = request.POST.get('accesslevelid', None)
if selectedaccesslevel:
# all your code that defines and sets access levels that you
# don't want to run because it doesn't have a crucial bit of info
args = {'firstname' : firstname, 'lastname' : lastname, 'owner' : owner, 'accesslevel':accesslevel, 'reportdetail':reportdetail, 'orglevelname':orglevelname}
return render(request, 'submitted.html', args)

Related

How to do multiple request POST in django?

I have a view that sends a form to another view so that the user can review his form, and then after making another request post to save at that moment... so when the user enters the review view, he enters in request.POST and the form ends up being saved at the wrong time
def resumo(request, avaliado_id):
print(request.method == 'POST')
perfil = Perfil.objects.filter(user_id=avaliado_id)
queryDict = request.POST
notas = (list(queryDict.values()))
criterios = (list(queryDict.keys()))
valores = (list(queryDict.values()))
valores = [float(x.replace(",",".")) for x in valores[2:]]
pesos = (queryDict.getlist('pesos'))
pesos = [float(x.replace(",",".")) for x in pesos]
res_list = [valores[i] * pesos[i] for i in range(len(valores))]
media = sum(res_list)
lista = zip(criterios[2:], notas[2:])
print(list(lista))
query_criterio = Criterio.objects.filter(ativo = True).values_list('id', flat=True)
lista_criterio_id = list(query_criterio)
if request.method == 'POST':
avaliado = Perfil.objects.get(pk = avaliado_id)
avaliador = request.user.perfil
avaliacao = Avaliacao.objects.create(avaliador = avaliador, avaliado= avaliado, media = media)
avaliacao.save()
print(avaliacao.id)
for nota, criterio in zip(notas[2:], lista_criterio_id):
nota = Notas.objects.create(avaliacao = Avaliacao.objects.get(pk = avaliacao.id), notas = nota, criterios = Criterio.objects.get( pk = criterio))
nota.save()
context = {
'media' : media,
'chaves_e_valores' : zip(criterios[2:], notas[2:]),
'perfis' : perfil,
}
return render(request, 'admin/resumo.html', context)
in the first line "request.method == 'POST'" returns True and because of that it ends up hitting in conditional if.

my stylesheet and images doesn't work with Jinja2 templates with parameters - Django

I successfully converted my website templates to Jinja2, everything works as it should, except in urls with parameters.
I have this is views.py file
path("profile/<id>", views.profile),
When the template loads in my browser the css and images dont load.
But when I remove the parameter and set id manually in the view function everything works. Am I doing anything wrong?
profile function in views
def profile(request, id):
mydb.connect()
sql = "SELECT * FROM account_data WHERE user_id ="+str(id)
mycursor.execute(sql)
myresult = mycursor.fetchone()
if myresult == None:
mydb.connect()
sql = "SELECT * FROM account_data WHERE roblox_id="+str(id)
mycursor.execute(sql)
myresult = mycursor.fetchone()
if myresult == None:
return render(request, 'rostats_app/incorrectdetails.html', {"errormessage":"ERROR 404", "redirection":"signup", "banner":banner})
# gets skill squares
if myresult[5] != "":
skills_count = 1
for i in myresult[5]:
if i == "⏎":
skills_count += 1
skills_boxes = 0
if (skills_count >= 0) and (skills_count <= 4):
skills_boxes = 4
elif (skills_count >= 5) and (skills_count <= 8):
skills_boxes = 8
skills = myresult[5]
skills = skills.split("⏎", 4)
skills_1 = []
for x in range(0, len(skills)):
skills_1.append(skills[x])
for num, x in enumerate(skills_1):
skills_1[num] = x.split(":")
else:
skills_boxes = 0
skills_1 = []
indicator = myresult[8]
if "user_id" in request.session:
state = "Sign Out"
if str(id) == str(request.session["user_id"]):
config_profile = True
profile_heading = "Your Profile"
indicator = ""
else:
config_profile = False
if myresult[1] != "":
profile_heading = str(myresult[1])+"'s Profile"
else:
profile_heading = str(myresult[10])+"'s Profile"
else:
if myresult[1] != "":
profile_heading = str(myresult[1])+"'s Profile"
else:
profile_heading = str(myresult[10])+"'s Profile"
config_profile = False
state = "Sign Up"
status=myresult[6]
return render(request, "rostats_app/profile.html", {"username":myresult[1], "avatarurl":myresult[3], "avatarurl2":myresult[9], "discriminator":myresult[2], "roblox_username":myresult[10], "skills_boxes":skills_boxes, "skills_1":skills_1, "config_profile":config_profile, "state":state, "profile_heading":profile_heading, "indicator":indicator, "status":status, "banner":banner})
this loads the css file
<link rel="stylesheet"type="text/css" href="static/styles.css">
I fixed it by putting a / before the images and the css. I think the problem is that it tried loading it from somewhere else when parameters where in use.
try this
path("profile/<int:id>", views.profile,name='profile'),

If statement gives wrong output in query set

I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database.
I believe I should be using a get since i'm expecting one value, but how do I filter my get on coid = owner.coid.coid and provide the value ?level?
I'm looking for my output for datareducecode to be 'S00009' and not <QuerySet ['S00009']>. How can I accomplish this? Below is my view...
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
print (f"checkedlist on submitted:{checkedlist}")
access_request_date = timezone.now()
coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername)
datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid)
# facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
# divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
# print(facilitycfo)
# print(divisioncfo)
selectedaccesslevel = request.POST.get('accesslevelid')
print (f"accesslevel:{selectedaccesslevel}")
selectedphi = request.POST.get('phi')
print (f"phi:{selectedphi}")
print (owner.coid.coid)
if request.method == 'POST' and selectedaccesslevel == '3':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '4':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '5':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '6':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '7':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{Coid}"', flat = True)
print (datareducecode)
else:
datareducecode = 'No Match on Coid'
print (datareducecode)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date, datareducecode = datareducecode )
requestsave.save()
# print (datareducecode)
return JsonResponse({'is_success':True})
So this seems to do the trick:
list(datareducecode)[0]

elif condition in django view

I'm having view function which filters object according to the data I give and if that filtered object does not exist in the database it adds the object to DB(i didn't write add function yet). Shows error if it exists already. I'm getting data from a template using ajax post request.
#view.py
#csrf_exempt
def setUserInDB(request):
if request.method=="POST":
if request.POST.get('pname','u_id'):
pname = request.POST.get('pname')
u_id = request.POST.get('u_id')
user = userprofile.objects.get(pk=u_id)
pid = Project.objects.get(title=pname)
else:
u_id = None
pname = None
if request.POST.get('db_id','chkbox'):
db_id = request.POST.get('db_id')
db = Db_profile.objects.get(pk=db_id)
chkbox = request.POST.get('chkbox')
print chkbox
else:
db_id = None
chkbox = None
if Projectwiseusersetup.objects.filter(userid=user,project_id=pid,
db_profileid= db,setasdefaultproject=chkbox):
print "already exist"
elif (((Projectwiseusersetup.objects.filter(userid = user,project_id =
pid,db_profileid=db,setasdefaultproject=False)).exists()) and
(chkbox==True)):
print "FtoT"
elif Projectwiseusersetup.objects.filter(userid = user,project_id =
pid,db_profileid=db,setasdefaultproject=True) and chkbox==False:
print "TtoF"
else:
print "aaaa"
user,pid,db,chkbox }---- i'm getting these data from ajax post request,
userid, project_id, db_profileid, setasdefaultproject(boolean) }----- model fields
when I try to check my elif condition, i'm getting output in console "aaaa"(else part). what is wrong with elif?
Here the ex:
x = 4
if x == 1:
print ("1")
elif (x == 2):
print("2")
elif (x == 3):
print("3")
else:
print("4")

Django. Contains 2 slightly different forms but second form's data being saved in both

Here are my lines dealing with the two forms :
user = request.user
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
The data submitted in second form is being saved in both liked and disliked.
I have used User foreignkey in both the liked and disliked models.
Here is the complete function :
def collect(request):
context = RequestContext(request)
submitted = False
if request.method == 'POST':
data = request.POST
user_liked_form = UserLikedForm(data = request.POST)
user_disliked_form = UserDislikedForm(data = request.POST)
# user_id = data["user_id"]
user = request.user
if user_liked_form.is_valid() and user_disliked_form.is_valid():
# user_liked_form.save(commit = True)
# user_disliked_form.save(commit = True)
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
submitted = True
else:
print user_liked_form.errors, user_disliked_form.errors
else:
user_liked_form = UserLikedForm()
user_disliked_form = UserDislikedForm()
return render_to_response(
'collect.html',
{'user_liked_form': user_liked_form, 'user_disliked_form': user_disliked_form, 'submitted': submitted},
context)
It sounds like your UserLikedForm and UserDislikedForm have the same field names and when the form is submitted, only the second value comes through in request.POST. To fix this, you will need to add a prefix to the forms:
user_liked_form = UserLikedForm(prefix='liked')
user_disliked_form = UserDislikedForm(prefix='disliked')
That way when the forms are rendered, each form will have unique field names.