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]
Related
**QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1, due to unknown error.**
def view_entry_pdf(request,id):
standard_fields = ['user_username','user_email', 'form_id', 'entry_id', 'date_dmy','user_full_name']
try:
entry = Entries.objects.get(pk=id)
cert = Certificate.objects.filter(form_id=entry.form.id, is_active=1).first()
get_cert = request.GET.get('cert_id','')
if get_cert:
cert = Certificate.objects.get(id=get_cert)
if not cert:
messages.warning(request, 'PDF template not found.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
valid_rules = validate_rules(entry,cert, cert.rules.all())
if valid_rules:
pass
else:
messages.warning(request, 'Certificate rules not matched.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
entry.is_read = True
entry.save()
file_name = 'entry-certificate.pdf'
if cert.file_name:
file_name = cert.file_name
res = re.findall(r'(\{\{[^}]+}\})', file_name)
placeholders = {}
standard_placeholders = {}
#standard_fields
for sf in standard_fields:
sfv = ''
if sf == 'user_username':
sfv = entry.user.username
elif sf == 'user_email':
sfv = entry.user.email
elif sf == 'form_id':
sfv = str(entry.form.id)
elif sf == 'entry_id':
sfv = str(entry.id)
elif sf == 'date_dmy':
today = datetime.now().date()
sfv = today.strftime("%d-%m-%Y")
elif sf == 'user_full_name':
sfv = f"{entry.user.first_name} {entry.user.last_name}"
standard_placeholders['{{'+sf+'}}'] = sfv
standard_placeholders = account_placeholders(request, standard_placeholders)
if res:
fields_all = entry.form.fields.all().order_by('sort_order')
for f in fields_all:
key = '{{'+f.label_name.replace(" ", "_").lower()+'}}'
placeholders[key] = f.id
for p in res:
f_id = placeholders.get(p)
if p and f_id:
en_data = entry.columns.filter(field_id=f_id)
val = ''
if en_data.count() and en_data[0].value:
val = en_data[0].value
file_name = file_name.replace(p, val)
elif standard_placeholders.get(p):
file_name = file_name.replace(p, standard_placeholders[p])
cert_path = '{}/form/certificates/{}'.format(settings.MEDIA_ROOT,file_name)
#cert_path = 'media/form/certificates/{file_name}'
url = '{}://{}/admin/forms/entry-pdf/{}?system_run=1&cert={}'.format(request.scheme, request.get_host(), entry.id, cert.id)
print("reached here------------------------------")
options = {
'dpi': 365,
'page-size':cert.page_type,
'orientation':cert.orientation
}
pdfkit.from_url(url,cert_path,options=options)
#set pdf permissions
setPdfPermissions(cert, cert_path)
return FileResponse(open(cert_path, 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
I am converting html to pdf. This code worked fine before. I dont know what kind of problem is arrising now. I am not aware of this tool htmltopdf. If i am doing anything wrong please help me
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 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.
I'm trying to have the option for an admin to make fields required or not for a user.
My form looks like this.
class StudentDetailForm(MyForm):
first_name = fields.CharField(required=True)
last_name = fields.CharField(required=True)
date_of_birth = MyDateField(required=True, widget=MyDateInput(attrs{'class': 'dobpicker'}))
id_number2 = fields.CharField(required=True, label='PPS Number')
note = fields.CharField(required=False,
widget=forms.Textarea(attrs={'cols': '25', 'rows': '2'}))
class Meta:
model = Person
fields = ['first_name', 'last_name', 'date_of_birth', 'id_number2', 'gender', 'note']
etc...
This is how I tried to changed the required field. It loops through all the fields and presents tick boxes for visible or required on the admin page.
Then each is presented on the form page with a required or not value.
student_form = StudentDetailForm(None, data=request.POST or None)
mother_form = ParentDetailForm(None, data=request.POST or None, prefix='g1', instance=mother)
father_form = ParentDetailForm(None, data=request.POST or None, prefix='g2', instance=father)
family_form = FamilyDetailForm(None, data=request.POST or None)
# student_form, mother_form, father_form, family_form = get_web_intake_forms(school, request.POST or None, requestpps)
for name, value in webfields.items():
if not value['visible']:
# name is actual name plus : plus a number
# split up to name and number
bits = name.split(':')
fname = bits[0]
formnum = bits[1]
if formnum == '1':
del student_form.fields[fname]
elif formnum == '2':
del mother_form.fields[fname]
elif formnum == '3':
del father_form.fields[fname]
elif formnum == '4':
del family_form.fields[fname]
elif value['required']:
# name is actual name plus : plus a number
# split up to name and number
bits = name.split(':')
fname = bits[0]
formnum = bits[1]
if formnum == '1':
student_form.base_fields[fname].required = True
elif formnum == '2':
mother_form.fields[fname].required = True
elif formnum == '3':
father_form.fields[fname].required = True
elif formnum == '4':
family_form.base_fields[fname].required = True
elif not value['required']:
# name is actual name plus : plus a number
# split up to name and number
bits = name.split(':')
fname = bits[0]
formnum = bits[1]
if formnum == '1':
student_form.base_fields[fname].required = False
elif formnum == '2':
mother_form.fields[fname].required = False
elif formnum == '3':
father_form.fields[fname].required = False
elif formnum == '4':
family_form.base_fields[fname].required = False
I tried base_fields which kind of worked but was a bit messy.
Any ideas?
You probably don't want to change base_fields - that updates the fields of the StudentDetailForm class, not just the particular form instance
Depending on the rest of your view, setting form.fields['first_name'].required should work.
However, it's normally better to set self.fields['first_name'].required inside the form's __init__ method. I'm not sure how you would do this because you seem to have multiple forms and many field names, so here's a simpler example.
class MyForm(forms.Form):
first_name = forms.CharField()
def __init__(self, *args, **kwargs):
first_name_required = kwargs.pop('first_name_required')
super(MyForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = first_name_required
You would then initialise your form like:
form = MyForm(data=request.POST, first_name_required=True)
I have a dinamic form wizard step as following:
class AltaForm6(forms.Form):
CHOICES = ((1, 1,), (2, 2,))
username = ChoiceFieldInvalid(required=True, label="Usuario", widget=forms.RadioSelect, choices=CHOICES)
username2 = forms.CharField(required=False, label="Otro")
#username = ChoiceWithOtherField(required=True, label="Usuario", choices=CHOICES)
def clean_username2(self):
username = self.cleaned_data.get('username')
username2 = self.cleaned_data.get('username2')
if username == "Otro" and len(username2) == 0:
raise forms.ValidationError("Debe especificar un nombre de usuario")
return username2
def clean_username(self):
username = self.cleaned_data.get('username')
return username
Then i dynamically change the choices values:
class AltaWizard(SessionWizardView):
template_name = 'agroshare/wizard.html'
def get_form(self, step=None, data=None, files=None):
form = super(AltaWizard, self).get_form(step, data, files)
if step == '5':
import logging
logger = logging.getLogger(__name__)
cleaned_data = self.get_cleaned_data_for_step('2') or {}
logger.error(cleaned_data)
nombre = cleaned_data.get('nombre')
apellido = cleaned_data.get('apellido')
first = possibleUid(nombre, apellido, '1')
second = possibleUid(nombre, apellido, '2')
if ' ' in nombre:
third = possibleUid(nombre, apellido, '3')
form.fields['username'].choices = ((first, first,), (second, second,), (third, third,), ("Otro", "Otro",))
if ' ' in apellido:
fourth = possibleUid(nombre, apellido, '4')
form.fields['username'].choices = ((first, first,), (second, second,), (fourth, fourth,), ("Otro", "Otro",))
else:
form.fields['username'].choices = ((first, first,), (second, second,), ("Otro", "Otro",))
if step == '5':
form.user = self.request.user
return form
def render(self, form=None, **kwargs):
form = form or self.get_form()
context = self.get_context_data(form=form, **kwargs)
if self.steps.current == '5':
form2 = self.get_form('5')
cleaned_data = self.get_cleaned_data_for_step('5') or {}
username = cleaned_data.get('username')
form2.fields['username'].choices = [username]
return self.render_to_response(context)
The problem is, when i go back to this step trough the wizard, it does not modify the "choices" values, it shows "CHOICES = ((1, 1,), (2, 2,))"
How can i achieve that when i go back to this step, the form can actually show the values i want?