elif condition in django view - django

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")

Related

Django - when 1 user accesses the same view with different url kwargs - why am I getting cross over of data?

I have a django app that contains samples. On my home page, it displays a table with many samples, containing hyperlinks to the 'Sample page' - which is a view get request.
When I click on several of these samples in tandem, to open new tabs, each to a specific tab - I am getting cross over of data - I.e the url sample_id kwargs is different, but the page is displaying the same results which is incorrect. When i refresh the page, the correct sample data appears.
Is there any way around this happening is a user is to open several different sample tabs at the same time? This would impact on results and could cause errors in the workflow offered by the django app.
*is this because my view is processing too much, so the different view request=s ends up over lapping ?
Edit: adding view:
class FilterVariantSampleView(ReportView, ReportPDFGenerator, FileGenerator, limsQuery):
template_name = os.path.join(
'results',
'filter_templates',
'sample_page.html'
)
type = 'sample'
choice = False
group_required = ['filter']
def get(self, request, *args, **kwargs):
self.user = request.user
self.obtain_sample_information(kwargs)
self.obtain_patient_information()
self.obtain_header()
# create sample notes form
sample_notes_form = SampleNotesForm(
instance=self.sample_obj)
self.context['sample_notes_form'] = sample_notes_form
self.create_variant_filter_formset()
panel_list = [o.run_id.machine_panel_id.panel_id
for o in self.all_sr_obj]
if len(panel_list):
self.panel_obj = panel_list[0]
# self.generate_hotspot_form()
self.assess_fails()
crs_qs = ClinicallyReportedSample.objects.filter(
sample_id=self.sample_obj)
crs_qs = crs_qs.exclude(
reported_on_panel__parent_panel__isnull=False,
primary_technical_report=False,
final_technical_report=False
)
remove_report_form_list = []
lims_molecular_results = self.query_lims_clone_molecular(
qs=crs_qs)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
self.context['summary'] = summary
if crs_qs.count() == 1:
crs_obj = crs_qs[0]
self.context['crs_qs'] = crs_qs
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
else:
messages.add_message(self.request, messages.WARNING,
'This sample has been sequenced on multiple panels.')
self.context['crs_qs'] = crs_qs
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
for crs_obj in crs_qs:
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
if crs_obj.diagnostic_report_required == False:
messages.add_message(self.request, messages.WARNING,
f'This sample does NOT require a diagnostic reoprt '
f'for the {crs_obj.reported_on_panel} panel.')
self.context['remove_report_form_list'] = remove_report_form_list
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
"""
"""
self.define_variant_filter_formset()
submit = request.POST.get('submit', None)
if submit:
if submit == 'Modify sample':
logger.info('')
logger.info('Sample: {}'.format(self.sample_obj))
logger.info("Submit: '{}'".format(submit))
# pass POST dict to formset
modify_formset = self.CRVFormSet(request.POST, prefix='crv')
# validate
if modify_formset.is_valid():
logger.info('Modify Variant Formset valid')
logger.info('')
self.modify_variants(modify_formset)
self.modify_sample()
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
else:
msg = ('Modify ClinicallyReportedVariant '
f'Formset NOT valid: {modify_formset.errors}')
logger.error(msg)
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
elif submit == 'Update':
form = RemoveDiagnosticReportForm(request.POST,
instance=ClinicallyReportedSample.objects.get(
sample_id=kwargs['sample_id'],
reported_on_panel=request.POST['reported_on_panel'])
)
if form.is_valid():
logger.info('RemoveDiagnosticReportForm is valid')
try:
form.save()
except Exception as e:
logger.error(e)
else:
msg = f'RemoveDiagnosticReportForm is NOT valid: {form.errors}'
logger.error(msg)
messages.add_message(self.request, messages.ERROR, msg)
return HttpResponseRedirect(request.path_info)
elif 'Download' in submit:
panel_name = submit.split(' ')[1]
self.panel_obj = Panel.objects.get(panel_name=panel_name)
self.crs_obj = ClinicallyReportedSample.objects.get(
sample_id=self.sample_obj, reported_on_panel=self.panel_obj)
if 'panel data' in submit:
logger.info(f'Downloading data for {self.sample_obj}')
if self.crs_obj.sample_id.external_dept.site in ['Newcastle', 'Sheffield']:
downloaded_data = self.download_yne_data()
if downloaded_data:
self.crs_obj.downloaded_data = True
self.crs_obj.downloaded_data_user = request.user
self.crs_obj.downloaded_data_date = timezone.now()
self.crs_obj.save()
return downloaded_data
else:
return HttpResponseRedirect(self.request.path_info)
elif 'report' in submit:
logger.info(f'Downloading report for {self.sample_obj}')
# update crs_obj
self.crs_obj.download_technical_report = True
self.crs_obj.download_technical_report_user = self.user
self.crs_obj.download_technical_report_date = timezone.now()
self.crs_obj.save()
# return HttpResponseRedirect(self.request.path_info)
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
if mol_df.empty:
logger.info('No molecular tests done')
self.latex_context['gene_status'] = False
else:
gene = mol_df[
(mol_df['test_name'] == 'gene') &
(mol_df['status'] == 'complete')
]
if gene.empty:
self.context['gene'] = False
else:
msg = ("gene Sanger in-fill test has been completed.{}")
result = gene['result'].to_string(index=False)
if result == 'normal or wild-type':
msg = msg.format(' No detectable variants.')
msg_info = messages.INFO
gene_df = pd.DataFrame()
elif result == 'failed':
msg = msg.format(' Unfortunately the test failed.')
msg_info = messages.WARNING
gene_df = pd.DataFrame()
elif result == 'mutated' or result == 'suspicious':
gene_df = self.get_gene_result(gene, technical_report=True)
if result == 'suspicious':
msg = msg.format(' There is suspicion of a variant '
'(see below for more information).')
else:
msg = msg.format(' A variant was detected '
'(see below for more information).')
msg_info = messages.INFO
else:
msg = msg.format(' Error - contact administrator.')
msg_info = messages.ERROR
result = 'error'
gene_df = pd.DataFrame()
self.latex_context['gene_status'] = result
self.latex_context['gene_df'] = gene_df
logger.info(msg)
messages.add_message(self.request, msg_info, msg)
print(self.latex_context)
# call method from TechnicalReportPDFGenerator
self.generateReport(report_type='technical')
response = self.download_technical_report()
return response
return render(request, self.template_name, self.context)
This may be due to the cache of your browser, are you sure the calls are going through the first time ?

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'),

