Re: Newforms / Validation / Uniqueness

2007-06-01 Thread Nebojša Đorđević

On 31.05.2007., at 04:30, Malcolm Tredinnick wrote:

> On Wed, 2007-05-30 at 08:31 -0700, ringemup wrote:
> [...]
>>> So a "uniqueness" constraint on your model is not something that the
>>> form framework is really in a position to check. Instead, what  
>>> should
>>> happen is you construct the model object and then call
>>> object.validate(), which returns ValidationErrors if there are  
>>> problems.
>>> The validate() method on a model will have full access to the model
>>> instance (including "self").
>>
>> Do you then have to figure out which errors apply to which Form
>> fields, and sort them out and assign them?  I haven't seen any sample
>> code doing anything of this sort, so I'd be very interested to see  
>> how
>> it works.
>
> Since full model-aware validation doesn't exist yet, example code  
> would
> be premature. :-)
>
> To sort of answer your question, however: yes, in the cases where you
> are using model-aware validation as part of the form validation, you
> would need to figure out the mapping back. We might be able to make  
> some
> things easier in form_for_model() cases, but, as I say, the code  
> doesn't
> exist yet, so any claims as to what actually happens would be
> hypothetical.

You can see some validation examples and at http://django- 
utils.googlecode.com/svn/branches/0.1/forms/  -- look at the  
`create_object` for the example.

Code is little old but should work.

(sadly, I currently do not have any spare time to work on this :( )

-- 
Nebojša Đorđević - nesh, ICQ#43799892, http://www.linkedin.com/in/ 
neshdj
Studio Quattro - Niš - Serbia
http://studioquattro.biz/ | http://code.google.com/p/django-utils/
Registered Linux User 282159 [http://counter.li.org]



--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-31 Thread ringemup

> Since full model-aware validation doesn't exist yet, example code would
> be premature. :-)

Ah, sorry, I thought you were saying that models have an existing
validate() method that could be called on an object constructed by a
form.


On May 30, 3:18 pm, "Alfonso Ali" <[EMAIL PROTECTED]> wrote:
> My solution is to use the base class parameter of form_for_[model|instance]
> function, for example:

Thanks, that looks like a reasonably elegant solution.  I'm still
trying to figure out what methods I'd need to override and whether
they need to be completely rewritten or where I can call super().  If
I get this working, I'm going to write up an "extending newforms for
dummies" explanation in case there are other people out there who are
as dense as me.  ;-)



--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-30 Thread Malcolm Tredinnick

On Wed, 2007-05-30 at 08:31 -0700, ringemup wrote:
[...]
> > So a "uniqueness" constraint on your model is not something that the
> > form framework is really in a position to check. Instead, what should
> > happen is you construct the model object and then call
> > object.validate(), which returns ValidationErrors if there are problems.
> > The validate() method on a model will have full access to the model
> > instance (including "self").
> 
> Do you then have to figure out which errors apply to which Form
> fields, and sort them out and assign them?  I haven't seen any sample
> code doing anything of this sort, so I'd be very interested to see how
> it works.

Since full model-aware validation doesn't exist yet, example code would
be premature. :-)

To sort of answer your question, however: yes, in the cases where you
are using model-aware validation as part of the form validation, you
would need to figure out the mapping back. We might be able to make some
things easier in form_for_model() cases, but, as I say, the code doesn't
exist yet, so any claims as to what actually happens would be
hypothetical.

At this point, all I can claim is that it's perfect -- not at all
useful, but perfect. Hypothetical constructs are good like that. :-)

Regards,
Malcolm


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-30 Thread Alfonso Ali
My solution is to use the base class parameter of form_for_[model|instance]
function, for example:

class SomeTest(models.Model):
   name = models.CharField(maxlength=50)
   user = models.ForeignKey(User)

   class Meta:
  unique_together = (('user', 'name'),)

class SomeTestBaseForm(forms.BaseForm):
def __init__(self, *args, **kwargs):
   super(SomeTestBaseForm, self).__init__(*args, **kwargs)

   def clean_name(self):
   if self.data.get('name', None) and self.data.get('user', None):
  try:
  sometest = SomeTest.get(name=self.data['name'])
  except SomeTest.DoesNotExist:
  return self.data['name']
  raise forms.ValidationError(u'The name already exists')

