mathematical function and django connect

208 views
Skip to first unread message

Xristos Xristoou

unread,
Feb 9, 2016, 2:47:30 PM2/9/16
to Django users
hello,


i create some python mathematical function on python idle,
i want to create website where the user import value numbers on the function
and take the results from that.
question one,how to connect my mathematical function on the django?
question two,how to connect input and output from the scipts in the website ?
the second question i ask because input and output from the function is a dynamic define from the user



Sergiy Khohlov

unread,
Feb 9, 2016, 3:15:36 PM2/9/16
to django-users
Add regext to the  url.py and  view function to it
Add function to the view.py accepted  function values from  request object and return  value of  your functions
Create template  which few input values field and shown result

Many thanks,

Serge


+380 636150445
skype: skhohlov

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b9267697-b28e-4a03-af7c-88fd384cc72b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 9, 2016, 3:41:02 PM2/9/16
to Django users
what is regext?

Fabio C. Barrionuevo da Luz

unread,
Feb 9, 2016, 3:49:35 PM2/9/16
to django...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.



--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

Message has been deleted

Xristos Xristoou

unread,
Feb 9, 2016, 4:22:31 PM2/9/16
to Django users
yeah my bad for the regext i know that with the full name btw,form its not nesecery to create ?
my task is to copy paste my code in the view,create the regext,and connect on my templete ?only just ?

Fabio C. Barrionuevo da Luz

unread,
Feb 9, 2016, 4:31:13 PM2/9/16
to django...@googlegroups.com
these questions will be answered with the knowledge that you acquire after after completing the official tutorial:

https://docs.djangoproject.com/en/1.9/intro/

and additionally, perhaps :

http://masteringdjango.com/introduction/

or

http://www.tangowithdjango.com/book17/



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 9, 2016, 5:43:42 PM2/9/16
to Django users

THNX for response but that toturial not answer on my questions

Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 9, 2016, 10:20:16 PM2/9/16
to django...@googlegroups.com
I think you want to show  a form with a text input where the user could insert some input eg. math equation to sent to the server. In the server you what to get the input and use it in the standard input of your script, in your script you made what you want (included input validation)  finally the view sent to template the standard output of your script.


If it is something like that you need to used popen  to call your script or used a linux pipe to connect programs or other approach if you script is in Python
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f42b86ac-3fc5-4336-b9f7-dc950d069702%40googlegroups.com.

> For more options, visit https://groups.google.com/d/optout.
>

--
"La utopía sirve para caminar" Fernando Birri



Xristos Xristoou

unread,
Feb 10, 2016, 8:02:03 AM2/10/16
to Django users
yes i want this and work with python list for input and output


Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 10, 2016, 1:09:23 PM2/10/16
to django...@googlegroups.com
Someting like


def myview(request):
    dev = mymathfunc(request. POST.get_list('mi_input', []))

    return render(request, 'mytemplate.HTML', {'result': dev})


I am not sure if get_list it is a valid function, I know there is one that do the same, but can't remember how is called.

If you can give us an example maybe a better answer we will give you
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b933ec93-1d35-466e-86c7-b5cafde824d2%40googlegroups.com.

Xristos Xristoou

unread,
Feb 10, 2016, 1:18:00 PM2/10/16
to Django users
i dont know how to start to give you an example,is confused i am newmbie and i dont find anythink on the internet


Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 10, 2016, 1:34:10 PM2/10/16
to django...@googlegroups.com
OK, start with writing a view

https://docs.djangoproject.com/en/1.9/intro/tutorial03/

Show something funny in your HTML and when you be able to see in your browser let me know.



El miércoles, 10 de febrero de 2016, Xristos Xristoou <sax...@gmail.com> escribió:
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f07df36a-3a85-4a1b-a8d8-deba7dc9e9ff%40googlegroups.com.

Xristos Xristoou