django prevent accessing variable before it's defined on submit

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)

i want to show duplicate value error on front end

i have an query_name field in database. i want that every value should be unique so i changed it constraint and add unique= true.
now i want that if user enter the duplicate value then error duplicate value show to the user. currently error is showing only in backend
here is my code in python
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
data_dict = request.POST.dict()
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html', context = None)
database :
query_name = models.CharField(max_length=100,unique= True, default= True)
code 2 :
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
querydata = ReportCreationData.objects.all()
querydata_list = []
querydata_dict = {'query_name':''}
for data in querydata:
querydata_dict['query_name'] = data.query_name
print ('querydata_dict', querydata_dict)
data_dict = request.POST.dict()
query_name = data_dict['query_name'],
print ('query_name', query_name)
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
if (query_name == querydata_dict).exists():
raise ('already exists')
else:
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html')
with code 2 getting error:
AttributeError: 'bool' object has no attribute 'exists'
Please help
Thanks
You can try before inserting the data,run a select query from database and apply where clause on your query_name with your current value.So by this you can get duplicate records.

Save request.POST to database

in view.py:
#require_POST
#csrf_exempt
def ipn(request):
transactions_logger = logging.getLogger("django")
processor = Ipn(request.POST, logger=transactions_logger)
verification_success = processor.verify_ipn()
encoding = request.POST.get('ok_charset', None)
data = QueryDict(request.body, encoding=encoding)
if verification_success:
form = OkpayIpnForm(data)
if form.is_valid():
print("ALL FINE!!")
form.save()
return HttpResponse("")
In forms.py:
class OkpayIpnForm(forms.ModelForm):
class Meta:
model = OkpayIpn
exclude = []
Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger:
class Ipn(object):
OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
OKPAY_IPN_INVALID = b'INVALID'
OKPAY_IPN_VERIFIED = b'VERIFIED'
OKPAY_IPN_TEST = b'TEST'
OKPAY_STATUS_COMPLETED = 'completed'
__verification_result = False
def __init__(self, request_data, logger):
if 'ok_verify' in request_data:
raise Exception("ok_verify must not be present in initial request data for {}".format(
self.__class__.__name__
))
self._request_data = request_data
self.logger = logger
return
def verify_ipn(self):
self.__verification_result = False
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
verify_request_payload = {
'ok_verify': 'true',
}
verify_request_payload.update(self._request_data)
resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)
if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
self.__verification_result = True
# if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production.
# self.__verification_result = True
return self.__verification_result
All is ok, I revice IPN and validate it, then I try to validate form and save it to Database.
But form doesn't pass validation and doesn't save to database.
Thank You for help
Problem was that 1 CharField of Model for saving IPN has maxlength=20, but recieved 40 symbols.
Thx jape he advised to add in form validation else statement and print form.errors
the error of of form validation was :
<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>