How to use form values from an unbound form
I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned_data field unless I call is_valid()
. But is_valid()
always fails on unbound forms.
It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML.
For example, if I have:
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
is_valid() will fail if this is a GET (since it's unbound), and if I do:
if request.method == 'GET':
form = MyForm()
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
the first call to do_query triggers exceptions on form.cleaned_data, which is not a valid field because is_valid()
has not been called. It seems like I have to do something like:
if request.method == 'GET':
form = MyForm()
do_query(form['start_date'].field.initial, form['end_date'].field.initial)
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one.
Does anyone see a cleaner way to do this?
Asked by: Tara399 | Posted: 28-01-2022
Answer 1
If you add this method to your form class:
def get_cleaned_or_initial(self, fieldname):
if hasattr(self, 'cleaned_data'):
return self.cleaned_data.get(fieldname)
else:
return self[fieldname].field.initial
you could then re-write your code as:
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.method.POST)
form.is_valid()
do_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date'))
Answered by: Alina865 | Posted: 01-03-2022
Answer 2
Unbound means there is no data associated with form (either initial or provided later), so the validation may fail. As mentioned in other answers (and in your own conclusion), you have to provide initial values and check for both bound data and initial values.
The use case for forms is form processing and validation, so you must have some data to validate before you accessing cleaned_data
.
Answer 3
You can pass a dictionary of initial values to your form:
if request.method == "GET":
# calculate my_start_date and my_end_date here...
form = MyForm( { 'start_date': my_start_date, 'end_date': my_end_date} )
...
See the official forms API documentation, where they demonstrate this.
edit: Based on answers from other users, maybe this is the cleanest solution:
if request.method == "GET":
form = MyForm()
form['start_date'] = form['start_date'].field.initial
form['end_date'] = form['end_date'].field.initial
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
I haven't tried this though; can someone confirm that this works? I think this is better than creating a new method, because this approach doesn't require other code (possibly not written by you) to know about your new 'magic' accessor.
Answered by: Michelle131 | Posted: 01-03-2022Similar questions
class - python unbound method again
This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
print Student.MostFrequent() TypeError: unbound method
MostFrequent() must be called with
Student instance as first argument
(got nothing instead)
This Student.MostFrequent() is called all the way in the end (last line) and the...
python - No such test method / unbound error
I have overridden the unittest.TestCase class to include some additional functionality like this
class TestCase(unittest.TestCase):
def foo(self):
return 4711
which I am going to use in the setUpClass call in a Test Case like this
class MyTest(TestCase):
@classmethod
def setUpClass(cls):
value = cls.foo() #1
value = MyTest.f...
python - Unbound Local Error
I keep getting an unbound local error with the following code in python:
xml=[]
global currentTok
currentTok=0
def demand(s):
if tokenObjects[currentTok+1].category==s:
currentTok+=1
return tokenObjects[currentTok]
else:
raise Exception("Incorrect type")
def compileExpression():
xml.append("<expression>")
xml.append(compileTerm(cu...
python - Why do I get Unbound Local Error?
So the functions in question are very long, so I will summarize it.
def func1( X = None, Y = None ) :
if X :
dostuff
if condition :
Z += 1
if Y :
print Y
func1.Z = 0
def func2( A )
for loop that does stuff and calls func1
When I run this, it tells me that the line Z += 1 has an error "UnboundLocalError: local variable 'Z' referenced before assignment"
...
python - Unbound Local Error I can't solve
I'm trying to build a conversions calculator and I believe I have it correct but I keep getting a
"UnboundLocalError: local variable 'F2C' referenced before assignment"
Does this mean I'm using the wrong key? Or does it mean the order I wrote the functions is the problem?
The beginning section of the code works properly when I ran it but I can't figure out what the error is trying to tell me.
Here...
api - Unbound Local Error python
This question already has answers here:
Python Unbound Method Error
Can someone please correct me on the mistake I have been having trouble with! The problem is that it is not generating a random integer in the Goalie nor Player class. This issue isn't allowing me to actually get both "players" to move.
Error:
import random
def main():
name = raw_input("Name: ")
kick = raw_input("\nWelcome " +name+ " to soccer shootout! Pick a corner to fire at! Type: TR, BR, TL,...
python - Unbound Local Error which i dont know how to fix
def perd():
Personaldetails_file = open("Personaldetails_file.txt", "w")
Personaldetails_file = open("Personaldetails_file.txt", "a")
pd = input("Are you a new user?")
if pd == "yes":
print ("Add your details")
####################################
age = int(input("how old are you?"))
DOB = input("Date of birth:")
gender = input("Gender:")
weight = int(input("weig...
Python Error unbound method?
If I try to run a command from https://github.com/ilovecode1/sandshell.py it gives me the error bellow:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method runsingle() must be called with sandshell instance as first argument (got str instance instead)
Thanks Yo...
python - Getting unbound method error?
I tried to run this code below
class TestStaticMethod:
def foo():
print 'calling static method foo()'
foo = staticmethod(foo)
class TestClassMethod:
def foo(cls):
print 'calling class method foo()'
print 'foo() is part of class: ', cls.__name__
foo = classmethod(foo)
After I ran this with the code below
tsm ...
class - python unbound method again
This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
print Student.MostFrequent() TypeError: unbound method
MostFrequent() must be called with
Student instance as first argument
(got nothing instead)
This Student.MostFrequent() is called all the way in the end (last line) and the...
using unbound methods in another python class
I have an unbound method as <unbound method foo.ops>, i would like to use the same method with another class. take an example
class foo2(object):
pass
foo2.ops = foo.ops
however
obj = foo2()
obj.ops()
raises TypeError: unbound method ops() must be called with foo instance as first argument (got nothing instead)
Can I create a Python Numpy ufunc from an unbound member method?
I would like to use numpy.frompyfunc to generate an unbound ufunc from an unbound member method. My concrete but failing attempts look like
class Foo(object):
def f(x,y,z):
return x + y + z
Foo.g = numpy.frompyfunc(Foo.f,3,1)
i = Foo()
i.g(5,6,7)
where the last line fails with
"TypeError: unbound method f() must be called with Foo instance as first argument (got int instance ...
python - Unbound method error while calling static method
I have a class with two methods in it, one static and another none static:
class Person(object):
def getDetails(self):
Person.change_something(self.name)
@staticmethod
def change_something(name):
return name.upper()
When I create an instance of a class Person and call person.getDetails(), I am getting error that says unbound method change_so...
python - No such test method / unbound error
I have overridden the unittest.TestCase class to include some additional functionality like this
class TestCase(unittest.TestCase):
def foo(self):
return 4711
which I am going to use in the setUpClass call in a Test Case like this
class MyTest(TestCase):
@classmethod
def setUpClass(cls):
value = cls.foo() #1
value = MyTest.f...
python - unbound method when using type builtin to create a dynamic object
I have this code:
class X(object):
x = 10
def test_x(self):
return self.x
class Y(X):
def test_y(self):
return self.x
y = Y()
y.test_y() # works fine
But when I construct a new object z based on X using type :
z = type('Z', (X,), dict(z=1))
z.x # works fine
z.test_x() # gives a TypeError :
unbound method...
python - Unbound Local Error
I keep getting an unbound local error with the following code in python:
xml=[]
global currentTok
currentTok=0
def demand(s):
if tokenObjects[currentTok+1].category==s:
currentTok+=1
return tokenObjects[currentTok]
else:
raise Exception("Incorrect type")
def compileExpression():
xml.append("<expression>")
xml.append(compileTerm(cu...
Why does id() of an unbound method in Python 2 change for every access
Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21)
[GCC 4.4.3]
>>> class myclass:
... def func(self):
... pass
>>> dd = myclass.func
>>> ee = myclass.func
>>> cc = myclass.func
>>> ff = myclass.func
>>> ss = myclass.func
>>> uu = myclass.func
>>> pp = myclass.func
>>>
>>>
>>> id(dd) ; id(cc) ...
python - Why do I get Unbound Local Error?
So the functions in question are very long, so I will summarize it.
def func1( X = None, Y = None ) :
if X :
dostuff
if condition :
Z += 1
if Y :
print Y
func1.Z = 0
def func2( A )
for loop that does stuff and calls func1
When I run this, it tells me that the line Z += 1 has an error "UnboundLocalError: local variable 'Z' referenced before assignment"
...
Python unbound local error on one machine but not on another
I get "UnboundLocalError: local variable 's' referenced before assign" in python script on one machine but not on another where the script runs OK. Both machines are on Windows 7 and use Python 2.7.3. Any suggestions what could be the reason for this behaviour? Thank you.
Here's the code that causes the error:
with open(self.temp_dir + test + ".log",'r') as log:
for line in log:
if "INPUT_...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python