unread,
Feb 10, 2016, 2:49:28 PM2/10/16
to Django users
for example:
myscipt
that my input for example the user define the number to want for input and next input integer numbers on the list(NList) that list go to progress and exported one variable result outpout and list of variables results. i dont upload the progress code because i think not is nesecery for my questions.

total_inputs= int(input("number of numbers to input: "))
   for i in range (total_inputs)
    Num = input("Enter a number: ")
    NList.append(int(Num))
    ..................................
    progress
    .................................
    result1=result
    result2=listresult
    print(result1)
    print(result2)

Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 10, 2016, 3:48:43 PM2/10/16
to django...@googlegroups.com
Maybe you need to refactor your script, I suggest you something like this:


def my_math_func(your_input):
    your_input = your_input.replace(" ", "") # prevent "1, 2"
    list_input = [int(x) for x in your_input.split(",")] # others comprobations could be do
    list_output = []

    for x in list_input:
        ...
        progress
        ...

        result1=result
        result2=listresult
        list_output.append(
               ( str(result1), str(result1) ),
        )
    return list_output
   
if __name__ == "__main__":
    your_input = input("Insert a list of number sepatated by ,")
    print(my_math_func(your_input))

If you see now you have and script that could be called by terminal and the function could be used in a django view

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 10, 2016, 4:22:22 PM2/10/16
to Django users
if i dont want refactor my scipt,and use this
def my_math_func(input1,input2):
      my code
     return list_output,output

is that correct ?


Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 10, 2016, 5:04:34 PM2/10/16
to django...@googlegroups.com
It's correct.

A recomendation
Try to get out all input() from the function, because django is a server side so user don't have a standard input.

 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 10, 2016, 5:12:26 PM2/10/16
to Django users

THNX for response to help me,two questions,how to import list input on my def math(input,listinput) how to define this ?
now i dont have model,on my html template how to connect on my scipt ?


Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Luis Zárate

unread,
Feb 10, 2016, 5:43:38 PM2/10/16
to django...@googlegroups.com
I repeat you again

OK, start with writing a view

https://docs.djangoproject.com/en/1.9/intro/tutorial03/

Show something funny in your HTML and when you be able to see in your browser let me know.

How to do that, see the tutorial, basically this are the steps

create a django app   (python manager.py startapp mathapp)
set mathapp in INSTALLED_APPS in settings.py
Setup urls.py to link the view
create a view in views.py
create a template for example mytemplate.html in a folder called "templates" inside mathapp

See my others email I send you example code that could help.

Don't think in your math function right now later I will help you to connect django view with python math function.

When you have  a view share your code here.



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 15, 2016, 10:52:57 AM2/15/16
to Django users
after read your toturial from the django docs and next page from the django docs
i think so my python code is wrong to get in views.py, i think so get in form

Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

James Schneider

unread,
Feb 15, 2016, 12:32:21 PM2/15/16
to django...@googlegroups.com
On Tue, Feb 9, 2016 at 11:47 AM, Xristos Xristoou <sax...@gmail.com> wrote:
hello,


i create some python mathematical function on python idle,
i want to create website where the user import value numbers on the function
and take the results from that.

Usually this is done through a form. You can either have the user provide the necessary values directly in input fields, or have the user upload a file containing the information that your view will parse.
 
question one,how to connect my mathematical function on the django?

Normally you would have the function on your path and import it for use within your view. Nothing fancy required.
 
question two,how to connect input and output from the scipts in the website ?

Generally your 'script' containing your math functions would not run separately, rather they would be imported directly and run as part of the same process that is running Django. You would add the necessary 'from foo import bar' statements to grab the functions you need, and then simply execute the functions from the data that you gathered in the form (or parsed from the uploaded file from the user).

If the mathematical operations will take longer than a few seconds to execute, you should also consider a batch processor to handle performing the calculations in the background and having the user return to a status page where they can check on their jobs. Long-running processes in the web server can easily choke resources for a variety of reasons, whereas a batch processor (such as Celery) is purpose-built to handle such operations.
 