SomeTestForm = forms.form_for_model(SomeTest, SomeTestBaseForm)

this way you can add custom validation and DRY when your form's fields match
your model.

Regards,
  Ali

On 5/29/07, ringemup <[EMAIL PROTECTED]> wrote:
>
>
> Hello --
>
> I'm using a basic form_for_model() form object for a model that has a
> unique=True constraint on a field other than the primary key.
>
> When validating submitted data, is there a reason the form check that
> that constraint hasn't been violated and throw a validation error?
> I'd like to be able to catch that input error and present a message to
> the user, instead of what's currently happening, which is that no
> error is thrown and when I try to save the data I get an integrity
> error, which is unrecoverable.
>
> Do I need to create a custom form class just to handle a uniqueness
> requirement?
>
> Thanks!
>
>
> >
>

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-30 Thread Horst Gutmann

ringemup wrote:
> 
> Do you then have to figure out which errors apply to which Form
> fields, and sort them out and assign them?  I haven't seen any sample
> code doing anything of this sort, so I'd be very interested to see how
> it works.
> 

I was recently in the same situation and did something like this:

def handle_integrityerror(form):
message = sys.exc_info()[1].message
if message.startswith("column "):
parts = message.split(" ")
form.errors.setdefault(parts[1],[]).append(" ".join(parts[1:]))

You basically call this method when catching a django.db.IntegrityError
and it will try to determine based on the exception's message what field
in the auto-generated form caused the trouble and adds basically that
message to the error-list for the offending field.

It's not really an elegant solution but so far it seems to work for me.

Horst

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-30 Thread ringemup


> The short answer to your problem is probably to not use form_for_model()
> if you want this sort of support. Instead write your own Form sub-class
> and write a clean() method for it. The form_for_model() function is just
> an aid after all; it shouldn't be the only thing you ever consider
> using.

OK  I think I'm also not entirely clear on the difference between
creating a completely separate Form class vs. extending BaseForm and
using form_for_model() -- the implications of each option, what does
and doesn't have to be done for each, and when each is preferable.


> There's a "division of labor" problem going on in the case you are
> looking at. Forms are orthogonal to models. It just happens that in this
> case, accidentally, your form has a correspondence between its fields
> and one of your models, but in the entire universe of possible forms and
> possible models, that correspondence can't be assumed.

You're right, it is orthogonal.  I suppose form_for_model() really
exists in order for basic forms to be available for all models in the
admin, and it's just exposed to other apps for the sake of
convenience?

> [Aside: it seems that Django projects split into two rough groups --
> those whose forms are in close correlation to their models and those
> whose forms map the data onto different fields in different models after
> lots of munging; I never seem to write the first type of app, for
> example, so form_for_model is something I don't find myself needing at
> all.]

Yup, I've got an app of the second type coming up, but I'm working on
one of the first type in an attempt to become familiar with newforms.

> So a "uniqueness" constraint on your model is not something that the
> form framework is really in a position to check. Instead, what should
> happen is you construct the model object and then call
> object.validate(), which returns ValidationErrors if there are problems.
> The validate() method on a model will have full access to the model
> instance (including "self").

Do you then have to figure out which errors apply to which Form
fields, and sort them out and assign them?  I haven't seen any sample
code doing anything of this sort, so I'd be very interested to see how
it works.

I have to say, I'm incredibly impressed with Django, with all the
functionality it provides, and with the way it's moving so quickly.
Newforms, in particular, reminds me of something I was beginning to
build into my personal PHP library, and I recognize that it's a
boatload of work to make something that everyone can use.  I can't
wait until the documentation catches up with the development!

> Am Dienstag, 29. Mai 2007 21:19 schrieb ringemup:

> you can add custom validation methods to the class (either by subclassing
> or by adding a bound method)
>
> Example: ("file" is the attribute of the form/model)
>
> def clean_file(self):
> value = self.fields["file"].widget.value_from_datadict(self.data, 
> self.add_prefix("file"))
> if not ...:
> raise forms.ValidationError(u"...")
> return value

