Django calling an another function inside from a view function - python

The views.py somthing like this
def getFormValues(request):
if ('mobile_a' in request.GET and request.GET['mobile_a']) and ('mobile_b' in request.GET and request.GET['mobile_b']):
mobile_a = request.GET['mobile_a']
mobile_b =request.GET['mobile_b']
# calling the mark calculation function
return calculateMark(mobile_a, mobile_b)
else:
message ='You submitted an empty form.'
return HttpResponse(message)
Here I am calling a function(calculateMark) which will calculate a marking. In the end of the calculateMark function I have something like this
if (tech_mark_a == 0 and tech_mark_b == 0):
mobile_a_infos = TechSpecificationAdd.objects.filter(tech_variables)
return render_to_response('degrees_result.html', {'mobile_a': tech_mark_a, 'mobile_b': mobile_b}, mobile_a_infos)
elif (tech_mark_a > 0 and tech_mark_b > 0):
return render_to_response('degrees_result.html', {'mobile_a': tech_mark_a, 'mobile_b': mobile_b})
The Problem is when I am submitting an empty form It's showing the message as getFormValues(). But when I submit something on the form it's showing an error The view MarkCalculation.views.getFormValues didn't return an HttpResponse object.
How can I solve the problem? Thanks in advance.

Fix your calculateMark() function so that it doesn't have any code paths that don't return a response. Also, consider converting the arguments to numbers first.

Related

How to get a serie of request.POST values

In the following views.py:
def valores(request):
global peso_unitario, preco_unitario
peso_unitario=[]
preco_unitario=[]
N=a
print('N='+str(N))
for i in range(N):
peso_u=request.POST['peso_u']
preco_u=request.POST['preco_u']
if peso_u.isdigit() and preco_u.isdigit():
c = int(peso_u)
d = int(preco_u)
peso_unitario.append(c)
preco_unitario.append(d)
print(a)
print(preco_unitario)
if i<N-1:
return render(request, 'valores.html')
else:
return render(request, 'pacote.html',
{'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario})
else:
res = 'Apenas numero.'
return render(request, 'pacote.html', {'res': res})
I have a function that receives a global value N=a, this value was received from the user, now I need to receive N times the both values in request.POST loop, but each time the user needs to enter the values. I don't know how to do this.
This is your python code, as per your problem you need to make a loop in your template to take input from user N times or maybe take values of peso_u and preco_u in a list whose length must be equal to N here.

Python Flask Redirect

def check():
if 3>2:
return redirect(url_for('control'))
#app.route('/reason', methods=['GET','POST'])
def reason():
check()
return render_template('reason.html')
#app.route('/control', methods=['GET','POST']
def control():
return render_template('control.html')
I have two html files (control.html and reason.html). the code loads reason.html page first and receives user input using POST method then after doing certain checks, I want to reload control.html.
the problem is I am not able to load control.html
You are ignoring the return value from check(). Consequently, the object that will signal a redirect is simply lost.
You should inspect the return value from check() and either return that result, or the 'reason.html' result:
# UNTESTED
#app.route('/reason', methods=['GET','POST'])
def reason():
check_result = check()
if check_result:
return check_result
return render_template('reason.html')
On a related note, your check() has two return paths. One explicitly invokes return, the other implicitly returns None as it falls off the end of the function. This is perfectly legal, but confusing stylistically. Try this:
def check():
if 3>2:
return redirect(url_for('control'))
return None
Perhaps a more understandable code arrangement would be to have check limit its responsibilities to simply checking and reporting the result; then reason() can be responsible for whatever page is displayed, like so:
#UNTESTED
def check():
if 3>2:
return True
return False
# UNTESTED
#app.route('/reason', methods=['GET','POST'])
def reason():
if check():
return redirect(url_for('control'))
return render_template('reason.html')

Is it possible to pass httprequest parameter from one view function to another in Django

I am trying to pass Httprequest parameter from one view function to another in Django but it doesn't seem working is it valid to pass the request parameter from one view to another?
def view1(request):
result = view2(request)
return HttpResponse(result)
def view2(request):
html = []
values = request.POST.items()
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k,v))
return (html)
It is possible. And there is no need to assigning it to a variable. Just use:
return view2(request)
I think you are not returning appropriate string for the response. You can update your view as
def view1(request):
result = view2(request)
return HttpResponse(''.join(result))

How to get django form wizard extra_context to show on template?