the second question i ask because input and output from the function is a dynamic define from the user

Gathering dynamic data is the entire purpose of forms. If all data from the user was static, we'd never need to gather information from them. Complete the tutorial project if you haven't done so, and that should become clear.
 
-James

Luis Zárate

unread,
Feb 16, 2016, 2:15:16 PM2/16/16
to django...@googlegroups.com

What is wrong in your code?

I suggested you some scripts changes that allows import and use in views.

Help us to help you, give us more information about what are you doing, what are you planning to do? Why you think you code is wrong?.

Did you create the view as I suggested?

I think you need to do this steps.

1. Create a django view with some HTML template
2. Create a form ( search for django forms)
3. Insert the form in the HTML template
4. Validate and extract the data inside forms ( it is easy using django forms)
5. Format the data for use in mathematic function (send data to script in the correct way )
6. Get data from script
7. Insert the data into template context
8. Render in HTML the data in the HTML template
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f4806da4-886f-4562-8e46-4633693b333e%40googlegroups.com.

Xristos Xristoou

unread,
Feb 21, 2016, 1:32:39 AM2/21/16
to Django users
i have a progress with help anyway i am newbie

i convert my python script(remember the first script on the first page) to django script on the view

views.py:

from django.shortcuts import render_to_response
def calc(request):
a = []
NList = []
y=0
nums = request.POST['num']
total_inputs = request.POST['total']
for i in range(total_inputs):
NList.append(int(num) for num in nums.split(','))
for k in NList:
if k is 1:
y = 1
elif (k > 1) and (k < 5):
y = (k - 1) + 2
a.append(y)
return render_to_response('blog/calc.html', {
'a' :a,
})

app/urls:

urlpatterns = [
url(r'^$',views.calc, name='calc'),
]

html form:

<form action="" method="POST">
Number of number: <input type="text" name="num" value="Number">
Enter a value: <input type="text" name="total" value="Total value">
<button type="submit" value="Submit">
</form>

and i take that error

MultiValueDictKeyError at /

"'num'"
  1.  nums = request.POST['num']

Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

Xristos Xristoou

unread,
Feb 21, 2016, 2:33:05 AM2/21/16
to Django users
i find solution for that error

if i change request to :

if 'nums' in request.POST:
nums = request.POST['nums']
else:
nums = False


now i have else error and i think the code in my html form is wrong (inside the form i copy paste {% csrf_token %}) and again nothing

Forbidden (403)

CSRF verification failed. Request aborted

Help

Reason given for failure:

    CSRF token missing or incorrect.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function passes a request to the template's render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.



Τη Τρίτη, 9 Φεβρουαρίου 2016 - 9:47:30 μ.μ. UTC+2, ο χρήστης Xristos Xristoou έγραψε:

James Schneider

unread,
Feb 21, 2016, 2:34:28 AM2/21/16
to django...@googlegroups.com
You're likely getting this error because request.POST['num'] is empty (wasn't submitted via the form). With the way that your view is written, this error will occur if you are using that view to display the initial blank form. As of now, you can only use that view as the action= target for the form. 

request.POST is a Django QueryDict with keys for each field in the form. 


When accessing fields in request.POST, usually you use something like request.POST.get('num') so that an error isn't thrown, and instead returns None. If a form field can contain multiple values, you would need to call .get() multiple times in a loop.


Otherwise it seems like you are getting closer.

-James




James Schneider

unread,
Feb 21, 2016, 2:44:48 AM2/21/16
to django...@googlegroups.com
On Sat, Feb 20, 2016 at 11:33 PM, Xristos Xristoou <sax...@gmail.com> wrote:
i find solution for that error

if i change request to :

if 'nums' in request.POST:
nums = request.POST['nums']
else:
nums = False


now i have else error and i think the code in my html form is wrong (inside the form i copy paste {% csrf_token %}) and again nothing

Forbidden (403)

CSRF verification failed. Request aborted

