Electronics & Programming

develissimo

Open Source electronics development and programming

  • You are not logged in.
  • Root
  • » Django
  • » Custom form where fields in Form do not match Model [RSS Feed]

#1 March 7, 2008 05:59:36

Michael L.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Custom form where fields in Form do not match Model


Hi all

I'm having problems in saving a custom form. The form presents list of
choices for a
user. In the model the choices are stored single string field
'choices'. But in my
form I wish to present a list of choices and concatenate them together
to save into
the model.
- Hence the model has 'choices'.
- The Form will have choice1, choice2 etc (probably up to several choices).
The code below is simplified with much cruft removed.

In forms.py I have:

class AddDecisionForm(forms.Form):

choice1 = forms.CharField(label='choice1', required=False)
choice2 = forms.CharField(label='choice2', required=False)

enumerated-choices =
if choice1:
enumerated-choices.append(choice1)
if choice2:
enumerated-choices.append(choice2)
etc....

# Include this here so the form has the field that can be saved to
the model.
choices = forms.CharField(initial='1,2', required=False,
widget=forms.HiddenInput)

def save(self):
d = Decision(**self.cleaned_data)
d.choices = str(enumerated_choices)
d.save()

The above basically outlines "what" I want to do but does not work.

In my views.py I have:

if request.method == 'POST':
if request.POST == 'Add':
form = AddDecisionForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("%s/planner/decision/list/" % root)
else:
# TODO

I'm getting an error when I click Add.
"TypeError at /planner/decision/add/
'choice1' is an invalid keyword argument for this function.

I have read overhttp://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validationandhttp://www.b-list.org/weblog/2007/nov/23/newforms/But still having problems working how how to clean this form data. I
understand that I need to probably do some processing in a clean
method to concatenate the choice1 etc values to choices but maybe even
use del self.base_fields etc somehow to remove them from
the form before it validates?
I'm just really confused.

Mike
--
Michael Lake
Caver, Linux enthusiast & interested in most things technical.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
For more options, visit this group athttp://groups.google.com/group/django-users?hl=en-~----------~----~----~----~------~----~------~--~---

Offline

#2 March 7, 2008 12:27:19

Malcolm T.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Custom form where fields in Form do not match Model


On Fri, 2008-03-07 at 16:59 +1100, Michael Lake wrote:

> In forms.py I have:
>
> class AddDecisionForm(forms.Form):
>
> choice1 = forms.CharField(label='choice1', required=False)
> choice2 = forms.CharField(label='choice2', required=False)
>
> enumerated-choices =
> if choice1:
> enumerated-choices.append(choice1)
> if choice2:
> enumerated-choices.append(choice2)
> etc....
>
> # Include this here so the form has the field that can be saved to
> the model.
> choices = forms.CharField(initial='1,2', required=False,
> widget=forms.HiddenInput)
>
> def save(self):
> d = Decision(**self.cleaned_data)
> d.choices = str(enumerated_choices)
> d.save()
>
> The above basically outlines "what" I want to do but does not work.


> I'm getting an error when I click Add.
> "TypeError at /planner/decision/add/
> 'choice1' is an invalid keyword argument for this function.

It is fairly important when reporting an error like this that you give
enough information to indicate where the error is coming from. That is
why Python gives you a full traceback. You've done the equivalent of
reporting "somebody has been hit by a car" without giving the street
address.

Guessing a lot here (it looks like there's only one place "choice1"
could be being used as a keyword argument), I suspect you'll find the
problem is related to this line in your view:

d = Decision(**self.cleaned_data)

Since your form has fields 'choice1' and 'choice2', this will be
equivalent to a call to

Decision(choice1=..., choice2=..., choices=...)

