I'm trying to render the Django template after uploading a file (POST method). The issue is: I insert some print() inside the POST request.method and everything is working fine (terminal VSCode) but the template (HTML) is not being displayed inside the render() function.
View.py:
def index(request):
if 'GET' == request.method:
print("It didn't work it!")
print(request.FILES['file'])
return render(request, 'auditoria_app/index.html')
else:
print('It worked it!')
excel_file = request.FILES["file"]
wb = openpyxl.load_workbook(excel_file, data_only=True)
wb.security.workbook_password = 'Rnip*2020'
inputsCombo = wb['Inputs COMBO']
inputsDNCombo = wb['Inputs DN COMBO']
outputCombo = wb['OutPut COMBO']
faixas = wb['Faixas']
wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True)
sigma = wb2['sigma']
sic = wb2['Performance']
# wb4 = openpyxl.load_workbook('media/ultimoContrato.xlsm', data_only=True)
# ultimoContrato = wb4['Base']
numeroIbms = inputsCombo['F5'].value
ibms = []
output = outputResults(numeroIbms, outputCombo)
for i in range(8, 8 + numeroIbms):
ibm = Ibm(i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma)
ibms.append(ibm)
print(ibm.numeroIbm)
# sigmaReport(sigma, ibm)
return render(request, 'auditoria_app/index.html',
{'ibms': ibms,
'numeroIbms': numeroIbms,
'output': output,
})
Message displayed on VSCode terminal:
It worked it!
Outside: SAE_R360_pagnussat.xlsm
1038108
1049885
[04/Sep/2021 21:18:36] "POST /auditoria/ HTTP/1.1" 200 5132
Related
I am trying to extract an Array from a POST request using Django.
def settlements_orders(request):
database = "####"
if request.method == 'POST':
first_date = request.POST.get('first_date', False)
last_date = request.POST.get('last_date', False)
brands = request.POST.getlist('brands[]')
else:
first_date = '2020-01-01'
last_date = '2020-05-13'
brands= ['ICON-APPAREL']
settlements_orders = SettlementOrders.objects.using(database)\
.filter(posted_date__date__range=[first_date, last_date]) \
.filter(sku__brand__in=brands) \
.select_related('sku').select_related('posted_date') \
.values('sku__company','sku__brand','sku__department','sku__category','sku__sub_category',
'sku__parent_asin','sku__asin','sku__vendor', 'sku__color','sku__size','sku__case_pack',
'posted_date__year', 'posted_date__month'
)\
.annotate(count=Count('order_id'),
qty_sold=Sum('quantity_sold'),
qty_returned=Sum('quantity_returned'),
order_revenue=Sum('order_revenue'),
refund_revenue=Sum('refund_revenue'),
promotion=Sum('promotion'),
giftwrap_collected=Sum('giftwrap_collected'),
giftwrap_paid=Sum('giftwrap_paid'),
shipping_fees_collected=Sum('shipping_fees_collected'),
shipping_fees_paid=Sum('shipping_fees_paid'),
sales_tax_collected=Sum('sales_tax_collected'),
sales_tax_paid=Sum('sales_tax_paid'),
shipping_tax_collected=Sum('shipping_tax_collected'),
shipping_tax_paid=Sum('shipping_tax_paid'),
fulfillment_fees=Sum('fulfillment_fees'),
comission_fees=Sum('comission_fees'),
closing_fees=Sum('closing_fees'),
other_fees=Sum('other_fees'),
restock_fees=Sum('restock_fees'),
goodwill_paid=Sum('goodwill_paid'),
goodwill_reimbursed=Sum('goodwill_reimbursed'),
return_fees=Sum('return_fees'),
reimbursements=Sum('reimbursements'),
margin=Sum('margin')
)
return JsonResponse(settlements_orders[::1], safe=False)
I am using the Array to filter data When I make a GET request I am returned data but on a POST request, I get a 500 response. Any help would be appreciated.
I have bunch of urls in urls.py , and In template I have defined like below :
<li>Billing</li>
<li>Proforma Invoice</li>
<li>Quotation</li>
But the problem is if I click on one line say viewinvoices, and after that I click on proformainvoice, it redirects to
localhost:8000/vieweinvoices/proformainvoice.html but it should go to localhost:8000/proformainvoice.html how can I do that?
views.py :
def vieweinvoices(request):
alltaxInvoice = taxInvoice.objects.all()
totalInvoices = taxInvoice.objects.all().count()
startdate = datetime.today()
enddate = startdate - timedelta(days=14)
totalthismonthsInvoices = taxInvoice.objects.filter(
invoicedate__range=[startdate, enddate]
).count()
context = {
"alltaxInvoice": alltaxInvoice,
"totalInvoices": totalInvoices,
"totalthismonthsInvoices": totalthismonthsInvoices,
"startdate": startdate,
"enddate": enddate,
}
return render(request, "Invoice/TaxInvoice/viewinvoice.html", context)
all views are like this
and
urls.py
path("vieweinvoices/", views.vieweinvoices, name="vieweinvoices"),
path("viewequotations/", views.viewequotations, name="viewequotations"),
I try to do some stress test against my websocket server. On client side I run the following script from this site :
import time, sys
from twisted.internet import defer, reactor
from twisted.internet.defer import Deferred, returnValue, inlineCallbacks
from autobahn.twisted.websocket import connectWS, \
WebSocketClientFactory, \
WebSocketClientProtocol
class MassConnectProtocol(WebSocketClientProtocol):
didHandshake = False
def onOpen(self):
print("websocket connection opened")
self.factory.test.onConnected()
self.factory.test.protos.append(self)
self.didHandshake = True
class MassConnectFactory(WebSocketClientFactory):
protocol = MassConnectProtocol
def clientConnectionFailed(self, connector, reason):
if self.test.onFailed():
reactor.callLater(float(self.retrydelay)/1000., connector.connect)
def clientConnectionLost(self, connector, reason):
if self.test.onLost():
reactor.callLater(float(self.retrydelay)/1000., connector.connect)
class MassConnect:
def __init__(self, name, uri, connections, batchsize, batchdelay, retrydelay):
print('MassConnect init')
self.name = name
self.uri = uri
self.batchsize = batchsize
self.batchdelay = batchdelay
self.retrydelay = retrydelay
self.failed = 0
self.lost = 0
self.targetCnt = connections
self.currentCnt = 0
self.actual = 0
self.protos = []
def run(self):
print('MassConnect runned')
self.d = Deferred()
self.started = time.clock()
self.connectBunch()
return self.d
def onFailed(self):
self.failed += 1
sys.stdout.write("!")
return True
def onLost(self):
self.lost += 1
#sys.stdout.write("*")
return False
return True
def onConnected(self):
print("onconnected")
self.actual += 1
if self.actual % self.batchsize == 0:
sys.stdout.write(".")
if self.actual == self.targetCnt:
self.ended = time.clock()
duration = self.ended - self.started
print " connected %d clients to %s at %s in %s seconds (retries %d = failed %d + lost %d)" % (self.currentCnt, self.name, self.uri, duration, self.failed + self.lost, self.failed, self.lost)
result = {'name': self.name,
'uri': self.uri,
'connections': self.targetCnt,
'retries': self.failed + self.lost,
'lost': self.lost,
'failed': self.failed,
'duration': duration}
for p in self.protos:
p.sendClose()
#self.d.callback(result)
def connectBunch(self):
if self.currentCnt + self.batchsize < self.targetCnt:
c = self.batchsize
redo = True
else:
c = self.targetCnt - self.currentCnt
redo = False
for i in xrange(0, c):
factory = MassConnectFactory(self.uri)
factory.test = self
factory.retrydelay = self.retrydelay
connectWS(factory)
self.currentCnt += 1
if redo:
reactor.callLater(float(self.batchdelay)/1000., self.connectBunch)
class MassConnectTest:
def __init__(self, spec):
self.spec = spec
print('MassConnetest init')
#inlineCallbacks
def run(self):
print self.spec
res = []
for s in self.spec['servers']:
print s['uri']
t = MassConnect(s['name'],
s['uri'],
self.spec['options']['connections'],
self.spec['options']['batchsize'],
self.spec['options']['batchdelay'],
self.spec['options']['retrydelay'])
r = yield t.run()
res.append(r)
returnValue(res)
def startClient(spec, debug = False):
test = MassConnectTest(spec)
d = test.run()
return d
if __name__ == '__main__':
spec = {}
spec['servers'] = [{'name': 'test', 'uri':"ws://127.0.0.1:8080"} ]
spec['options'] ={'connections': 1000,'batchsize': 500, 'batchdelay': 1000, 'retrydelay': 200 }
startClient(spec,False)
But after running this script there are no connections established on the server side. Server seems to be configured properly, because when I connect to my server using different client side (for example web browser), it works fine and websocket connection is established. I also checked network sniffer and it seems that script doesn't produce any websocket connections.
What did I do wrong in this script?
The massconnect.py script you used was supposed to be invoked from another part of the autobahntestsuite, such as the wstest command:
$ echo '{"servers": [{"name": "test", "uri":"ws://127.0.0.1:8080"} ], "options": {"connections": 1000,"batchsize": 500, "batchdelay": 1000, "retrydelay": 200 }}' > spec.json
$ wstest -m massconnect --spec spec.json
If you want to copy massconnect directly, I think it's missing the command to start the Twisted deferred tasks:
if __name__ == '__main__':
spec = {}
spec['servers'] = [{'name': 'test', 'uri':"ws://127.0.0.1:8080"} ]
spec['options'] ={'connections': 1000,'batchsize': 500, 'batchdelay': 1000, 'retrydelay': 200 }
startClient(spec,False)
reactor.run() # <-- add this
And check your Python indentations, either some of them got corrupted when pasting here, or the original code had incorrect indentations in some class and function definitions.
I'm trying to inline my stylesheets with the following code:
views.py
def index(request):
latest_course_list = Course.objects.order_by('-start_date')
template = loader.get_template('index.html')
style_sheets = ""
style_sheets = addStyle(style_sheets)
ctx = {
'latest_course_list': latest_course_list,
'style_sheets': style_sheets,
}
return render_to_response('index.html', ctx, context_instance=RequestContext(request))
def addStyle(style):
style_sheets=""
style_sheet_list = [
"bootstrap",
"custom-style",
"responsive",
"animate",
"flexslider",
"theme-style"
]
for sheet in style_sheet_list:
with open (DJANGO_ROOT + "/assets/css/" + sheet + ".css", "r") as myfile:
style_sheets+=myfile.read()
style_sheets+="\n"
return style_sheets
template:
<style type="text/css">{{ style_sheets }}</style>
But it only gets down to half way through the animate.css before cutting off and just adding "..."
What limit am I hitting here? How can I solve it?
This is roughly what I'm trying to do:
def post(request):
VehicleFormSet = formset_factory(StaffVehicleForm)
if request.method == 'POST':
vehicle_formset = VehicleFormSet(request.POST)
if 'add_vehicle' in request.POST:
if vehicle_formset.is_valid():
form_count = vehicle_formset.total_form_count()
vehicle_formset.forms.append(vehicle_formset._construct_form(form_count))
Basically, if a user clicks the "Add" button and their entry is valid, I want to add another blank form to the formset, and hide the previous one.
The problem with the code above is that I can't figure out how to increase total_form_count(). The way I have it now, it will work once, and then if you press it again, nothing will happen, presumably because form_count is the same. I also don't like calling _construct_form and relying on the internals.
class RequiredFormSet(BaseFormSet):
def add_form(self, **kwargs):
# add the form
tfc = self.total_form_count()
self.forms.append(self._construct_form(tfc, **kwargs))
self.forms[tfc].is_bound = False
# make data mutable
self.data = self.data.copy()
# increase hidden form counts
total_count_name = '%s-%s' % (self.management_form.prefix, TOTAL_FORM_COUNT)
initial_count_name = '%s-%s' % (self.management_form.prefix, INITIAL_FORM_COUNT)
self.data[total_count_name] = self.management_form.cleaned_data[TOTAL_FORM_COUNT] + 1
self.data[initial_count_name] = self.management_form.cleaned_data[INITIAL_FORM_COUNT] + 1
def add_fields(self, form, index):
super(RequiredFormSet, self).add_fields(form, index)
form.empty_permitted = False
That will do it. Only took 7 hours to figure out. And I still don't know why I need .is_bound = False to make the initial values not screw up.
I do this using javascript. Since the formset renders three management fields
<input type="hidden" id="id_TOTAL_FORMS" value="1" name="TOTAL_FORMS">
<input type="hidden" id="id_INITIAL_FORMS" value="1" name="INITIAL_FORMS">.
<input type="hidden" id="id_MAX_NUM_FORMS" name="MAX_NUM_FORMS">
you can use javascript to increment the id_TOTAL_FORMS value, and just add in the extra fields. So I'd create my fieldset like this:
VehicleFormSet = modelformset_factory(StaffVehicleForm, extra = 0, max_num = None)
The tricky thing is to create the extra form fields in javascript. I usually use AJAX to fetch a new row from a custom view.
For posterity here is another way which works without JS (or alongside JS) and which does not require intimate knowledge of formset methods. Instead, you can just inspect the POST data and adjust it as if JS had done some work client-side. The following makes sure that there is always (at least) one empty form at the end of the formset:
def hsview( request):
HS_formset = formset_factory( HSTestForm, extra=3 )
prefix='XYZZY'
testinpost, empty = 'key', '' # field in the form and its default/empty value
extra=3
# I prefer to do the short init of unbound forms first, so I invert the usual test ...
if request.method != 'POST':
formset = HS_formset( prefix=prefix)
else:
# process POSTed forms data.
# pull all relevant things out of POST data, because POST itself is not mutable
# (it doesn't matter if prefix allows in extraneous items)
data = { k:v for k,v in request.POST.items() if k.startswith(prefix) }
#if there are no spare empty forms, tell it we want another form, in place of or extra to client-side JS
#don't want to crash if unvalidated POST data is nbg so catch all ...
try:
n = int( data[ prefix + '-TOTAL_FORMS'])
test = '{}-{}-{}'.format(prefix, n-1, testinpost)
#print(test)
test = data.get( test, empty)
except Exception:
test = 'bleagh'
# log the error if it matters enough ...
if test != empty:
data[ prefix + '-TOTAL_FORMS'] = n + 1
# now the usual formset processing ...
formset = HS_formset( data, prefix=prefix)
# other_form = OtherForm( request.POST)
if formset.is_valid():
...
I use RegEx in my Vue.js method:
addForm: function () {
this.count++
let form_count = this.count
form_count++
let formID = 'id_form-' + this.count
incremented_form = this.vue_form.replace(/form-\d/g, 'form-' + this.count)
this.formList.push(incremented_form)
this.$nextTick(() => {
let total_forms = document.getElementsByName('form-TOTAL_FORMS').forEach
(function (ele, idx) {
ele.value = form_count
})
})
},
delForm: function () {
if (this.count != 0) {
this.count--
let form_count = this.count
form_count++
let formID = 'id_form-' + this.count
this.formList.pop()
this.$nextTick(() => {
let total_forms = document.getElementsByName('form-TOTAL_FORMS').forEach
(function (ele, idx) {
ele.value = form_count
})
})
}
else return
},