Where did you place the {% csrf_token %} in your template? It needs to sit anywhere in between your <form></form> tags. If it is outside of the <form> tags, it will have no effect.

You should also look at the source code of the page inside of the browser and make sure that is a hidden form element named csrf_token with a value of a random string, to ensure it is being generated properly.


-James

Xristos Xristoou

unread,
Feb 21, 2016, 2:50:35 AM2/21/16
to Django users
place csrf on my code 

<form action="" method="POST">{% csrf_token %}
Number of number:
<input type="text" name="nums" value="Number">
Enter a value: <
input type="text" name="total_inputs" value="Total value">
<
button type="submit" value="Submit">
</
form>

and the background color from input is a differend and i take that message 

This inspection highlights form elements without required associated label (WCAG 2.0: H44) or title attribute (WCAG 2.0: H65) and provides the ability to create a new label or add an attribute.

James Schneider

unread,
Feb 21, 2016, 2:58:04 AM2/21/16
to django...@googlegroups.com
On Sat, Feb 20, 2016 at 11:50 PM, Xristos Xristoou <sax...@gmail.com> wrote:
place csrf on my code 

<form action="" method="POST">{% csrf_token %}
Number of number:
<input type="text" name="nums" value="Number">
Enter a value: <
input type="text" name="total_inputs" value="Total value">
<
button type="submit" value="Submit">
</
form>

and the background color from input is a differend and i take that message 

This inspection highlights form elements without required associated label (WCAG 2.0: H44) or title attribute (WCAG 2.0: H65) and provides the ability to create a new label or add an attribute.


I'm assuming that last line is something from your editor. Your CSRF token appears to be in the right spot. The only other note I would have without other information is that your first form input is named "nums", but your view is looking for "num".  

-James

Xristos Xristoou

unread,
Feb 21, 2016, 3:12:16 AM2/21/16
to Django users
yes i see that and fix it but not work again

Xristos Xristoou

unread,
Feb 21, 2016, 11:57:41 PM2/21/16
to Django users
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.

Luis Zárate

unread,
Feb 22, 2016, 12:19:17 AM2/22/16
to django...@googlegroups.com
use render instead of render_to_response

from django.shortcuts import render


 return render(request, 'blog/calc.html', {
        'a' :a,
        })


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Xristos Xristoou

unread,
Feb 22, 2016, 12:33:09 AM2/22/16
to Django users
i find it,just add return render_to_response('blog/calc.html', {'a' :a},context_instance=RequestContext(request))
and dont show me that error,but not work again
now if i touch calc button just reload dont show me error dont show me results only clear numbers why ?

<form action="" method="POST">{% csrf_token %}
  Number of number: <input type="text" name="num" value="Number"/>
Enter a value: <input type="text" name="total_input" value="Total value"/>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">calc</button>
</div>
</form>
<p>
<div>
{{ a }}
or full info
{% for sm in a%}
{{ sm }}
{% endfor %}
</div>
</p>

James Schneider

unread,
Feb 22, 2016, 3:32:35 AM2/22/16
to django...@googlegroups.com
On Sun, Feb 21, 2016 at 9:33 PM, Xristos Xristoou <sax...@gmail.com> wrote:
i find it,just add return render_to_response('blog/calc.html', {'a' :a},context_instance=RequestContext(request))
and dont show me that error,but not work again
now if i touch calc button just reload dont show me error dont show me results only clear numbers why ?


Not sure what you mean by 'clear numbers'. Are saying that the results are being shown, but not styled in any way? 
 
<form action="" method="POST">{% csrf_token %}
Number of number: <input type="text" name="num" value="Number"/>
Enter a value: <input type="text" name="total_input" value="Total value"/>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">calc</button>
</div>
</form>
<p>
<div>
{{ a }}
or full info
{% for sm in a%}
{{ sm }}
{% endfor %}
</div>
</p>


If you have multiple values in 'a', then it will show all of those values on a single line separated by spaces, I believe. In fact, it will likely show them twice since you have {{ a }} and a {% for %} loop running through 'a'. 