and I'll wager that your Decision model doesn't have fields of that
name. Remember that the cleaned_data dictionary contains one key for
each field in your form. So if they don't map exactly onto the field
names for your model (with no extras -- it's not going to magically read
your mind and decide you didn't mean to pass in choice1 and choice2),
you'll need to manually map from the cleaned_data entries to the
keywords to pass to the Decision constructor.

Regards,
Malcolm


>
> I have read over
>http://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validation> andhttp://www.b-list.org/weblog/2007/nov/23/newforms/> But still having problems working how how to clean this form data. I
> understand that I need to probably do some processing in a clean
> method to concatenate the choice1 etc values to choices but maybe even
> use del self.base_fields etc somehow to remove them from
> the form before it validates?
> I'm just really confused.
>
> Mike
--
On the other hand, you have different fingers.http://www.pointy-stick.com/blog/--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
For more options, visit this group athttp://groups.google.com/group/django-users?hl=en-~----------~----~----~----~------~----~------~--~---

Offline

#3 March 8, 2008 11:49:18

s.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Custom form where fields in Form do not match Model


Hi

On Mar 7, 11:26 pm, Malcolm Tredinnick <>
wrote:
> It is fairly important when reporting an error like this that you give
> enough information to indicate where the error is coming from.
...
Sorry. See at bottom.

> Guessing a lot here (it looks like there's only one place "choice1"
> could be being used as a keyword argument), I suspect you'll find the
> problem is related to this line in your view:
>
> d = Decision(**self.cleaned_data)
>
> Since your form has fields 'choice1' and 'choice2', this will be
> equivalent to a call to
>
> Decision(choice1=..., choice2=..., choices=...)
>
> and I'll wager that your Decision model doesn't have fields of that
> name.

Correct, it just has one field 'choices'. I mentioned in the post that
the model has 'choices', the Form will have choice1, choice2 etc.

> Remember that the cleaned_data dictionary contains one key for
> each field in your form. So if they don't map exactly onto the field
> names for your model (with no extras -- it's not going to magically read
> your mind and decide you didn't mean to pass in choice1 and choice2),
> you'll need to manually map from the cleaned_data entries to the
> keywords to pass to the Decision constructor.

Yes I realise that I have to do the work in setting a value for the
field 'choices' for the model
from the values choice1 & choice2 in the form which should be in
cleaned_data if the form is valid.
I thought something like this is what I would do:

def clean(self):
# later I'll do a loop as there are a few of these choices.
self.cleaned_data = self.cleaned_data +
self.cleaned_data
# The model does not contain choice1, choice2 etc so remove
them.
del self.base_fields
del self.base_fields
# Now the form data should match the model so it should 'save'
OK.
return self.cleaned_data



I presume that as the form should be valid there will be a
cleaned_data dict available.
So I still can't understand why I get TypeError at /planner/decision/
add/
'choice1' is an invalid keyword argument for this function

Traceback:
File "/usr/lib/python2.4/site-packages/django_6910/core/handlers/
base.py" in get_response
82. response = callback(request, *callback_args,
**callback_kwargs)
File "/home/mikel/django_projects/proteomics/pls/lab/planner.py" in
decision_add
57. form.save()
File "/home/mikel/django_projects/proteomics/pls/lab/forms.py" in save
110. d = Decision(**self.cleaned_data)
File "/usr/lib/python2.4/site-packages/django_6910/db/models/base.py"
in __init__
176. raise TypeError, "'%s' is an invalid keyword
argument for this function" % kwargs.keys()

Exception Type: TypeError at /planner/decision/add/
Exception Value: 'choice1' is an invalid keyword argument for this
function

Mike

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
For more options, visit this group athttp://groups.google.com/group/django-users?hl=en-~----------~----~----~----~------~----~------~--~---

Offline

#4 March 8, 2008 14:31:57

Karen T.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Custom form where fields in Form do not match Model


On Sat, Mar 8, 2008 at 6:49 AM, speleolinux <>
wrote:

>
> Hi
>
> On Mar 7, 11:26 pm, Malcolm Tredinnick <>
> wrote:
> > It is fairly important when reporting an error like this that you give
> > enough information to indicate where the error is coming from.
> ...
> Sorry. See at bottom.
>
> > Guessing a lot here (it looks like there's only one place "choice1"
> > could be being used as a keyword argument), I suspect you'll find the
> > problem is related to this line in your view:
> >
> > d = Decision(**self.cleaned_data)
> >
> > Since your form has fields 'choice1' and 'choice2', this will be
> > equivalent to a call to
> >
> > Decision(choice1=..., choice2=..., choices=...)
> >
> > and I'll wager that your Decision model doesn't have fields of that
> > name.
>
> Correct, it just has one field 'choices'. I mentioned in the post that
> the model has 'choices', the Form will have choice1, choice2 etc.
>
> > Remember that the cleaned_data dictionary contains one key for
> > each field in your form. So if they don't map exactly onto the field
> > names for your model (with no extras -- it's not going to magically read
> > your mind and decide you didn't mean to pass in choice1 and choice2),
> > you'll need to manually map from the cleaned_data entries to the
> > keywords to pass to the Decision constructor.
>
> Yes I realise that I have to do the work in setting a value for the
> field 'choices' for the model
> from the values choice1 & choice2 in the form which should be in
> cleaned_data if the form is valid.
> I thought something like this is what I would do:
>
> def clean(self):
> # later I'll do a loop as there are a few of these choices.
> self.cleaned_data = self.cleaned_data +
> self.cleaned_data
> # The model does not contain choice1, choice2 etc so remove
> them.
> del self.base_fields
> del self.base_fields
> # Now the form data should match the model so it should 'save'
> OK.
> return self.cleaned_data
>

If you are going to populate a Decision from self.cleaned_data, then you
need to remove choice1 and choice2, etc, from the cleaned_data dictionary
that you return from your clean() function. Removing them from base_fields
I don't think does much at this point, they're already in cleaned_data and
that is where they need to be removed from.


>

I'm not sure where the right place is for this, mucking with removing fields
from cleaned_data seems inelegant but if you're going to be presenting a set
of fields on the form and have to consolidate them down to one field for the
model then it's got to be done somewhere.


> I presume that as the form should be valid there will be a
> cleaned_data dict available.
> So I still can't understand why I get TypeError at /planner/decision/
> add/
> 'choice1' is an invalid keyword argument for this function
>

The cleaned_data dict that is available is the one returned from your
clean() function. Since you haven't removed the clean1, clean2 choices from
that, you get the TypeError.

Karen

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
For more options, visit this group athttp://groups.google.com/group/django-users?hl=en-~----------~----~----~----~------~----~------~--~---

Offline

#5 March 9, 2008 12:46:49

s.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Custom form where fields in Form do not match Model


On Mar 9, 1:31 am, "Karen Tracey" <> wrote:
> If you are going to populate a Decision from self.cleaned_data, then you
> need to remove choice1 and choice2, etc, from the cleaned_data dictionary
> that you return from your clean() function. Removing them from base_fields
> I don't think does much at this point, they're already in cleaned_data and
> that is where they need to be removed from.

Ah thanks! For a start I was removing the fields from the wrong place.
I really needed to be doing this:
del self.cleaned_data

> I'm not sure where the right place is for this, mucking with removing fields
> from cleaned_data seems inelegant but if you're going to be presenting a set
> of fields on the form and have to consolidate them down to one field for the
> model then it's got to be done somewhere.

Inelegant. Oh well :-(
But yes I have to consolidate several fields into one in the model.

I now have this:

def clean(self):
enumerated_choices =
if self.cleaned_data:

enumerated_choices.append( (str(self.cleaned_data),
int(self.cleaned_data)) )
del self.cleaned_data
del self.cleaned_data
if self.cleaned_data:

enumerated_choices.append( (str(self.cleaned_data),
int(self.cleaned_data)) )
del self.cleaned_data
del self.cleaned_data

self.cleaned_data = str(enumerated_choices)
return self.cleaned_data

def save(self):
d = Decision(**self.cleaned_data)
d.save()
return '%s' % d.id

and it works !
Now it works I have to better understand what's happening and to
iterate over the choices so that it can do any number of fields.
(Basically a user enters a description of a choice and a drop down and
selects a decision. There can be several of these.
The data is turned into a stringified list of tuples and stored in the
database in one string field.)

Thanks Karen for the clue that got it working.

Mike


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
For more options, visit this group athttp://groups.google.com/group/django-users?hl=en-~----------~----~----~----~------~----~------~--~---

Offline

  • Root
  • » Django
  • » Custom form where fields in Form do not match Model [RSS Feed]

Board footer

Moderator control

Enjoy the 11th of December
PoweredBy

The Forums are managed by develissimo stuff members, if you find any issues or misplaced content please help us to fix it. Thank you! Tell us via Contact Options
Leave a Message
Welcome to Develissimo Live Support