That sounds like a reasonable solution.  Two questions: how does one
add a bound method (in fact, what is a "bound method")?  Also, how
does one subclass a class that is created dynamically with
form_for_model()?


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-30 Thread Thomas Guettler

Am Dienstag, 29. Mai 2007 21:19 schrieb ringemup:
> Hello --
>
> I'm using a basic form_for_model() form object for a model that has a
> unique=True constraint on a field other than the primary key.
>
> When validating submitted data, is there a reason the form check that
> that constraint hasn't been violated and throw a validation error?
> I'd like to be able to catch that input error and present a message to
> the user, instead of what's currently happening, which is that no
> error is thrown and when I try to save the data I get an integrity
> error, which is unrecoverable.
>
> Do I need to create a custom form class just to handle a uniqueness
> requirement?

Hi,

you can add custom validation methods to the class (either by subclassing
or by adding a bound method)

Example: ("file" is the attribute of the form/model)

def clean_file(self):
value = self.fields["file"].widget.value_from_datadict(self.data, 
self.add_prefix("file"))
if not ...:
raise forms.ValidationError(u"...")
return value


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Newforms / Validation / Uniqueness

2007-05-29 Thread Malcolm Tredinnick

On Tue, 2007-05-29 at 12:19 -0700, ringemup wrote:
> Hello --
> 
> I'm using a basic form_for_model() form object for a model that has a
> unique=True constraint on a field other than the primary key.
> 
> When validating submitted data, is there a reason the form check that
> that constraint hasn't been violated and throw a validation error?
> I'd like to be able to catch that input error and present a message to
> the user, instead of what's currently happening, which is that no
> error is thrown and when I try to save the data I get an integrity
> error, which is unrecoverable.
> 
> Do I need to create a custom form class just to handle a uniqueness
> requirement?

I'm not sure this is completely easy to do with newforms at the moment.
In oldforms, the validators on the model would have caught this, to some
extent, but that isn't the case with newforms.

The short answer to your problem is probably to not use form_for_model()
if you want this sort of support. Instead write your own Form sub-class
and write a clean() method for it. The form_for_model() function is just
an aid after all; it shouldn't be the only thing you ever consider
using.

An long explanation of what's going and how we can fix it follows...

This sort of thing is a motivation for us to get model-aware validation
(which is a catch-all name for a somewhat undefined, but semi-large area
of work) going.

There's a "division of labor" problem going on in the case you are
looking at. Forms are orthogonal to models. It just happens that in this
case, accidentally, your form has a correspondence between its fields
and one of your models, but in the entire universe of possible forms and
possible models, that correspondence can't be assumed.

[Aside: it seems that Django projects split into two rough groups --
those whose forms are in close correlation to their models and those
whose forms map the data onto different fields in different models after
lots of munging; I never seem to write the first type of app, for
example, so form_for_model is something I don't find myself needing at
all.]

So a "uniqueness" constraint on your model is not something that the
form framework is really in a position to check. Instead, what should
happen is you construct the model object and then call
object.validate(), which returns ValidationErrors if there are problems.
The validate() method on a model will have full access to the model
instance (including "self").

There is a lot of the support code in place already for this, because
Adrian started working on it early last year. Other priorities have
taken over in the interim (we've done two releases and newforms has been
written, for a start!), but this is getting closer to the top of the
pile of things to clean up, particularly as we try to round out
newforms. It's not completely trivial, because oldforms still exists
(and will in 1.0, too), so we have to juggle things so that two
approaches work. I know I've done a reasonable about of scribbling on
paper trying to get this straight and I suspect some other people have,
too, over time. We'll work it out, though, and try to make this sort of
thing "more natural" for very simple forms attached to a model.

Regards,
Malcolm


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Newforms / Validation / Uniqueness

2007-05-29 Thread ringemup

Hello --

I'm using a basic form_for_model() form object for a model that has a
unique=True constraint on a field other than the primary key.

When validating submitted data, is there a reason the form check that
that constraint hasn't been violated and throw a validation error?
I'd like to be able to catch that input error and present a message to
the user, instead of what's currently happening, which is that no
error is thrown and when I try to save the data I get an integrity
error, which is unrecoverable.

Do I need to create a custom form class just to handle a uniqueness
requirement?

Thanks!


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---