You'll have to add your own HTML styling within your template if you want them to look different in the browser.

-James 

Xristos Xristoou

unread,
Feb 22, 2016, 3:08:16 PM2/22/16
to Django users
the problem in the html form we need to change second input to take multiple values,for example first input take a number
and the second input take many numbers..if the first number = 2 then take second input two numbers,two fields for input i try this but not work

orm action="" method="POST">{% csrf_token %}
  Number of number: <input type="integer" name="total_inputs" value="Number"/>
  <button type="submit" class="btn btn-default">calc</button>
  {% for i in total_inputs %}
             Enter a value: <input type="integer" name="num" value="Total value"/>
            <button type="submit" class="btn btn-default">calc</button>
  {% endfor %}
</form>
show me error in the {% for i in total_inputs %}

James Schneider

unread,
Feb 23, 2016, 5:35:13 PM2/23/16
to django...@googlegroups.com
On Mon, Feb 22, 2016 at 12:08 PM, Xristos Xristoou <sax...@gmail.com> wrote:
the problem in the html form we need to change second input to take multiple values,for example first input take a number
and the second input take many numbers..if the first number = 2 then take second input two numbers,two fields for input i try this but not work

orm action="" method="POST">{% csrf_token %}
  Number of number: <input type="integer" name="total_inputs" value="Number"/>
  <button type="submit" class="btn btn-default">calc</button>
  {% for i in total_inputs %}
             Enter a value: <input type="integer" name="num" value="Total value"/>
            <button type="submit" class="btn btn-default">calc</button>
  {% endfor %}
</form>
show me error in the {% for i in total_inputs %}


Why would you ask how many values that a user is going to provide? Why not just count them after the user provides them? Are they providing them in a single input, or are you trying to add multiple input fields, one for each number?

For a workflow like that, you should probably look at django-formtools, which includes form wizards for multi-page forms (page 1 asks how many values, page 2 provides X number of fields inputs given on page 1, etc.). Or you need to amend the form dynamically using JavaScript. That gets really tricky though.

Is this math formula something you can convert to JavaScript and perform entirely in the client browser? I would go that route and not even bother with trying to have Django process the forms and compute a result.

-James

Xristos Xristoou

unread,
Feb 28, 2016, 5:06:41 PM2/28/16
to Django users
update my project now

my view.py code

def calc(request):
a = []
NList = []
y=0
        member=0
member = request.POST.get ('member', False)
for i in range(int(member)):
input = request.POST.get ('input', False)
NList.append(int(input))

for k in NList:
if k is 1:
y = 1
elif (k > 1) and (k < 5):
y = (k - 1) + 2
a.append(y)
        return render_to_response ('blog/calc.html', {'a' :a, 'member':member}, context_instance=RequestContext(request))

my urls.py
from django.conf.urls import url
from . import views