EDIT: FWIW, I am running django 1.3
I have...
class CreateProductWizard(FormWizard):
def get_template(self, step):
if step == 1:
return 'product/form_wizard/editor.html'
else:
return 'product/form_wizard/wizard_%s.html' % step
def process_step(self, request, form, step):
if step == 1:
self.extra_context = {'ptype': form.cleaned_data}
return
else:
return
def done(self, request, form_list):
# now that it's all together, store it.
return render_to_response('product/form_wizard/done.html',
{'form_data': [form.cleaned_data for form in form_list]},
context_instance=RequestContext(request))
and I'd like to get the self.extra_context to the template.
How do I get that on the template?
I've tried on the template:
{{extra_context}}
{{form.extra_context}}
{{form.extra_context.ptype}}
etc..
Looking at the docs i'd say that get_context_data is what you are after:
Returns the template context for a step. You can overwrite this method
to add more data for all or some steps. This method returns a
dictionary containing the rendered form step.
So what I ended up using on the template was:
{{ptype}}
which I had already tried.
The problem, and I'm still not sure why was that I had:
def process_step(self, request, form, step):
if step == 1:
self.extra_context = {'ptype': form.cleaned_data}
return
else:
return
and what worked was:
def process_step(self, request, form, step):
self.extra_context = {'ptype': 'hello!!',}
For some reason, the 'step' that is being passed to 'process_step()' is always == 0 which made my 'if step ==1:' logic fail...
After reviewing the source (django.contrib.formtools.wizard.FormWizard), one thing that looks like it could be failing on is my form is not valid. It must be valid for the step number to increment and call the process_step function. HOWEVER, the {{step}} variable is getting the right value. And I'm not doing anything crazy with the form...
So weird. But my main question is solved.

django 1.3 forms validation using clean method to retrieve getlist

I have a form with checkboxes, the form functioning well, in my view i can use request.POST.getlist('list') to retrieve the list of values.
At the moment am trying to do some form validation inside the clean method and when i try to use self.cleaned_data['list'] I get the last value. I cannot retrieve the list of items.
Any idea how i could do that?
forms.py
class SelectList_Form(forms.Form):
list = forms.CharField(required=False)
def clean(self):
super(SelectList_Form, self).clean()
cleaned_data = self.cleaned_data
try:
# TODO: list validation
if cleaned_data['list'].__len__() is 0:
raise forms.ValidationError(_('Must select at least one of the lists below'),)
if cleaned_data['list'].__len__() > 1:
try:
# In here when i print list it only shows me the last value. It doesn't show me the list of values when the box is checked
print cleaned_data['list']
except Main.DoesNotExist:
raise Http404
except forms.ValidationError:
raise
class Posting_Wizard(FormWizard):
def render_template(self, request, form, previous_fields, step, context=None):
if step == 0:
obj = MainI18n.objects.filter(main__is_active=True, language=request.LANGUAGE_CODE).\
exclude(main__parent=None).order_by('main__parent').select_related(depth=1)
category_choices=dict(['%s,%s' % (i.main.slug, i.main.parent.slug), '%s - %s' % (i.main.parent,i.label)] for i in obj)
form.fields['categories'] = forms.CharField(widget=forms.RadioSelect(choices=category_choices.items()))
if step == 1:
category = request.POST.get('0-categories')
pobj = Main.objects.filter(slug=category.split(',')[1], parent=None).get()
cobj = Main.objects.filter(slug=category.split(',')[0], parent=pobj.id).get()
lobj = ListI18n.objects.filter(list__is_active=True, language=request.LANGUAGE_CODE, list__main__slug=category.split(',')[0], list__main__parent=pobj.id).select_related()
list_choices = dict([i.id, i.title] for i in lobj)
if cobj.mainproperties.relation == 'M':
# Here i generate the checkboxes
form.fields['list']=forms.CharField(widget=forms.CheckboxSelectMultiple(choices=list_choices.items()),label="Pick the list",)
else:
form.fields['list']=forms.CharField(widget=forms.RadioSelect(choices=list_choices.items()),label="Pick the list",)
return super(Posting_Wizard, self).render_template(request, form, previous_fields, step, context)
def done(self, request, form_list):
return HttpResponseRedirect(reverse('accounts-registration-wizard-done'))
def get_template(self, step):
return 'listing/post/wizard/wizard_%s.html' % step
First, there are a number of basic Python errors here. There is almost never a need to access the double-underscore functions - they are internal implementation details. Always use the normal len() function instead. And, never use is for comparisons: it's for identity, so should only be used with things you know have the same identity, which basically just means None. So your code should read:
if len(cleaned_data['list']) == 0:
etc.
Now, secondly, I don't understand why you think there could ever be more than one 'element' in list. You've defined it as a CharField, which is a single field containing many characters. Your len is testing the number of characters entered into that field, not the number of fields, however you think you've defined them.

Categories

Resources