urlpatterns = [
url(r'^$',views.calc, name='calc'),
]
html code with the javascript
<body>
<form action="" method="post" name="detParameterForm">{% csrf_token %}
<fieldset class="det">
<legend>Closure Level</legend>
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
</fieldset>
<button type="submit" value="Submit">submit</button>
</form>
<script>
function addinputFields(){
// Disable Default Action (Form Posting)
event.preventDefault();
// parseInt() - The value entered should be a number / integer
var number = parseInt(document.getElementById("member").value);
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
</script>
<p>

{{ a}}
or full info
{% for sm in a %}
{{ sm }}
{% endfor %}
</p>
</body>

but not work again show me zero results,any idea ?

James Schneider

unread,
Feb 29, 2016, 6:52:35 PM2/29/16
to django...@googlegroups.com
On Sun, Feb 28, 2016 at 2:06 PM, Xristos Xristoou <sax...@gmail.com> wrote:
update my project now

my view.py code

def calc(request):
a = []
NList = []
y=0
member=0
member = request.POST.get ('member', False)
for i in range(int(member)):
input = request.POST.get ('input', False)
NList.append(int(input))
for k in NList:
if k is 1:
y = 1
elif (k > 1) and (k < 5):
y = (k - 1) + 2
a.append(y)
return render_to_response ('blog/calc.html', {'a' :a, 'member':member}, context_instance=RequestContext(request))


Have you verified that 'member' and 'input' are populated with values when the form is submitted? You should be able to put print() statements at various points in your code and watch the output on the dev server console. You should also check that the 'a' variable is populated just before it is placed into the context. 

Also, be careful using input as a variable name. That clashes with the input() function in Python 3. 

-James
Message has been deleted

James Schneider

unread,
Mar 3, 2016, 8:02:00 PM3/3/16
to django...@googlegroups.com


On Thu, Mar 3, 2016 at 10:48 AM, Xristos Xristoou <sax...@gmail.com> wrote:
update my code khow i feel so close but not work again hahaha to many problems

. I want to write a django code which takes a number and a list of numbers from the website as user input and and then export a list with results. but if i run my app don't show me results from the progress in html template, i can only input details if i push second button just reload the page and not show me results.

I have written following code but it doesn't show me the results:

views.py

def calc(request):
        NList=[]
        num=0
        a=[]
        y=0
        c=0
        total=0
        num = request.POST.get ('num', False)
        if request.method=='POST' and 'btnform1' in request.POST:
            b='1'.zfill(int(num))
            e=b[::-1]
            c=int(e)
            #num=int(num)
        if request.method=='POST' and 'btnform2' in request.POST:
         for i in range(int(num)):
             total = request.POST.get ('total', False)
             NList.append(int(total))
         for k in NList:
                if k == 1:
                    y=1

                elif (k > 1) and (k < 5):

                    y = k+1000
                a.append(y)

        return render_to_response ('blog/calc.html', {'a' :a,'num':num,'c':c,'y':y,'total':total,'NList':NList},context_instance=RequestContext(request))

html form

form id="form1" action="" method="POST">{% csrf_token %}
<div>

  Number of number: <input type="text" name="num" value="Number"/>

    <div>
    <button type="submit" name="btnform1">count</button>
        </div>
</div>
    <p>
    {{num}}
    </p>
</form>
<form id="form1" action="" method="POST">{% csrf_token %}
<div>
    {% for i in c|make_list %}

  Enter a value: <input type="text" name="total" value="Total value">

    {% endfor %}
<div>
    <button type="submit" name="btnform2">final</button>
    </div>
</div>
</form>

<p>
 {{ a}}
or full info
{% for sm in a %}
    {{ sm }}
{% endfor %}
</p>

urls.py

url(r'^$',views.calc, name='calc'),

this is a example if if the first input is num=4 then the script create 4 html inputs field(to user input second number list total) but if i click final button dont show me resust(a=output).


It appears to me that the problem is with the fact that you have two forms on your page, but your view function is expecting values from both forms in order to generate the results you want.

You can either a) only have a single form that is rebuilt per each step with the additional fields you need or b) refactor your view code. 

         for i in range(int(num)):
             total = request.POST.get ('total', False)
             NList.append(int(total))

Your problem in the view is that your loop relies on int(num), but the 'num' variable will be set to False when you click the 'final' button, because it is not sent as part of that form (ie request.POST.get('num') returns False), and so your loop will never run. In reality, you don't even need the 'num' variable, just query the 'total' fields:

for total in request.POST.getlist('total'):
    NList.append(int(total))

getlist() should return an empty list if 'total' is not available, so it should still work on initial page loads before the user specifies the number of fields they need, etc.

Also keep in mind that you are dealing with POST variables directly, with no validation that you would get from a true Django Form() object, and there is no error checking in your code either, so someone submitted 'four' instead of '4' would cause your code to throw an exception. Using a real Django form would help validate that case and provide error-handling to re-display the form in the users' browser.

-James
Reply all
Reply to author
Forward
0 new messages