Streamlining Model validation of ForeignKeys

2024-05-10 Thread Shaheed Haque
Hi,

I have two models Source and Input, where Input has an FK to Source like
this:

class Source(db_models.Model):
scheme = db_models.CharField(...)
path = db_models.CharField(...)
display_as = db_models.CharField(...)

class Input(db_models.Model):
name = db_models.CharField(...)
description = db_models.CharField(...)
type = db_models.CharField(...)
source = db_models.ForeignKey(Source, on_delete=db_models.CASCADE)
reuse = db_models.CharField(...)
value = db_models.CharField(...)

The instances of Source are statically created, and number 20 or so in
total. The instances of Input number in the millions, and may be loaded
from external files/network endpoints. When Input instances are created, we
perform normal Django validation processing, involving
form.is_valid()/form.errors. As we know, Django 5.x does something like:

   1. Form field validation using Form.clean_xxx().
   2. Form cross-field validation using Form.clean().
   3. Model validation, including validating the FK.

like this:

...
File "/.../django/forms/forms.py", line 197, in is_valid return
self.is_bound and not self.errors File "/.../django/forms/forms.py", line
192, in errors self.full_clean() File "/.../django/forms/forms.py", line
329, in full_clean self._post_clean() File "/.../django/forms/models.py",
line 496, in _post_clean self.instance.full_clean(exclude=exclude,
validate_unique=False) File "/.../django/db/models/base.py", line 1520, in
full_clean self.clean_fields(exclude=exclude) File
"/.../django/db/models/base.py", line 1572, in clean_fields setattr(self,
f.attname, f.clean(raw_value, self)) File
"/.../django/db/models/fields/__init__.py", line 830, in clean
self.validate(value, model_instance) File
"/.../django/db/models/fields/related.py", line 1093, in validate if not
qs.exists():
...

In one experiment, I observe that this results in 143k queries, taking a
total of 43s. Is there a way to short circuit this Model-level validation?
Since I know the ~20 instances of Source, even a cache of
Source.objects.all() would be a very cheap, but I cannot see any way to
inject that into the code for line 1093:

   def validate(self, value, model_instance):
   if self.remote_field.parent_link:
   return
   super().validate(value, model_instance)
   if value is None:
   return

   using = router.db_for_read(self.remote_field.model,
instance=model_instance)
   qs = self.remote_field.model._base_manager.using(using).filter(
<<<< queryset created here
   **{self.remote_field.field_name: value}
   )
   qs = qs.complex_filter(self.get_limit_choices_to())
   if not qs.exists():
<<<< queryset evaluated here, line 1093
   raise exceptions.ValidationError(...)

We actually have several versions of this problem so any ideas are welcome.

Thanks, Shaheed

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHAc2jfzag7v6t7_pvbRnyJ-chMFHyjmkXsDkRouTg7JOteRfQ%40mail.gmail.com.


Re: Model validation across relationships

2014-03-24 Thread Joshua Pokotilow
Thanks for the reply. I had a (perhaps unreasonable) malaise that 
validation should be limited to the fields on a single model.

On Sunday, March 23, 2014 4:19:29 PM UTC-4, Simon Charette wrote:
>
> I'd say that's exactly what you should use `Model.clean()` for. In this 
> case you're *doing validation that requires access to more than a single 
> field.*
>
> What sounds vague to you in the documentation?
>
> Le vendredi 21 mars 2014 19:43:07 UTC-4, Joshua Pokotilow a écrit :
>>
>> Given these models, would UserProfile.clean() make sense as written?
>>
>> class PhoneNumber(models.Model):
>> user = models.ForeignKey(User, related_name='phone_numbers')
>> phone_number = models.CharField(max_length=20)
>>
>> class UserProfile(models.Model):
>> user = models.OneToOneField(User)
>> sms_notifications_enabled = models.BooleanField(default=False)
>>
>> # Given these models / fields, does this implementation make sense?
>> def clean(self):
>> if self.sms_notifications_enabled:
>> if not self.user.phone_numbers.exists():
>> raise ValidationError("SMS notifications cannot be enabled 
>> because this user has no phone number")
>>
>> I *think* it’s OK, but the documentation for Model.clean() seems 
>> somewhat vague about what sorts of checks one may implement. Specifically, 
>> it says, “This method should be used to provide custom model validation, 
>> and to modify attributes on your model if desired. For instance, you could 
>> use it to automatically provide a value for a field, or to do validation 
>> that requires access to more than a single field.”
>>
>> Is the above code in line with best practices?
>>
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0b3f9b10-f20a-4684-81d7-f04a62bf3790%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model validation across relationships

2014-03-23 Thread Simon Charette
I'd say that's exactly what you should use `Model.clean()` for. In this 
case you're *doing validation that requires access to more than a single 
field.*

What sounds vague to you in the documentation?

Le vendredi 21 mars 2014 19:43:07 UTC-4, Joshua Pokotilow a écrit :
>
> Given these models, would UserProfile.clean() make sense as written?
>
> class PhoneNumber(models.Model):
> user = models.ForeignKey(User, related_name='phone_numbers')
> phone_number = models.CharField(max_length=20)
>
> class UserProfile(models.Model):
> user = models.OneToOneField(User)
> sms_notifications_enabled = models.BooleanField(default=False)
>
> # Given these models / fields, does this implementation make sense?
> def clean(self):
> if self.sms_notifications_enabled:
> if not self.user.phone_numbers.exists():
> raise ValidationError("SMS notifications cannot be enabled 
> because this user has no phone number")
>
> I *think* it’s OK, but the documentation for Model.clean() seems somewhat 
> vague about what sorts of checks one may implement. Specifically, it says, 
> “This method should be used to provide custom model validation, and to 
> modify attributes on your model if desired. For instance, you could use it 
> to automatically provide a value for a field, or to do validation that 
> requires access to more than a single field.”
>
> Is the above code in line with best practices?
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/58d9ed08-c88d-4b0f-9e46-eb6a1e246650%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Model validation across relationships

2014-03-21 Thread Joshua Pokotilow


Given these models, would UserProfile.clean() make sense as written?

class PhoneNumber(models.Model):
user = models.ForeignKey(User, related_name='phone_numbers')
phone_number = models.CharField(max_length=20)

class UserProfile(models.Model):
user = models.OneToOneField(User)
sms_notifications_enabled = models.BooleanField(default=False)

# Given these models / fields, does this implementation make sense?
def clean(self):
if self.sms_notifications_enabled:
if not self.user.phone_numbers.exists():
raise ValidationError("SMS notifications cannot be enabled 
because this user has no phone number")

I *think* it’s OK, but the documentation for Model.clean() seems somewhat 
vague about what sorts of checks one may implement. Specifically, it says, 
“This method should be used to provide custom model validation, and to 
modify attributes on your model if desired. For instance, you could use it 
to automatically provide a value for a field, or to do validation that 
requires access to more than a single field.”

Is the above code in line with best practices?

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/084d8f27-0014-47d0-83bd-29c11b50c645%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: conditional model validation

2012-09-28 Thread Lachlan Musicman
On Friday, September 28, 2012, Babatunde Akinyanmi wrote:

> Let me try to assist. A forms is_valid method causes 3 types of
> cleaning methods to be run. Based on that, I'm sure you really don't
> need to override it.
>
>
Yes, I've just discoverde the ValidationError e part of the docs :|



> I really don't understand what you mean by "I want the description
> field to be not blank/not the empty string" so maybe I could have been
> of more help but I'm sure a solution to your problem would be to
> override either the form's clean_fieldname or clean methods.
>

ie,
if e.mark = W, e.descr must be >"" # it can be anything from "a" to
"pregnant" to "killed" to "this is not an empty string" or " this is not a
blank string"
else e.descr == "" #this is a blank or empty string





> Check: https://docs.djangoproject.com/en/dev/ref/forms/validation/
> which is a link to the documentation on form validation
>


cheers - since I am using the admin forms, I was hoping I could add it to
the model, but is ok if I need to rewrite the forms

cheers
L.


> On 9/28/12, Lachlan Musicman > wrote:
> > Hola,
> >
> > I'm searching without much luck and can't see the answer in the docs.
> >
> > Am wanting to override the is_valid() method on a model (I think
> > that's what I want).
> >
> > Basically, I have a choices field, and if one of those choices is
> > selected, then I want a description field to be not blank/not the
> > empty string. If it's the other two choices, I want the description
> > field to be blank/empty string.
> >
> > First, I override is_valid() as a model method?
> >
> > Second, how do I return a false from is_valid()?
> >
> > ie, this is a rough up of what I'm looking for - what goes in place of
> > return FALSE/TRUE?
> >
> > def is_valid(self):
> >
> > if enrolment.mark == 'W': #student has withdrawn from course
> > -if enrolment.withdrawal_reason == '': #must have reason
> > --return FALSE
> > elif enrolment.withdrawal.reason != "": #ie, since enrolment.mark
> > isn't 'W', confirm that the enrolment.reason is ""
> > -return FALSE
> > else:
> > -return TRUE
> >
> > Cheers
> > L.
> > --
> > ...we look at the present day through a rear-view mirror. This is
> > something Marshall McLuhan said back in the Sixties, when the world
> > was in the grip of authentic-seeming future narratives. He said, “We
> > look at the present through a rear-view mirror. We march backwards
> > into the future.”
> >
> > http://www.warrenellis.com/?p=14314
> >
> > --
> > 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
> > django-users+unsubscr...@googlegroups.com .
> > For more options, visit this group at
> > http://groups.google.com/group/django-users?hl=en.
> >
> >
>
> --
> Sent from my mobile device
>
> --
> 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
> django-users+unsubscr...@googlegroups.com .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
...we look at the present day through a rear-view mirror. This is something
Marshall McLuhan said back in the Sixties, when the world was in the grip
of authentic-seeming future narratives. He said, “We look at the present
through a rear-view mirror. We march backwards into the future.”

http://www.warrenellis.com/?p=14314

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: conditional model validation

2012-09-28 Thread Babatunde Akinyanmi
Let me try to assist. A forms is_valid method causes 3 types of
cleaning methods to be run. Based on that, I'm sure you really don't
need to override it.

I really don't understand what you mean by "I want the description
field to be not blank/not the empty string" so maybe I could have been
of more help but I'm sure a solution to your problem would be to
override either the form's clean_fieldname or clean methods.

Check: https://docs.djangoproject.com/en/dev/ref/forms/validation/
which is a link to the documentation on form validation

On 9/28/12, Lachlan Musicman  wrote:
> Hola,
>
> I'm searching without much luck and can't see the answer in the docs.
>
> Am wanting to override the is_valid() method on a model (I think
> that's what I want).
>
> Basically, I have a choices field, and if one of those choices is
> selected, then I want a description field to be not blank/not the
> empty string. If it's the other two choices, I want the description
> field to be blank/empty string.
>
> First, I override is_valid() as a model method?
>
> Second, how do I return a false from is_valid()?
>
> ie, this is a rough up of what I'm looking for - what goes in place of
> return FALSE/TRUE?
>
> def is_valid(self):
>
> if enrolment.mark == 'W': #student has withdrawn from course
> -if enrolment.withdrawal_reason == '': #must have reason
> --return FALSE
> elif enrolment.withdrawal.reason != "": #ie, since enrolment.mark
> isn't 'W', confirm that the enrolment.reason is ""
> -return FALSE
> else:
> -return TRUE
>
> Cheers
> L.
> --
> ...we look at the present day through a rear-view mirror. This is
> something Marshall McLuhan said back in the Sixties, when the world
> was in the grip of authentic-seeming future narratives. He said, “We
> look at the present through a rear-view mirror. We march backwards
> into the future.”
>
> http://www.warrenellis.com/?p=14314
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
Sent from my mobile device

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



conditional model validation

2012-09-27 Thread Lachlan Musicman
Hola,

I'm searching without much luck and can't see the answer in the docs.

Am wanting to override the is_valid() method on a model (I think
that's what I want).

Basically, I have a choices field, and if one of those choices is
selected, then I want a description field to be not blank/not the
empty string. If it's the other two choices, I want the description
field to be blank/empty string.

First, I override is_valid() as a model method?

Second, how do I return a false from is_valid()?

ie, this is a rough up of what I'm looking for - what goes in place of
return FALSE/TRUE?

def is_valid(self):

if enrolment.mark == 'W': #student has withdrawn from course
-if enrolment.withdrawal_reason == '': #must have reason
--return FALSE
elif enrolment.withdrawal.reason != "": #ie, since enrolment.mark
isn't 'W', confirm that the enrolment.reason is ""
-return FALSE
else:
-return TRUE

Cheers
L.
-- 
...we look at the present day through a rear-view mirror. This is
something Marshall McLuhan said back in the Sixties, when the world
was in the grip of authentic-seeming future narratives. He said, “We
look at the present through a rear-view mirror. We march backwards
into the future.”

http://www.warrenellis.com/?p=14314

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model Validation with Exception Handling

2012-09-13 Thread Jani Tiainen

Hi,

I'm using following piece of code with ExtJS:


def extjs_validate_instance(instance):
"""Validate given Django model instance.
Return ExtJS formatted error response.
"""
try:
instance.full_clean() # Validate
except ValidationError, e:
opts = instance._meta
nice_messages = []
for fname, msgs in e.message_dict.items():
nice_messages.append({
'name' : 
force_unicode(opts.get_field_by_name(fname)[0].verbose_name),

'error' : ', '.join(msgs),
})

response_obj = {
'success': False,
'items' : nice_messages}
raise ErrorResponse(status.HTTP_200_OK, response_obj)


Now it returns dict "nice_messages" which contains fieldname and 
message(s) associated with that field.



13.9.2012 2:36, Kurtis Mullins kirjoitti:

Just a quick example of a field that can have two completely different
error types but both throw a ValidationError while running full_clean().

Let's say my Model includes an email address. The email address must be
unique. It could either fail because 1. It's not Unique (or) 2. It's an
invalid email address.

What I really want to do is determine the exception/error-type so that I
can handle it appropriately.

On Wed, Sep 12, 2012 at 7:09 PM, Kurtis <kurtis.mull...@gmail.com
<mailto:kurtis.mull...@gmail.com>> wrote:

Hey Guys,

Do you have any suggestions on a good way to grab error types during
Model Validation? I'm not using Forms or HTML. First, here's a
simplified snippet showing my current format for Model Data Validation.

my_object = MyModel(**data_dict)
try:
 my_object.full_clean()
 my_object.save()
 return SuccessJSONResponse()
except ValidationError, e:
 print e.message_dict # Testing
 # ... build some custom JSON data from the error
 return ErrorJSONResponse(json_data)

This works fine for properly validating the data and being able to
print out errors. It also allows me to easily see which fields threw
errors. Unfortunately, it doesn't provide me with the types of
errors in a "programmatic" fashion as far as I can tell. For
example, a field can fail because it's a duplicate entry or it can
fail because it didn't meet the criteria of the field-type (e.g.
max_length).

What I'm hoping for is there's a way I can still easily validate my
data using my Model but get more specific information about the
types of errors. If it's an IntegrityError then I need to build a
custom response indicating which field had failed along with an
"internal" (to the project) error code and a description. If it's
some other specific error (for example, maybe an email address isn't
a "valid" email address) then I'd like to identify the error type,
field name, and display that error accordingly. Hopefully that makes
sense :)

I'm not sure if I'm just over-looking something or trying to do
things the hard way but I'm up for suggestions. Keep in mind that
Forms + HTML are out of the question since this is an API-only
application.

Thanks!
- Kurtis

--
You received this message because you are subscribed to the Google
Groups "Django users" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/django-users/-/7CS8sJxLHhwJ.
To post to this group, send email to django-users@googlegroups.com
<mailto:django-users@googlegroups.com>.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com
<mailto:django-users%2bunsubscr...@googlegroups.com>.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.


--
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
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.



--
Jani Tiainen

- Well planned is half done and a half done has been sufficient before...

--
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model Validation with Exception Handling

2012-09-12 Thread Kurtis Mullins
Just a quick example of a field that can have two completely different
error types but both throw a ValidationError while running full_clean().

Let's say my Model includes an email address. The email address must be
unique. It could either fail because 1. It's not Unique (or) 2. It's an
invalid email address.

What I really want to do is determine the exception/error-type so that I
can handle it appropriately.

On Wed, Sep 12, 2012 at 7:09 PM, Kurtis <kurtis.mull...@gmail.com> wrote:

> Hey Guys,
>
> Do you have any suggestions on a good way to grab error types during Model
> Validation? I'm not using Forms or HTML. First, here's a simplified snippet
> showing my current format for Model Data Validation.
>
> my_object = MyModel(**data_dict)
> try:
> my_object.full_clean()
> my_object.save()
> return SuccessJSONResponse()
> except ValidationError, e:
> print e.message_dict # Testing
> # ... build some custom JSON data from the error
> return ErrorJSONResponse(json_data)
>
> This works fine for properly validating the data and being able to print
> out errors. It also allows me to easily see which fields threw errors.
> Unfortunately, it doesn't provide me with the types of errors in a
> "programmatic" fashion as far as I can tell. For example, a field can fail
> because it's a duplicate entry or it can fail because it didn't meet the
> criteria of the field-type (e.g. max_length).
>
> What I'm hoping for is there's a way I can still easily validate my data
> using my Model but get more specific information about the types of errors.
> If it's an IntegrityError then I need to build a custom response indicating
> which field had failed along with an "internal" (to the project) error code
> and a description. If it's some other specific error (for example, maybe an
> email address isn't a "valid" email address) then I'd like to identify the
> error type, field name, and display that error accordingly. Hopefully that
> makes sense :)
>
> I'm not sure if I'm just over-looking something or trying to do things the
> hard way but I'm up for suggestions. Keep in mind that Forms + HTML are out
> of the question since this is an API-only application.
>
> Thanks!
> - Kurtis
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/7CS8sJxLHhwJ.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Model Validation with Exception Handling

2012-09-12 Thread Kurtis
Hey Guys,

Do you have any suggestions on a good way to grab error types during Model 
Validation? I'm not using Forms or HTML. First, here's a simplified snippet 
showing my current format for Model Data Validation.

my_object = MyModel(**data_dict)
try:
my_object.full_clean()
my_object.save()
return SuccessJSONResponse()
except ValidationError, e:
print e.message_dict # Testing
# ... build some custom JSON data from the error
return ErrorJSONResponse(json_data)

This works fine for properly validating the data and being able to print 
out errors. It also allows me to easily see which fields threw errors. 
Unfortunately, it doesn't provide me with the types of errors in a 
"programmatic" fashion as far as I can tell. For example, a field can fail 
because it's a duplicate entry or it can fail because it didn't meet the 
criteria of the field-type (e.g. max_length).

What I'm hoping for is there's a way I can still easily validate my data 
using my Model but get more specific information about the types of errors. 
If it's an IntegrityError then I need to build a custom response indicating 
which field had failed along with an "internal" (to the project) error code 
and a description. If it's some other specific error (for example, maybe an 
email address isn't a "valid" email address) then I'd like to identify the 
error type, field name, and display that error accordingly. Hopefully that 
makes sense :)

I'm not sure if I'm just over-looking something or trying to do things the 
hard way but I'm up for suggestions. Keep in mind that Forms + HTML are out 
of the question since this is an API-only application.

Thanks!
- Kurtis

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/7CS8sJxLHhwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model validation fails, when inherited model redeclare parent field

2012-04-04 Thread shiva
Jani, thank you.

2012/4/4 Jani Tiainen :
> Hi,
>
> You'ew hitting limitation of Django ORM which prohibits overriding fields.
>
> https://docs.djangoproject.com/en/1.3/topics/db/models/#field-name-hiding-is-not-permitted
>
>
> 4.4.2012 6:34, shiva kirjoitti:
>
>> Hello!
>>
>> In our apps (that use Django 1.2.7) we use following models:
>>
>> class BaseRegistration(models.Model):
>>        exhibition = models.ForeignKey(...)
>>        year = models.IntegerField(...)
>>        user = models.ForeignKey('auth.User')
>>
>> class BarcodeRegistration(BaseRegistration):
>>        class Meta:
>>                abstract = True
>>
>> class EventRegistration(BarcodeRegistration):
>>        event = models.ForeignKey(...)
>>
>> I append *validate_unique* by *user* and *event* fields in
>> EventRegistration class:
>>
>> class EventRegistration(BarcodeRegistration):
>>        event = models.ForeignKey(...)
>>        user = models.ForeignKey('auth.User')
>>
>>        class Meta:
>>                unique_together = ('event', 'user')
>>
>> But in django command manage.py validate fails with error:
>>
>> exhibition.eventregistration: "unique_together" refers to user. This
>> is not in the same model as the unique_together statement.
>>
>> After some "pdb'ing" of django.core.management.validation,
>> django.db.models.base, and django.db.models.options I found, that is
>> happend because:
>>
>> In [13]: EventRegistration._meta.get_field('user') in
>> EventRegistration._meta.parents.keys()[0]._meta.local_fields
>> Out[13]: True
>>
>> In [14]: EventRegistration._meta.get_field('user') in
>> EventRegistration._meta.local_fields
>> Out[14]: False
>>
>> Is it's something wrong with our code?
>>
>> Thanks
>>
>> --
>> Shavrin Ivan
>>
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model validation fails, when inherited model redeclare parent field

2012-04-03 Thread Jani Tiainen

Hi,

You'ew hitting limitation of Django ORM which prohibits overriding fields.

https://docs.djangoproject.com/en/1.3/topics/db/models/#field-name-hiding-is-not-permitted


4.4.2012 6:34, shiva kirjoitti:

Hello!

In our apps (that use Django 1.2.7) we use following models:

class BaseRegistration(models.Model):
exhibition = models.ForeignKey(...)
year = models.IntegerField(...)
user = models.ForeignKey('auth.User')

class BarcodeRegistration(BaseRegistration):
class Meta:
abstract = True

class EventRegistration(BarcodeRegistration):
event = models.ForeignKey(...)

I append *validate_unique* by *user* and *event* fields in
EventRegistration class:

class EventRegistration(BarcodeRegistration):
event = models.ForeignKey(...)
user = models.ForeignKey('auth.User')

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

But in django command manage.py validate fails with error:

exhibition.eventregistration: "unique_together" refers to user. This
is not in the same model as the unique_together statement.

After some "pdb'ing" of django.core.management.validation,
django.db.models.base, and django.db.models.options I found, that is
happend because:

In [13]: EventRegistration._meta.get_field('user') in
EventRegistration._meta.parents.keys()[0]._meta.local_fields
Out[13]: True

In [14]: EventRegistration._meta.get_field('user') in
EventRegistration._meta.local_fields
Out[14]: False

Is it's something wrong with our code?

Thanks

--
Shavrin Ivan



--
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Model validation fails, when inherited model redeclare parent field

2012-04-03 Thread shiva
Hello!

In our apps (that use Django 1.2.7) we use following models:

class BaseRegistration(models.Model):
exhibition = models.ForeignKey(...)
year = models.IntegerField(...)
user = models.ForeignKey('auth.User')

class BarcodeRegistration(BaseRegistration):
class Meta:
abstract = True

class EventRegistration(BarcodeRegistration):
event = models.ForeignKey(...)

I append *validate_unique* by *user* and *event* fields in
EventRegistration class:

class EventRegistration(BarcodeRegistration):
event = models.ForeignKey(...)
user = models.ForeignKey('auth.User')

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

But in django command manage.py validate fails with error:

exhibition.eventregistration: "unique_together" refers to user. This
is not in the same model as the unique_together statement.

After some "pdb'ing" of django.core.management.validation,
django.db.models.base, and django.db.models.options I found, that is
happend because:

In [13]: EventRegistration._meta.get_field('user') in
EventRegistration._meta.parents.keys()[0]._meta.local_fields
Out[13]: True

In [14]: EventRegistration._meta.get_field('user') in
EventRegistration._meta.local_fields
Out[14]: False

Is it's something wrong with our code?

Thanks

--
Shavrin Ivan

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



modelForm validation -> model validation -> trigger field validation?

2012-01-25 Thread Sven
hi there,

has anyone of you an idea in which cycle the field method of 
ForeignKey.validate is triggered?

I have a custom ForeignKey Field where i override the validate method.
So i expect that 

ModelForm validation triggers 
-> Model validation (clean methods) and this triggers
-> Field validation of all contained fields

But this seems not be the case. Has anyone of you an idea?


-- 


Best Regards
 
Sven

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



model validation after related objects are updated

2011-10-21 Thread sspross
hi all

i have a admin model with tabluarinlines.

i want to do some additinal validations in the clean() function of the
model, but the validations (sum aggregation) depends on the relatated
objects (inlines).

where can i "hook" me in, to perform the validations after the related
objects were saved?

or do i have to overwrite the validations of the adminform?

thanks and best regards,
silvan

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: form.is_valid() NOT triggering model validation?

2011-09-29 Thread momo2k
Well, with the new knowledge about the debugger I found the place
where BaseModelForm calls all three form-validation methods in forms/
models.py:306:_post_form

Sorry.

On Sep 29, 9:26 pm, momo2k  wrote:
> That explains my thoughts that the debugger is "disturbing" the
> correct execution of the code, but this discussion does *not* (!)
> answer my question where the *model* of a *ModelForm* gets full_clean-
> ed - and why it doesn't do so in my case.
>
> On Sep 29, 8:48 pm, Shawn Milochik  wrote:
>
>
>
>
>
>
>
> > This exact thing was just discussed on this list.
>
> >https://groups.google.com/d/topic/django-users/R2HUGqZ1BAQ/discussion

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: form.is_valid() NOT triggering model validation?

2011-09-29 Thread momo2k
That explains my thoughts that the debugger is "disturbing" the
correct execution of the code, but this discussion does *not* (!)
answer my question where the *model* of a *ModelForm* gets full_clean-
ed - and why it doesn't do so in my case.

On Sep 29, 8:48 pm, Shawn Milochik  wrote:
> This exact thing was just discussed on this list.
>
> https://groups.google.com/d/topic/django-users/R2HUGqZ1BAQ/discussion

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: form.is_valid() NOT triggering model validation?

2011-09-29 Thread Shawn Milochik
This exact thing was just discussed on this list.

https://groups.google.com/d/topic/django-users/R2HUGqZ1BAQ/discussion

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



form.is_valid() NOT triggering model validation?

2011-09-29 Thread momo2k
Hello,

after hours of examinating and debugging the Django source code I
decided to post my problem here.

I'm using Django 1.3.1 and its docs say:


The is_valid() method and errors
Changed in Django 1.2: Please, see the release notes

The first time you call is_valid() or access the errors attribute of a
ModelForm has always triggered form validation, but as of Django 1.2,
it will also trigger model validation. This has the side-effect of
cleaning the model you pass to the ModelForm constructor. For
instance, calling is_valid() on your form will convert any date fields
on your model to actual date objects.


I'm using a FormView with a ModelForm. No matter if I add an instance
to the forms kwargs, the model.full_clean method is *not* called by
form.is_valid(). This is working fine later by

def form_valid(.

self.obj= form.save(commit=False)
self.obj.full_clean()

I thought my python skills would be OK after one and a half year of
django programming, but I neither get why the _errors attribute of the
BaseForm (forms.Form:109) is always ErrorDict, even directly after
assigning it to None (forms.Form:84) according to the pydev-debugger,
and therefore form.clean() is never called - nor where the
model.full_clean() method is called at all. The implementation of
ModelForm/BaseModelForm is not that confusing.
I would be lucky if someone could explain to me why model validation
is not triggered with my ModelForm and where to find the piece of code
that does it.

If you need more information, just ask, please.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model Validation

2011-09-25 Thread Kurtis Mullins
Looks like you want to use this field:
https://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield

On Sat, Sep 24, 2011 at 11:54 PM, jenia ivlev  wrote:

> I have a model M that has a field num=models.IntegerField()
> I have a modelform called 'F' for model 'M'.
> I want to ensure that num is never negative.
>
> If I do validation in my form class, 'F', then i can do clean_num():
> if negative than throw ValidationError('Num can never be negative').
> This validationerror will be automatically redisplayed to the user by
> redirecting him to back to the form that he submitted and displaying
> the 'Num can never be negative' message on top of the num field.
> Thats all done automatically by django as soon as I throw the
> validationerror from the clean_fieldname method.
>
> I would like to be able to do all that, but in the model class.
>
> So F, that has a FormField for the ModelField 'num' , will fail and
> display the error message defined in the model class that its
> representing.
> Also F2 and Fxxx will do the same if they all represent 'M' and have a
> FormField for ModelField num.
>
> How can I achieve this?
>
> Thank you for your time and kind concern.
> jenia
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Model Validation

2011-09-24 Thread jenia ivlev
I have a model M that has a field num=models.IntegerField()
I have a modelform called 'F' for model 'M'.
I want to ensure that num is never negative.

If I do validation in my form class, 'F', then i can do clean_num():
if negative than throw ValidationError('Num can never be negative').
This validationerror will be automatically redisplayed to the user by
redirecting him to back to the form that he submitted and displaying
the 'Num can never be negative' message on top of the num field.
Thats all done automatically by django as soon as I throw the
validationerror from the clean_fieldname method.

I would like to be able to do all that, but in the model class.

So F, that has a FormField for the ModelField 'num' , will fail and
display the error message defined in the model class that its
representing.
Also F2 and Fxxx will do the same if they all represent 'M' and have a
FormField for ModelField num.

How can I achieve this?

Thank you for your time and kind concern.
jenia

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



How to override the model validation on server start?

2011-03-15 Thread Allan
hi Everyone
I have a model that i exported from a legacy database. when i start
the server it tells me that some of the fields cannot have unique=true
with a string CharField with a length over 255.

Is there a way to override the model validation that runs on server
start?

Thanks,
Allan

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Possible bug in model validation

2011-02-03 Thread Karen Tracey
On Thu, Feb 3, 2011 at 12:30 PM, Miguel Araujo  wrote:

> Las try or I will report it as a bug as I think it is.
>

Your original post was a bit sparse on code/traceback details for the actual
problem you observed. The only specific code you showed was the lines you
added to work around the problem. More details on the actual problem
(traceback, and under what circumstances it happens) and the code that
triggers it might help motivate someone to try to figure out whether what
you are trying to report is a bug or not. That's what I would need to see to
try to assess, and I have not had the time to go manufacture the missing
details based on the prose description.

Karen
-- 
http://tracey.org/kmt/

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Possible bug in model validation

2011-02-03 Thread Miguel Araujo
Las try or I will report it as a bug as I think it is.

2011/1/28 Miguel Araujo <muchoch...@gmail.com>

> Well,
>
> I'm just trying to figure out if this should be reported.
>
> Thanks, regards
>
> 
> Miguel Araujo
> @maraujop
>
> 2011/1/22 Miguel Araujo <muchoch...@gmail.com>
>
> Hi everyone,
>>
>> I have a model A that has a overwritten save method that updates a model
>> B's field. Both (A & B) have model validation using full_clean method.
>> Problem is that B model's validation fails when updating the field, because
>> it raises an IntegrityError saying the primary key already exits,
>> obviously.
>>
>> To fix this within my save method I have done:
>>
>> if kwargs.get('force_update') is False:
>> self.full_clean()
>>
>> If this is the desired behavior, then just let me know, I don't think the
>> primary key on an update should be validated this way.
>>
>> Thanks, best regards
>>
>> 
>> Miguel Araujo
>> @maraujop
>>
>
>

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Possible bug in model validation

2011-01-28 Thread Miguel Araujo
Well,

I'm just trying to figure out if this should be reported.

Thanks, regards


Miguel Araujo
@maraujop

2011/1/22 Miguel Araujo <muchoch...@gmail.com>

> Hi everyone,
>
> I have a model A that has a overwritten save method that updates a model
> B's field. Both (A & B) have model validation using full_clean method.
> Problem is that B model's validation fails when updating the field, because
> it raises an IntegrityError saying the primary key already exits,
> obviously.
>
> To fix this within my save method I have done:
>
> if kwargs.get('force_update') is False:
> self.full_clean()
>
> If this is the desired behavior, then just let me know, I don't think the
> primary key on an update should be validated this way.
>
> Thanks, best regards
>
> 
> Miguel Araujo
> @maraujop
>

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Possible bug in model validation

2011-01-22 Thread Miguel Araujo
Hi everyone,

I have a model A that has a overwritten save method that updates a model B's
field. Both (A & B) have model validation using full_clean method. Problem
is that B model's validation fails when updating the field, because it
raises an IntegrityError saying the primary key already exits, obviously.

To fix this within my save method I have done:

if kwargs.get('force_update') is False:
self.full_clean()

If this is the desired behavior, then just let me know, I don't think the
primary key on an update should be validated this way.

Thanks, best regards


Miguel Araujo
@maraujop

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Jonathan Barratt
On 13 ?.?. 2010, at 22:07, Javier Guerra Giraldez wrote:

> 2010/10/13 Jonathan Barratt :
>> not being an SQLite user myself but knowing the database image is a simple 
>> single file
> 
> you'd be surprised to learn that a good single-file architecture can
> be waaay faster than a more complex system.  (good examples include
> Tokyo Cabinet and Varnish and, yes, SQLite)

I am surprised! Learn several new things every day... :)

Thanks Javier!
Jonathan

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



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Javier Guerra Giraldez
2010/10/13 Jonathan Barratt :
> not being an SQLite user myself but knowing the database image is a simple 
> single file

you'd be surprised to learn that a good single-file architecture can
be waaay faster than a more complex system.  (good examples include
Tokyo Cabinet and Varnish and, yes, SQLite)

of course, RAM based DBs can be even faster too.

-- 
Javier

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



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Jonathan Barratt

On 13 ?.?. 2010, at 17:43, Russell Keith-Magee wrote:

> 2010/10/13 Jonathan Barratt :
>> On 13 ?.?. 2010, at 2:31, Jorge Vargas wrote:
> 
>> A database migration might not be the sort of effort you were looking for, 
>> but I can only imagine that moving from SQLite to Postgres or MySQL would 
>> offer you the largest possible performance gains...
> 
> Unlikely. When a test suite is run under SQLite, it runs entirely in
> memory; PostgreSQL/MySQL test suites run with disk commits.''

Ahh, I see - not being an SQLite user myself but knowing the database image is 
a simple single file I had mistakenly assumed the opposite. Bad advise is worse 
than no advice, shame on me! 

> You can verify this by running Django's own test suite. I regularly see SQLite
> test runs at about double the speed of the best I've seen under
> PostgreSQL or MySQL.
> 
> Testing is a situation that SQLite is extremely well optimized for --
> single user, no need for long term persistence.

Thanks for the insight Russ, learn something new every day and all that...

Yours gratefully,
Jonathan

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



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Russell Keith-Magee
2010/10/13 Jonathan Barratt :
> On 13 ?.?. 2010, at 2:31, Jorge Vargas wrote:

> A database migration might not be the sort of effort you were looking for, 
> but I can only imagine that moving from SQLite to Postgres or MySQL would 
> offer you the largest possible performance gains...

Unlikely. When a test suite is run under SQLite, it runs entirely in
memory; PostgreSQL/MySQL test suites run with disk commits. You can
verify this by running Django's own test suite. I regularly see SQLite
test runs at about double the speed of the best I've seen under
PostgreSQL or MySQL.

Testing is a situation that SQLite is extremely well optimized for --
single user, no need for long term persistence.

Yours,
Russ Magee %-)

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



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Russell Keith-Magee
On Wed, Oct 13, 2010 at 3:31 AM, Jorge Vargas  wrote:
> Hello,
>
> I recently inherited a project that uses a lot of model validations
> and is mainly just a model (we have two django apps that use it as
> their backend).
>
> The test suite currently returns
>
> Ran 460 tests in 980.347s
> That is running on a SQLite db.
>
> Is this normal/expected behavior ? is there a way to speed this up ?


All you've told us is that you have 460 tests. That doesn't tell us if
it's 460 simple tests, or 460 complicated tests, or some mix of the
two, or the hardware you are running on, or any of the other myriad
details that would enable us to give you any meaningful feedback on
how long you should expect 460 tests to take to run.

It's also impossible to answer whether model validators are to blame.
They're not known a-priori to be exceptionally slow, although some do
require database queries, which might be the cause of a slowdown.
Whether that explains your problems is impossible to tell without more
details.

The only indicative value I can give you is that Django's own test
suite consists of 2300 tests, and takes about 5 minutes to run on my 3
year old MacBook Pro under SQLite.

> We have some custom code both for the test running and for making the
> project works therefore if this not not a normal behavior I suspect
> that the problem may lie in there.

The best way to answer this is to run a profiler over your code, and
see where the hotspots are.

Yours,
Russ Magee %-)

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



Re: How long is a model validation heavy testsuite supposed to run?

2010-10-13 Thread Jonathan Barratt
On 13 ?.?. 2010, at 2:31, Jorge Vargas wrote:

> Hello,
> 
> I recently inherited a project that uses a lot of model validations
> and is mainly just a model (we have two django apps that use it as
> their backend).
> 
> The test suite currently returns
> 
> Ran 460 tests in 980.347s
> That is running on a SQLite db.
> 
> Is this normal/expected behavior ? is there a way to speed this up ?

A database migration might not be the sort of effort you were looking for, but 
I can only imagine that moving from SQLite to Postgres or MySQL would offer you 
the largest possible performance gains...

0.02,
Jonathan

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



How long is a model validation heavy testsuite supposed to run?

2010-10-12 Thread Jorge Vargas
Hello,

I recently inherited a project that uses a lot of model validations
and is mainly just a model (we have two django apps that use it as
their backend).

The test suite currently returns

Ran 460 tests in 980.347s
That is running on a SQLite db.

Is this normal/expected behavior ? is there a way to speed this up ?

We have some custom code both for the test running and for making the
project works therefore if this not not a normal behavior I suspect
that the problem may lie in there.

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



Re: Model Validation - Prevent Datetimefield overlaps?

2010-08-30 Thread Karen Tracey
On Mon, Aug 30, 2010 at 10:34 PM, Victor Hooi  wrote:

> Just playing around - I noticed that setting "unique=True" on a
> DateTimeField() doesn't seem to work? As in, I was able to do
> something like:
>
> b1 =
>
> BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
>
> end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=10,bytes_out=10)
> b1.save()
> b2 =
>
> BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
>
> end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=20,bytes_out=20)
> b2.save()
>
> Is this expected behaviour, or do I have something wrong with my
> setup?
>

Did you add the unique=True to the fields after you had already run syncdb
to create the table?  If so, the database constraints to require the field
to be unique won't be in place. (And re-running syncdb won't create the
constraints either, since syncdb won't do anything for models with tables
that already exist.)

Karen
-- 
http://tracey.org/kmt/

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



Model Validation - Prevent Datetimefield overlaps?

2010-08-30 Thread Victor Hooi
heya,

I have a model that contains a whole bunch of bytes in/out for
datetime ranges. I.e.:

class BandwidthUsageEntry(models.Model):
start_of_usage_block = models.DateTimeField()
end_of_usage_block = models.DateTimeField()
bytes_in = models.IntegerField()
bytes_out = models.IntegerField()

I need to ensure that each entry doesn't overlap with any others
entries.

Just playing around - I noticed that setting "unique=True" on a
DateTimeField() doesn't seem to work? As in, I was able to do
something like:

b1 =
BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=10,bytes_out=10)
b1.save()
b2 =
BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=20,bytes_out=20)
b2.save()

Is this expected behaviour, or do I have something wrong with my
setup?

Anyhow, in terms of how to actually prevent overlaps, I assume that
the best way is to use a custom model validator, and check each start/
end against a query against all the entries?

(I saw this 
http://stackoverflow.com/questions/2243490/django-unique-time-interval-for-the-admin-panel,
but it seems to be going a different way that I don't follow).

How would I go about structuring this? Any particular tips here, or
any algorithms that could work well?

Cheers,
Victor

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



Re: Model validation for non-django-orm databases

2010-08-30 Thread Owen Nelson
Sounds good.  Thanks for the advice!

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



Re: Model validation for non-django-orm databases

2010-08-30 Thread David De La Harpe Golden
On 30/08/10 15:12, Owen Nelson wrote:

>  I just started to wonder if the ORM would, I don't
> know... "freak out" on the off-chance I run a query that returns a set of
> objects with duplicate values on what is supposed to be the pk.

Nah, you just get multiple objects back with the same "pk", mapped from
different rows. At least, at the moment...

But therefore one other thing to watch out for is that such multiple
objects themselves will, unless you take further steps, compare True
under '==', even if they really represent different rows in the
underlying db, since django basically checks if self.pk == other.pk [1]

# this is a model wrapping a table with a key (bug_id, field_id),
# and field_id is the arbitrarily chosen fake pk for ORM purposes
l = PMSM_CustomFieldString.objects.filter(field_id=4)
a = l[0]
b = l[1]
# those are definitely different objects for different rows, but:
print a.bug_id == b.bug_id
False
print a is b
False
print a == b
True

And also watch out for things like hashing, as a few lines below [1]
shows, django also similarly uses the pk as the __hash__ of such objects.

If you're anything like us, you're probably just iterating through
queryset results to suck data out, so it doesn't matter too much. You
could just make sure to use field values from the objects, not the
object itself, or maybe overriding the relevant __blah__ would work.

Mind you, if you do have very complicated needs, do also bear in mind a
whole other library, SQLAlchemy, does have composite field support, it's
just generally more complex than Django ORM.

[1]
http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py#L355

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



Re: Model validation for non-django-orm databases

2010-08-30 Thread Owen Nelson
> With the hack i think you mean, it doesn't matter, just pick one, the
> point of the hack is you just shamelessly lie to the django ORM. So make
> sure to make your model ummanaged and _don't_ try to save.
>

Excellent.  Yeah, I'd been planning on overriding save() to make it raise
NotImplementedError (it's a read-only database after all).


> I'm not sure about django 1.2+ model validation with the hack, though,
> or even just django 1.2.  We use the hack - but presently with 1.1.
>

Good deal.  I'd be targeting 1.2+ so I'll just have to wait and see I guess.


Looking at the docs, you're presumably not using a ModelForm, and if
> you're explicitly using Model.full_clean() or clean_fields() you can
> probably pass in an exclude=... to exclude the field(s) that you're
> lying to django about if need be.  Based on the docs rather than
> experience, I don't think django model calls validators on initial
> load/init, it has to be by ModelForm calling them on the model, or just
> explictly calling one of the model clean methods.
>

Ok, great.  If validation only takes place during operations normally
associated with insert/update (like ModelForm.save(), or Model.save()), I
should be good to go.  I just started to wonder if the ORM would, I don't
know... "freak out" on the off-chance I run a query that returns a set of
objects with duplicate values on what is supposed to be the pk.

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



Re: Model validation for non-django-orm databases

2010-08-30 Thread David De La Harpe Golden
On 30/08/10 06:07, onelson wrote:

> I've read that a "hack" around this kind of issue is to use the meta
> unique_together property and almost arbitrarily set primary_key on one
> of the fields.  That sounds great, except for the fact that I've got
> no guarantee that any given field will actually be unique -- which
> column do I add the primary_key to? 

With the hack i think you mean, it doesn't matter, just pick one, the
point of the hack is you just shamelessly lie to the django ORM. So make
sure to make your model ummanaged and _don't_ try to save.

N.B. I would assume that you're thoroughly on your own with this hack, I
wouldn't expect django to officially support it. Maybe one day someone
will make something like (for argument's sake)

foo = models.PositiveIntegerField()
bar = models.PositiveIntegerField()
foobar = models.CompositeField(['foo', 'bar'], primary_key=True)

work, but right now it doesn't.

> loads/validates I'm happy.

I'm not sure about django 1.2+ model validation with the hack, though,
or even just django 1.2.  We use the hack - but presently with 1.1.

Looking at the docs, you're presumably not using a ModelForm, and if
you're explicitly using Model.full_clean() or clean_fields() you can
probably pass in an exclude=... to exclude the field(s) that you're
lying to django about if need be.  Based on the docs rather than
experience, I don't think django model calls validators on initial
load/init, it has to be by ModelForm calling them on the model, or just
explictly calling one of the model clean methods.


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



Model validation for non-django-orm databases

2010-08-29 Thread onelson
I've got an external (read-only) database that I'd like to hook into
an app I'm working on -- it violates django's pk assumption by using
composite keys.

I'm hoping that, given a couple of assumptions of my own, I can hook
these tables up to the ORM without having the universe implode.
Since the database is read-only, I don't need (or want) the content to
be accessible via the admin site.
Queries against the tables with composite keys will never (in my own
code) make reference to pk, I'll always be using N values for the
fields that make up the composite key.

I've read that a "hack" around this kind of issue is to use the meta
unique_together property and almost arbitrarily set primary_key on one
of the fields.  That sounds great, except for the fact that I've got
no guarantee that any given field will actually be unique -- which
column do I add the primary_key to?  Basically, since the content is
being generated externally, and integrity is being managed on that
end, do I need to worry about this?

As long as the model loads/validates I'm happy.  Is there anything I
need to look out for here?

Best regards,
Owen Nelson

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



model validation with admin.TabularInline

2010-08-20 Thread bagheera


Take a look into pool app from django tutorial. How can i make validation  
of Question model to have at least two Answer entered, if  
admin.TabularInline is used?


http://docs.djangoproject.com/en/1.2/intro/tutorial02/#adding-related-objects

--
Linux user

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



Re: Admin Model Validation on ManyToMany Field

2010-07-15 Thread Heleen
Thanks very much for your reply!
I got it working now. At first I couldn't get my head around how it
would work using the clean of the intermediary model. But after a
night's sleep it made sense to me.
In the Admin my Permission model (the users field) is an inline of
Application and when I put the validation on Permission it also
automatically works in the Application Admin.

So now I have:

admin.py
class PermissionInline(admin.TabularInline):
form = PermissionForm
model = Permission
extra = 3

forms.py
class PermissionForm(forms.ModelForm):
class Meta:
model = Permission

def clean(self):
cleaned_data = self.cleaned_data
user = cleaned_data['user']
role = cleaned_data['role']
if role.id != 1:
folder = cleaned_data['application'].folder
if len(filter(lambda x:x in
user.profile.company.all(),folder.company.all())) > 0: # this is an
intersection
raise forms.ValidationError("One of the users of this
Application works for one of the Repository's organisations!")
return cleaned_data

And this works!

On Jul 14, 5:16 pm, jaymzcd  wrote:
> Hi Heleen,
>
> I think this is because your running the users through an intermediate
> model. That changes the way you need to work with the M2M data. You
> should be working on the Permission model/objects instead. If you
> check out the M2M docs for models via an intermediate:
>
> http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-o...
>
> You'll see the example is pretty much what you have only with Group
> instead of Application.
>
> "The only way to create this type of relationship is to create
> instances of the intermediate model. Unlike normal many-to-many
> fields, you can't use add, create, or assignment (i.e.,
> beatles.members = [...]) to create relationships:"
>
> jaymz
>
> On Jul 14, 2:32 pm, Heleen  wrote:
>
> > Thank you for your reply.
>
> > Yes I have selected a user and folder.
> > I believe ManyToMany fields are always optional (hence many to many).
> > So my users and company fields are optional, but my folder field
> > isn't.
> > When I add a new Application in the Admin I do specify a folder and
> > users (if I don't I would at least get a 'Required field' error for
> > the folder field).
> > I've tested the method above (clean function) with another model that
> > has a manytomany field, and it does exactly the same thing, even when
> > I really do fill in the data. In fact, if I delibirately throw an
> > error and look in the debug info I can see the ManyToMany field data
> > being present in the POST data, just like I can when I do the same
> > thing with the above models.
>
> > Btw, I just noticed a typo in my Folder model description above,
> > that's not the issue as it's correct in my original model.
>
> > On Jul 14, 2:02 pm, Nuno Maltez  wrote:
>
> > > Hi,
>
> > > Just a guess: have you actually selected a user and a folder when
> > > submitting the form? I think only valid field are present on the
> > > cleaned_data dict, and your users and folder fields are not optional
> > > (blank=True, null=True).
>
> > > hth,
> > > nuno
>
> > > On Tue, Jul 13, 2010 at 1:45 PM, Heleen  wrote:
> > > > Hello,
>
> > > > I have the following classes:
> > > > class Application(models.Model):
> > > >  users = models.ManyToManyField(User, through='Permission')
> > > >  folder = models.ForeignKey(Folder)
>
> > > > class Folder(models.Model):
> > > >  company = models.ManyToManyField(Compnay)
>
> > > > class UserProfile(models.Model):
> > > >  user = models.OneToOneField(User, related_name='profile')
> > > >  company = models.ManyToManyField(Company)
>
> > > > Now when I save application, I would like to check if the users do not
> > > > belong to the application's folder's companies.
> > > > I have posed this question before and someone came up with the
> > > > following sollution:
> > > > forms.py:
> > > > class ApplicationForm(ModelForm):
> > > >    class Meta:
> > > >        model = Application
>
> > > >    def clean(self):
> > > >        cleaned_data = self.cleaned_data
> > > >        users = cleaned_data['users']
> > > >        folder = cleaned_data['folder']
> > > >        if
> > > > users.filter(profile__company__in=folder.company.all()).count() > 0:
> > > >            raise forms.ValidationError('One of the users of this
> > > > Application works in one of the Folder companies!')
> > > >        return cleaned_data
>
> > > > admin.py
> > > > class ApplicationAdmin(ModelAdmin):
> > > >    form = ApplicationForm
>
> > > > This seems like right the way to go about this. The problem is that
> > > > neither the users nor folder fields are in the cleaned_data and I get
> > > > a keyerror when it hits the users = cleaned_data['users'] line.
>
> > > > I was hoping that someone here could explain to me why these
> > > > manytomany fields don't show up in 

Re: Admin Model Validation on ManyToMany Field

2010-07-14 Thread jaymzcd
Hi Heleen,

I think this is because your running the users through an intermediate
model. That changes the way you need to work with the M2M data. You
should be working on the Permission model/objects instead. If you
check out the M2M docs for models via an intermediate:

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

You'll see the example is pretty much what you have only with Group
instead of Application.

"The only way to create this type of relationship is to create
instances of the intermediate model. Unlike normal many-to-many
fields, you can't use add, create, or assignment (i.e.,
beatles.members = [...]) to create relationships:"

jaymz

On Jul 14, 2:32 pm, Heleen  wrote:
> Thank you for your reply.
>
> Yes I have selected a user and folder.
> I believe ManyToMany fields are always optional (hence many to many).
> So my users and company fields are optional, but my folder field
> isn't.
> When I add a new Application in the Admin I do specify a folder and
> users (if I don't I would at least get a 'Required field' error for
> the folder field).
> I've tested the method above (clean function) with another model that
> has a manytomany field, and it does exactly the same thing, even when
> I really do fill in the data. In fact, if I delibirately throw an
> error and look in the debug info I can see the ManyToMany field data
> being present in the POST data, just like I can when I do the same
> thing with the above models.
>
> Btw, I just noticed a typo in my Folder model description above,
> that's not the issue as it's correct in my original model.
>
> On Jul 14, 2:02 pm, Nuno Maltez  wrote:
>
>
>
> > Hi,
>
> > Just a guess: have you actually selected a user and a folder when
> > submitting the form? I think only valid field are present on the
> > cleaned_data dict, and your users and folder fields are not optional
> > (blank=True, null=True).
>
> > hth,
> > nuno
>
> > On Tue, Jul 13, 2010 at 1:45 PM, Heleen  wrote:
> > > Hello,
>
> > > I have the following classes:
> > > class Application(models.Model):
> > >  users = models.ManyToManyField(User, through='Permission')
> > >  folder = models.ForeignKey(Folder)
>
> > > class Folder(models.Model):
> > >  company = models.ManyToManyField(Compnay)
>
> > > class UserProfile(models.Model):
> > >  user = models.OneToOneField(User, related_name='profile')
> > >  company = models.ManyToManyField(Company)
>
> > > Now when I save application, I would like to check if the users do not
> > > belong to the application's folder's companies.
> > > I have posed this question before and someone came up with the
> > > following sollution:
> > > forms.py:
> > > class ApplicationForm(ModelForm):
> > >    class Meta:
> > >        model = Application
>
> > >    def clean(self):
> > >        cleaned_data = self.cleaned_data
> > >        users = cleaned_data['users']
> > >        folder = cleaned_data['folder']
> > >        if
> > > users.filter(profile__company__in=folder.company.all()).count() > 0:
> > >            raise forms.ValidationError('One of the users of this
> > > Application works in one of the Folder companies!')
> > >        return cleaned_data
>
> > > admin.py
> > > class ApplicationAdmin(ModelAdmin):
> > >    form = ApplicationForm
>
> > > This seems like right the way to go about this. The problem is that
> > > neither the users nor folder fields are in the cleaned_data and I get
> > > a keyerror when it hits the users = cleaned_data['users'] line.
>
> > > I was hoping that someone here could explain to me why these
> > > manytomany fields don't show up in cleaned_data and that someone could
> > > possibly give me a sollution to my problem.
>
> > > Thanks!
> > > Heleen
>
> > > --
> > > You received this message because you are subscribed to the Google Groups 
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to 
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group 
> > > athttp://groups.google.com/group/django-users?hl=en.

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



Re: Admin Model Validation on ManyToMany Field

2010-07-14 Thread Nuno Maltez
On Wed, Jul 14, 2010 at 3:50 PM, Nuno Maltez  wrote:
> Sorry, I can't reproduce your error with django 1.2.
>
> I copied your models (just removed the intermediaty "Permission"
> because I don't know your User model) into a new app and I have 2

Oops, forgot to add i made the ManyToMany  a relation to django's User model.

Nuno

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



Re: Admin Model Validation on ManyToMany Field

2010-07-14 Thread Nuno Maltez
Sorry, I can't reproduce your error with django 1.2.

I copied your models (just removed the intermediaty "Permission"
because I don't know your User model) into a new app and I have 2
scenarios Adding an Application in the admin:

a) if I select a User and Folder, the validation runs just fine
b) if I do not select an User, then the "clean" method is still
accessed, but since 'users' is not present in the cleaned_data dict it
throws an exception - which is the scenario you give, hence my
original guess :)

Nuno

On Wed, Jul 14, 2010 at 2:32 PM, Heleen  wrote:
> Thank you for your reply.
>
> Yes I have selected a user and folder.
> I believe ManyToMany fields are always optional (hence many to many).
> So my users and company fields are optional, but my folder field
> isn't.
> When I add a new Application in the Admin I do specify a folder and
> users (if I don't I would at least get a 'Required field' error for
> the folder field).

> I've tested the method above (clean function) with another model that
> has a manytomany field, and it does exactly the same thing, even when
> I really do fill in the data. In fact, if I delibirately throw an
> error and look in the debug info I can see the ManyToMany field data
> being present in the POST data, just like I can when I do the same
> thing with the above models.
>
> Btw, I just noticed a typo in my Folder model description above,
> that's not the issue as it's correct in my original model.
>
> On Jul 14, 2:02 pm, Nuno Maltez  wrote:
>> Hi,
>>
>> Just a guess: have you actually selected a user and a folder when
>> submitting the form? I think only valid field are present on the
>> cleaned_data dict, and your users and folder fields are not optional
>> (blank=True, null=True).
>>
>> hth,
>> nuno
>>
>> On Tue, Jul 13, 2010 at 1:45 PM, Heleen  wrote:
>> > Hello,
>>
>> > I have the following classes:
>> > class Application(models.Model):
>> >  users = models.ManyToManyField(User, through='Permission')
>> >  folder = models.ForeignKey(Folder)
>>
>> > class Folder(models.Model):
>> >  company = models.ManyToManyField(Compnay)
>>
>> > class UserProfile(models.Model):
>> >  user = models.OneToOneField(User, related_name='profile')
>> >  company = models.ManyToManyField(Company)
>>
>> > Now when I save application, I would like to check if the users do not
>> > belong to the application's folder's companies.
>> > I have posed this question before and someone came up with the
>> > following sollution:
>> > forms.py:
>> > class ApplicationForm(ModelForm):
>> >    class Meta:
>> >        model = Application
>>
>> >    def clean(self):
>> >        cleaned_data = self.cleaned_data
>> >        users = cleaned_data['users']
>> >        folder = cleaned_data['folder']
>> >        if
>> > users.filter(profile__company__in=folder.company.all()).count() > 0:
>> >            raise forms.ValidationError('One of the users of this
>> > Application works in one of the Folder companies!')
>> >        return cleaned_data
>>
>> > admin.py
>> > class ApplicationAdmin(ModelAdmin):
>> >    form = ApplicationForm
>>
>> > This seems like right the way to go about this. The problem is that
>> > neither the users nor folder fields are in the cleaned_data and I get
>> > a keyerror when it hits the users = cleaned_data['users'] line.
>>
>> > I was hoping that someone here could explain to me why these
>> > manytomany fields don't show up in cleaned_data and that someone could
>> > possibly give me a sollution to my problem.
>>
>> > Thanks!
>> > Heleen
>>
>> > --
>> > You received this message because you are subscribed to the Google Groups 
>> > "Django users" group.
>> > To post to this group, send email to django-us...@googlegroups.com.
>> > To unsubscribe from this group, send email to 
>> > django-users+unsubscr...@googlegroups.com.
>> > For more options, visit this group 
>> > athttp://groups.google.com/group/django-users?hl=en.
>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Admin Model Validation on ManyToMany Field

2010-07-14 Thread Heleen
Thank you for your reply.

Yes I have selected a user and folder.
I believe ManyToMany fields are always optional (hence many to many).
So my users and company fields are optional, but my folder field
isn't.
When I add a new Application in the Admin I do specify a folder and
users (if I don't I would at least get a 'Required field' error for
the folder field).
I've tested the method above (clean function) with another model that
has a manytomany field, and it does exactly the same thing, even when
I really do fill in the data. In fact, if I delibirately throw an
error and look in the debug info I can see the ManyToMany field data
being present in the POST data, just like I can when I do the same
thing with the above models.

Btw, I just noticed a typo in my Folder model description above,
that's not the issue as it's correct in my original model.

On Jul 14, 2:02 pm, Nuno Maltez  wrote:
> Hi,
>
> Just a guess: have you actually selected a user and a folder when
> submitting the form? I think only valid field are present on the
> cleaned_data dict, and your users and folder fields are not optional
> (blank=True, null=True).
>
> hth,
> nuno
>
> On Tue, Jul 13, 2010 at 1:45 PM, Heleen  wrote:
> > Hello,
>
> > I have the following classes:
> > class Application(models.Model):
> >  users = models.ManyToManyField(User, through='Permission')
> >  folder = models.ForeignKey(Folder)
>
> > class Folder(models.Model):
> >  company = models.ManyToManyField(Compnay)
>
> > class UserProfile(models.Model):
> >  user = models.OneToOneField(User, related_name='profile')
> >  company = models.ManyToManyField(Company)
>
> > Now when I save application, I would like to check if the users do not
> > belong to the application's folder's companies.
> > I have posed this question before and someone came up with the
> > following sollution:
> > forms.py:
> > class ApplicationForm(ModelForm):
> >    class Meta:
> >        model = Application
>
> >    def clean(self):
> >        cleaned_data = self.cleaned_data
> >        users = cleaned_data['users']
> >        folder = cleaned_data['folder']
> >        if
> > users.filter(profile__company__in=folder.company.all()).count() > 0:
> >            raise forms.ValidationError('One of the users of this
> > Application works in one of the Folder companies!')
> >        return cleaned_data
>
> > admin.py
> > class ApplicationAdmin(ModelAdmin):
> >    form = ApplicationForm
>
> > This seems like right the way to go about this. The problem is that
> > neither the users nor folder fields are in the cleaned_data and I get
> > a keyerror when it hits the users = cleaned_data['users'] line.
>
> > I was hoping that someone here could explain to me why these
> > manytomany fields don't show up in cleaned_data and that someone could
> > possibly give me a sollution to my problem.
>
> > Thanks!
> > Heleen
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Admin Model Validation on ManyToMany Field

2010-07-14 Thread Nuno Maltez
Hi,

Just a guess: have you actually selected a user and a folder when
submitting the form? I think only valid field are present on the
cleaned_data dict, and your users and folder fields are not optional
(blank=True, null=True).

hth,
nuno

On Tue, Jul 13, 2010 at 1:45 PM, Heleen  wrote:
> Hello,
>
> I have the following classes:
> class Application(models.Model):
>  users = models.ManyToManyField(User, through='Permission')
>  folder = models.ForeignKey(Folder)
>
> class Folder(models.Model):
>  company = models.ManyToManyField(Compnay)
>
> class UserProfile(models.Model):
>  user = models.OneToOneField(User, related_name='profile')
>  company = models.ManyToManyField(Company)
>
> Now when I save application, I would like to check if the users do not
> belong to the application's folder's companies.
> I have posed this question before and someone came up with the
> following sollution:
> forms.py:
> class ApplicationForm(ModelForm):
>    class Meta:
>        model = Application
>
>    def clean(self):
>        cleaned_data = self.cleaned_data
>        users = cleaned_data['users']
>        folder = cleaned_data['folder']
>        if
> users.filter(profile__company__in=folder.company.all()).count() > 0:
>            raise forms.ValidationError('One of the users of this
> Application works in one of the Folder companies!')
>        return cleaned_data
>
> admin.py
> class ApplicationAdmin(ModelAdmin):
>    form = ApplicationForm
>
> This seems like right the way to go about this. The problem is that
> neither the users nor folder fields are in the cleaned_data and I get
> a keyerror when it hits the users = cleaned_data['users'] line.
>
> I was hoping that someone here could explain to me why these
> manytomany fields don't show up in cleaned_data and that someone could
> possibly give me a sollution to my problem.
>
> Thanks!
> Heleen
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Admin Model Validation on ManyToMany Field

2010-07-13 Thread Heleen
Hello,

I have the following classes:
class Application(models.Model):
 users = models.ManyToManyField(User, through='Permission')
 folder = models.ForeignKey(Folder)

class Folder(models.Model):
 company = models.ManyToManyField(Compnay)

class UserProfile(models.Model):
 user = models.OneToOneField(User, related_name='profile')
 company = models.ManyToManyField(Company)

Now when I save application, I would like to check if the users do not
belong to the application's folder's companies.
I have posed this question before and someone came up with the
following sollution:
forms.py:
class ApplicationForm(ModelForm):
class Meta:
model = Application

def clean(self):
cleaned_data = self.cleaned_data
users = cleaned_data['users']
folder = cleaned_data['folder']
if
users.filter(profile__company__in=folder.company.all()).count() > 0:
raise forms.ValidationError('One of the users of this
Application works in one of the Folder companies!')
return cleaned_data

admin.py
class ApplicationAdmin(ModelAdmin):
form = ApplicationForm

This seems like right the way to go about this. The problem is that
neither the users nor folder fields are in the cleaned_data and I get
a keyerror when it hits the users = cleaned_data['users'] line.

I was hoping that someone here could explain to me why these
manytomany fields don't show up in cleaned_data and that someone could
possibly give me a sollution to my problem.

Thanks!
Heleen

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



Re: Model validation (not form validation)

2010-06-17 Thread derek
On Jun 16, 8:20 am, MH  wrote:
> Hi,
> I'm making a model, that has a bit complex dependencies between the fields,
> such as date progression (start_date must not be later than finish_date).
> I'm looking for a way to validate these dependencies while creating (or
> saving) the model, but I am not sure which approach should I use.
>
> The best solution would be overriding Model's method *clean*, but this seems
> to work only when working with forms. Another solution utilizes pre_save()
> or save() methods.
>
> Which one is the "proper" one?
>
> Regards,
> Mateusz Haligowski

There's a good example at:
http://www.jroller.com/RickHigh/entry/django_admin_and_field_validation

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



Model validation (not form validation)

2010-06-16 Thread MH
Hi,
I'm making a model, that has a bit complex dependencies between the fields,
such as date progression (start_date must not be later than finish_date).
I'm looking for a way to validate these dependencies while creating (or
saving) the model, but I am not sure which approach should I use.

The best solution would be overriding Model's method *clean*, but this seems
to work only when working with forms. Another solution utilizes pre_save()
or save() methods.

Which one is the "proper" one?

Regards,
Mateusz Haligowski

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



model validation fails if a field is excluded in the modelform

2010-02-09 Thread Kenneth Gonsalves
hi,

I have a modelForm for a model where one field is excluded. One of the lines in 
my model validation needs that field - so model validation fails with a 
'DoesNotExist' error. How does one get round this? The relevant parts of the 
model and the traceback are appended. The field excluded is 'player'.

model:

class Handicap(models.Model):
"""just name and handicap index - how to handle validity?"""
player = models.ForeignKey(Player,verbose_name=_("Player"))
handicap = models.DecimalField(_("Handicap index"),max_digits=3, 
decimal_places=1)
valfrom = models.DateField(_("Valid from"))
valto = models.DateField(_("Valid to"))
class Meta:
unique_together = ('player','valto')

def clean(self):

if self.valfrom >= self.valto:
raise ValidationError(_("from date should be less than to date"))
for hand in self.player.handicap_set.all():
if self.valto == hand.valto:
raise ValidationError(_("There is another handicap with the 
same to date"))

traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/addhandicap/1/
Django Version: 1.2 beta 1 SVN-12403
Python Version: 2.6.0
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'djangogolf.web']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')


Traceback:
File "/usr/lib/python2.6/django/core/handlers/base.py" in get_response
  101. response = callback(request, *callback_args, 
**callback_kwargs)
File "/usr/lib/python2.6/django/contrib/auth/decorators.py" in _wrapped_view
  24. return view_func(request, *args, **kwargs)
File "/home/lawgon/djangogolf/../djangogolf/web/views.py" in addhandicap
  628. if form.is_valid():
File "/usr/lib/python2.6/django/forms/forms.py" in is_valid
  120. return self.is_bound and not bool(self.errors)
File "/usr/lib/python2.6/django/forms/forms.py" in _get_errors
  111. self.full_clean()
File "/usr/lib/python2.6/django/forms/forms.py" in full_clean
  267. self._clean_form()
File "/usr/lib/python2.6/django/forms/models.py" in _clean_form
  318. self.instance.clean()
File "/home/lawgon/djangogolf/../djangogolf/web/models.py" in clean
  163. for hand in self.player.handicap_set.all():
File "/usr/lib/python2.6/django/db/models/fields/related.py" in __get__
  264. raise self.field.rel.to.DoesNotExist

Exception Type: DoesNotExist at /addhandicap/1/
Exception Value: 
-- 
regards
Kenneth Gonsalves
Senior Project Officer
NRC-FOSS
http://nrcfosshelpline.in/web/

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



Re: False negatives on model validation of CharField with choices

2010-01-29 Thread Thomas B. Higgins
Ramiro, great work on this! With your second patch I'm back in
business - with optgroups!

On a related matter, I don't often want a "blank" option when I use
choices/selects. I've been setting default selections and eliminating
the "blank" line as described on 11/07/07 by semenov in #4653 using a
combination of an explicit blank=False and a declared default value.
Under 1.1.1, this worked even when the field was disabled by
JavaScript (disabled because it was only conditionally required). I
had assumed that the default value was sent along to the database, but
don't really care. There was a big debate over what the convention for
"no blank choice" should be in #4653.

Now, using the development version, I can say blank=True, define a
default and get no blank option for some fields, while with other
fields with the same, identical model attribute structure yields a
select with the blank option. The only difference being that the
former group have "choices=something, required=False" in the model
form. Is the new convention that required=False in the model form
means no blank choice? This is wholly illogical to me.

Do you think this is an oversight? Is this new state of affairs
documented somewhere? Do you think it warrants a ticket?

Thanks for all your help.

Tom

On Jan 29, 5:13 am, Ramiro Morales  wrote:
> On Thu, Jan 28, 2010 at 2:46 PM, Thomas B.Higgins
>
>  wrote:
> > I've done some further checking, and see that this issue has two
> > parts. The first part is certainly a bug. Basically, selects with
> > optgroups are broken. Here's the 
> > ticket:http://code.djangoproject.com/ticket/12722.
>
> Sorry I didn't reply before, I had been offline.
>
> This has been already reported in ticket [1]12667. Please test the
> patch attached to
> it and report back your experiences.
>
> Regards,
>
> 1.http://code.djangoproject.com/ticket/12667
>
> --
> Ramiro Morales  |  http://rmorales.net

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



Re: False negatives on model validation of CharField with choices

2010-01-29 Thread Thomas B. Higgins
Ramiro, great work on this! With your second patch I'm back in
business - with optgroups!

On a related matter, I don't often want a "blank" option when I use
choices/selects. I've been setting default selections and eliminating
the "blank" line as described on 11/07/07 by semenov in #4653 using a
combination of an explicit blank=False and a declared default value.
Under 1.1.1, this worked even when the field was disabled by
JavaScript (disabled because it was only conditionally required). I
had assumed that the default value was sent along to the database, but
don't really care. There was a big debate over what the convention for
"no blank choice" should be in #4653.

Now, using the development version, I can say blank=True, define a
default and get no blank option for some fields, while with other
fields with the same, identical model attribute structure yields a
select with the blank option. The only difference being that the
former group have "choices=something, required=False" in the model
form. Is the new convention that required=False in the model form
means no blank choice? This is wholly illogical to me.

Do you think this is an oversight? Is this new state of affairs
documented somewhere? Do you think it warrants a ticket?

Thanks for all your help.

Tom

On Jan 29, 5:13 am, Ramiro Morales  wrote:
> On Thu, Jan 28, 2010 at 2:46 PM, Thomas B.Higgins
>
>  wrote:
> > I've done some further checking, and see that this issue has two
> > parts. The first part is certainly a bug. Basically, selects with
> > optgroups are broken. Here's the 
> > ticket:http://code.djangoproject.com/ticket/12722.
>
> Sorry I didn't reply before, I had been offline.
>
> This has been already reported in ticket [1]12667. Please test the
> patch attached to
> it and report back your experiences.
>
> Regards,
>
> 1.http://code.djangoproject.com/ticket/12667
>
> --
> Ramiro Morales  |  http://rmorales.net

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



Re: False negatives on model validation of CharField with choices

2010-01-29 Thread Ramiro Morales
On Thu, Jan 28, 2010 at 2:46 PM, Thomas B. Higgins
 wrote:
> I've done some further checking, and see that this issue has two
> parts. The first part is certainly a bug. Basically, selects with
> optgroups are broken. Here's the ticket: 
> http://code.djangoproject.com/ticket/12722.

Sorry I didn't reply before, I had been offline.

This has been already reported in ticket [1]12667. Please test the
patch attached to
it and report back your experiences.

Regards,

1. http://code.djangoproject.com/ticket/12667

-- 
Ramiro Morales  |  http://rmorales.net

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



Re: False negatives on model validation of CharField with choices

2010-01-28 Thread Thomas B. Higgins
I've done some further checking, and see that this issue has two
parts. The first part is certainly a bug. Basically, selects with
optgroups are broken. Here's the ticket: 
http://code.djangoproject.com/ticket/12722.

The second part is that if, on a choice field, blank=False, the model
won't validate unless there is a selection, even if a default is
supplied. So, if the field has been disabled, there will be an error.
This is different from previous Django behavior, but probably doesn't
matter much to me, now that I know what is happening.

On Jan 27, 10:44 pm, "Thomas B. Higgins" <thomasbhigg...@gmail.com>
wrote:
> I am writing to see if anyone thinks this is not a bug before creating
> a new ticket. I have an app that runs as expected on Django 1.1.1. It
> used to work on the development version, but a problem arose no later
> than 1.2 alpha 1 SVN-12271, and perhaps much earlier.
>
> Basically, the errors dictionary is wrong for every CharField with
> choices in the model. My custom validation continues to work, except
> when overridden by default validation. When my custom validation is
> commented out, the picture becomes clearer:
>
> 1)  An error "Value u"A325" is not a valid choice" is reported for a
> select field with no possibility of selecting a blank when any of the
> four available choices is selected. Elimination of the "blank" line is
> handled as described on 11/07/07 by semenov 
> athttp://code.djangoproject.com/ticket/4653
> using a combination of an explicit blank=False and a declared default
> value. This is baffling. I cannot conceive of a reason for an error in
> this case.
>
> 2) An error of "This field cannot be blank" is reported for fields
> with a default named in the model, such as:
>
> stiff_pl_grade    = models.CharField(max_length=8, choices=PL_grades,
> blank=False, default="A36",
>     help_text="Stiffener PL grade")
>
> It is my understanding that if a default is supplied, it should not be
> necessary to fill the field, even if blank=False.
>
> FloatFields with choices and IntegerFields with choices continue to
> behave as expected.
>
> It seems clear that when the is_valid() method is run on the form,
> something bad is happening to CharFields with choices, and this type
> of field only, and perfectly valid string selections or string
> defaults are being reported as invalid, probably by automatic model
> validation.
>
> My code works fine under version 1.1.1 and I see nothing in the
> development documentation to explain this odd new behavior.
>
> Any thoughts?

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



Re: False negatives on model validation of CharField with choices

2010-01-28 Thread Karen Tracey
On Thu, Jan 28, 2010 at 1:44 AM, Thomas B. Higgins <thomasbhigg...@gmail.com
> wrote:

> It seems clear that when the is_valid() method is run on the form,
> something bad is happening to CharFields with choices, and this type
> of field only, and perfectly valid string selections or string
> defaults are being reported as invalid, probably by automatic model
> validation.
>
> My code works fine under version 1.1.1 and I see nothing in the
> development documentation to explain this odd new behavior.
>
> Any thoughts?
>


What you are describing is not ringing any bells and I cannot recreate
aything like what you are saying in some attempts to duplicate based on
the vague prose description.  Posting some of the actual code you are using
to define, create, and process the form you are talking about might help.

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-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



False negatives on model validation of CharField with choices

2010-01-27 Thread Thomas B. Higgins
I am writing to see if anyone thinks this is not a bug before creating
a new ticket. I have an app that runs as expected on Django 1.1.1. It
used to work on the development version, but a problem arose no later
than 1.2 alpha 1 SVN-12271, and perhaps much earlier.

Basically, the errors dictionary is wrong for every CharField with
choices in the model. My custom validation continues to work, except
when overridden by default validation. When my custom validation is
commented out, the picture becomes clearer:

1)  An error "Value u"A325" is not a valid choice" is reported for a
select field with no possibility of selecting a blank when any of the
four available choices is selected. Elimination of the "blank" line is
handled as described on 11/07/07 by semenov at 
http://code.djangoproject.com/ticket/4653
using a combination of an explicit blank=False and a declared default
value. This is baffling. I cannot conceive of a reason for an error in
this case.

2) An error of "This field cannot be blank" is reported for fields
with a default named in the model, such as:

stiff_pl_grade= models.CharField(max_length=8, choices=PL_grades,
blank=False, default="A36",
help_text="Stiffener PL grade")

It is my understanding that if a default is supplied, it should not be
necessary to fill the field, even if blank=False.

FloatFields with choices and IntegerFields with choices continue to
behave as expected.

It seems clear that when the is_valid() method is run on the form,
something bad is happening to CharFields with choices, and this type
of field only, and perfectly valid string selections or string
defaults are being reported as invalid, probably by automatic model
validation.

My code works fine under version 1.1.1 and I see nothing in the
development documentation to explain this odd new behavior.

Any thoughts?

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



Re: Model validation

2009-11-12 Thread rebus_
2009/11/12 Dirk Uys :
> On Thu, Nov 12, 2009 at 2:23 PM, rebus_  wrote:
>
>>
>> You can add custom clean methods in your form:
>>
>> class Event (models.Model):
>>    start_date = models.DateField()
>>    end_date = models.DateField()
>>
>>   def clean(self):
>>       start = self.cleaned_data.get('start_date', False)
>>       end = self.cleaned_data.get('end_date', False)
>>       if not start or not end:
>>          raise forms.ValidationError('message')
>>       if start > end:
>>          raise forms.ValidationError('start is greater then end')
>>       return self.cleaned_data
>>
>> This is just an example code.
>>
>> Using this approach validation errors will not be associated with and
>> field.
>> You could write clean_start_date and clean_end_date methods which
>> would evaluate each field and all validation errors would be
>> associated with specific field.
>>
>> To learn more about form validation read [1] or [2]:
>>
>> [1] http://docs.djangoproject.com/en/dev/ref/forms/validation/
>> [2]
>> http://code.djangoproject.com/browser/django/trunk/docs/ref/forms/validation.txt
>>
>
> Thanks! This is actually what I have done. The only problem is that I do not
> always use forms to supply data (sometimes I import from CVS) and would like
> to avoid doing the validation at two different points.
>
> For the time being, I guess this will do
>
> Cheers
> Dirk
>

Technically, i think you should be able iterate over dataset imported
from CVS and bound each data row to form, validate the form and then
use the cleaned_data to create an object of the Model and save it or
whatever. Not sure what performance impacts this would have, if any,
but i guess that would depend on the amount of data that needs
validation.

Take a look at [1] forms API for example.

Also you could factor out the clean code into standalone function for
example and then use that function to validate the given data both in
form and the place you use imported data.

But then again i am no guru on the subject, these are just my opinions.

[1] http://docs.djangoproject.com/en/dev/ref/forms/api/

--

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




Re: Model validation

2009-11-12 Thread Dirk Uys
On Thu, Nov 12, 2009 at 2:23 PM, rebus_  wrote:


> You can add custom clean methods in your form:
>
> class Event (models.Model):
>start_date = models.DateField()
>end_date = models.DateField()
>
>def clean(self):
>   start = self.cleaned_data.get('start_date', False)
>   end = self.cleaned_data.get('end_date', False)
>   if not start or not end:
>  raise forms.ValidationError('message')
>   if start > end:
>  raise forms.ValidationError('start is greater then end')
>   return self.cleaned_data
>
> This is just an example code.
>
> Using this approach validation errors will not be associated with and
> field.
> You could write clean_start_date and clean_end_date methods which
> would evaluate each field and all validation errors would be
> associated with specific field.
>
> To learn more about form validation read [1] or [2]:
>
> [1] http://docs.djangoproject.com/en/dev/ref/forms/validation/
> [2]
> http://code.djangoproject.com/browser/django/trunk/docs/ref/forms/validation.txt
>
>
Thanks! This is actually what I have done. The only problem is that I do not
always use forms to supply data (sometimes I import from CVS) and would like
to avoid doing the validation at two different points.

For the time being, I guess this will do

Cheers
Dirk

--

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




Re: Model validation

2009-11-12 Thread rebus_
2009/11/12 Dirk Uys :
> I have a model with a from and to date:
>
> class Event (models.Model):
>     start_date = models.DateField()
>     end_date = models.DateField()
>
> In order to ensure start_date is always before end_date i can think of 3
> options:
>
> 1. Use form validation iow in the clean method of an inherited form
> 2. Use the django.db.models.signals.pre_save signal
> 3. Create a custor field that takes an parameter of the date field wich must
> allways be greater than or less than
>
> What is the easiest way to achieve this?
>
> Regards
> Dirk
>
> --

You can add custom clean methods in your form:

class Event (models.Model):
start_date = models.DateField()
end_date = models.DateField()

   def clean(self):
   start = self.cleaned_data.get('start_date', False)
   end = self.cleaned_data.get('end_date', False)
   if not start or not end:
  raise forms.ValidationError('message')
   if start > end:
  raise forms.ValidationError('start is greater then end')
   return self.cleaned_data

This is just an example code.

Using this approach validation errors will not be associated with and field.
You could write clean_start_date and clean_end_date methods which
would evaluate each field and all validation errors would be
associated with specific field.

To learn more about form validation read [1] or [2]:

[1] http://docs.djangoproject.com/en/dev/ref/forms/validation/
[2] 
http://code.djangoproject.com/browser/django/trunk/docs/ref/forms/validation.txt

--

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




Model validation

2009-11-12 Thread Dirk Uys
I have a model with a from and to date:

class Event (models.Model):
start_date = models.DateField()
end_date = models.DateField()

In order to ensure start_date is always before end_date i can think of 3
options:

1. Use form validation iow in the clean method of an inherited form
2. Use the django.db.models.signals.pre_save signal
3. Create a custor field that takes an parameter of the date field wich must
allways be greater than or less than

What is the easiest way to achieve this?

Regards
Dirk

--

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




Re: model-validation: Excessive (and weird) queries during validation

2009-11-02 Thread Mark L.



On Nov 2, 10:27 pm, Karen Tracey <kmtra...@gmail.com> wrote:
> On Mon, Nov 2, 2009 at 1:41 PM, Mark L. <mark.l...@gmail.com> wrote:
>
> > As the subject states, I am using the model-validation branch at the
> > moment, which allows me to do, well, validation in the models.
>
> > I've however, noticed a very strange behaviour of the validation
> > logic, - any time  the clean() method is fired on the
> > "materialized" (saved or retrieved from the database) model, that
> > contains unique fields, the following query is fired (let me just give
> > you an example):
>
> > from django.db import models
>
> > class A(models.Model):
> >    pass
>
> > a = A.objects.create()
> > a.clean()
>
> > a.clean() results, among everything, in this: 'SELECT (1) AS "a" FROM
> > "val_a" WHERE ("val_a"."id" = 1 AND NOT ("val_a"."id" = 1 ))'
>
> > I might be missing something vital, but what is that "where" clause
> > there for? What is it supposed to check?
>
> It's trying to verify the uniqueness of the supposed-to-be-unique field id.
> The query makes sense for fields other than the primary key, where the WHERE
> clause turns out more like:
>
> WHERE model.unique_field = proposed_value AND NOT model.id =
> current_instance.pk
>
> That is, it's asking "Is there any other instance in the DB, besides this
> one I'm looking at, that has the proposed_value for this
> supposed-to-be-unique field?"  If the answer is no, then all is fine, the
> proposed value doesn't violate the unique constraint.  If the answer is yes,
> then the validation check needs to fail because saving this model instance
> to the DB would violate the unique constraint.
>
> Of course, it doesn't make sense for the primary key field.  For that field,
> when you exclude the current instance from the search the WHERE clause
> becomes impossible to satisfy.  The model validation code, I'd guess, has
> been moved from where it was initially implemented (ModelForms).  In its
> original place the primary key field would not ordinarily have been included
> in the list of unique fields to check because it wouldn't ordinarily be on
> the form, and only values on the form are checked for uniqueness.
>
> The code in the new place likely needs to realize the primary key field
> shouldn't be checked for uniqueness.  You could check to see if this has
> been reported in trac and if not open a ticket for it.  I don't recall it
> having been brought up by anyone else but I could have missed it.
>
> Karen

Thanks for the quick reply, Karen

I've investigated a bit and it seems, that the problem is just what
you've said - the logic, that decides whether the field needs to be
checked for uniqueness or not, just doesn't take into account the
fact, that the field might be a primary key. Should be an easy fix,
especially since it doesn't seem to affect the ModelForm validation.

I've created a ticket on the issue tracker with a demonstration of the
problem and the fix.

Either way, it should be noted, that adding unique fields to the
models (besides the obvious pk field), can cause extreme performance
drops. Imagine cleaning a collection of 200 or objects causing 200 db
queries to be run (I'll benchmark it later). Perhaps the uniqueness
check for the Model could be moved to save() instead of clean() just
for this one reason?

Mark
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: model-validation: Excessive (and weird) queries during validation

2009-11-02 Thread Karen Tracey
On Mon, Nov 2, 2009 at 1:41 PM, Mark L. <mark.l...@gmail.com> wrote:

>
> As the subject states, I am using the model-validation branch at the
> moment, which allows me to do, well, validation in the models.
>
> I've however, noticed a very strange behaviour of the validation
> logic, - any time  the clean() method is fired on the
> "materialized" (saved or retrieved from the database) model, that
> contains unique fields, the following query is fired (let me just give
> you an example):
>
> from django.db import models
>
> class A(models.Model):
>pass
>
> a = A.objects.create()
> a.clean()
>
> a.clean() results, among everything, in this: 'SELECT (1) AS "a" FROM
> "val_a" WHERE ("val_a"."id" = 1 AND NOT ("val_a"."id" = 1 ))'
>
> I might be missing something vital, but what is that "where" clause
> there for? What is it supposed to check?


It's trying to verify the uniqueness of the supposed-to-be-unique field id.
The query makes sense for fields other than the primary key, where the WHERE
clause turns out more like:

WHERE model.unique_field = proposed_value AND NOT model.id =
current_instance.pk

That is, it's asking "Is there any other instance in the DB, besides this
one I'm looking at, that has the proposed_value for this
supposed-to-be-unique field?"  If the answer is no, then all is fine, the
proposed value doesn't violate the unique constraint.  If the answer is yes,
then the validation check needs to fail because saving this model instance
to the DB would violate the unique constraint.

Of course, it doesn't make sense for the primary key field.  For that field,
when you exclude the current instance from the search the WHERE clause
becomes impossible to satisfy.  The model validation code, I'd guess, has
been moved from where it was initially implemented (ModelForms).  In its
original place the primary key field would not ordinarily have been included
in the list of unique fields to check because it wouldn't ordinarily be on
the form, and only values on the form are checked for uniqueness.

The code in the new place likely needs to realize the primary key field
shouldn't be checked for uniqueness.  You could check to see if this has
been reported in trac and if not open a ticket for it.  I don't recall it
having been brought up by anyone else but I could have missed it.

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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



model-validation: Excessive (and weird) queries during validation

2009-11-02 Thread Mark L.

As the subject states, I am using the model-validation branch at the
moment, which allows me to do, well, validation in the models.

I've however, noticed a very strange behaviour of the validation
logic, - any time  the clean() method is fired on the
"materialized" (saved or retrieved from the database) model, that
contains unique fields, the following query is fired (let me just give
you an example):

from django.db import models

class A(models.Model):
pass

a = A.objects.create()
a.clean()

a.clean() results, among everything, in this: 'SELECT (1) AS "a" FROM
"val_a" WHERE ("val_a"."id" = 1 AND NOT ("val_a"."id" = 1 ))'

I might be missing something vital, but what is that "where" clause
there for? What is it supposed to check? The stacktrace for the query
is the following:
787  clean django/db/models/base.py
619   validate django/db/models/base.py
624   validate_unique django/db/models/base.py
683   _perform_unique_checks django/db/models/base.py
112   __nonzero__ django/db/models/query.py
106   _result_iter django/db/models/query.py
692   _fill_cache django/db/models/query.py
756   iterator django/db/models/query.py
287   results_iter django/db/models/sql/query.py
2369 execute_sql django/db/models/sql/query.py

Apparently, it is happening inside the uniqueness check. Anyway, the
most strange thing, is that calling clean() results in a query. I've
noticed it when I was displaying a set of a few hundred objects (each
of them has to be cleaned before sending the data to template), which
resulted in a few hundred of queries (for a single request), which
brought my dev-machine to the knees. It becomes worse if the cleaned
model is a part of a table-inheritance hierarchy, - clean() is called
sequentially for every model "up" the hierarchy, which results in a
tremendous number of queries executed per single request.

I must say, however, that I, at this moment, have no idea how to check
for uniqueness *without* issuing a query and, from what I see, django
doesn't like to assume things, so the db hits *will* be made.

Obviously, I can swindle Django into not checking uniqueness on clean
(by rolling my own clean method in models.Model subclasses), however,
that doesn't sound like a very good idea (if alternatives exist).

Sorry if this is an inappropriate list/group for this question. Maybe
I should instead address it to the django-developers or the issue
tracker.

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Mutually exclusive fields in model validation

2009-09-16 Thread Daniel Roseman

On Sep 15, 11:19 pm, Sonal Breed <sonal.br...@gmail.com> wrote:
> Thanks a lot Cliff, I implemented it in a similar manner, just wanted
> to know if we
> have anything like validation rules a la Access.
>
> Thanks again,
> Sincerely,
> Sonal.

Not yet. Honza Kral's Google Summer of Code project for model
validation is due to be merged reasonably soon though, so this will be
in version 1.2 - or in trunk at some earlier point if you don't want
to wait that long.
--
DR.
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Mutually exclusive fields in model validation

2009-09-15 Thread Sonal Breed

Thanks a lot Cliff, I implemented it in a similar manner, just wanted
to know if we
have anything like validation rules a la Access.

Thanks again,
Sincerely,
Sonal.

On Sep 15, 3:08 pm, "J. Cliff Dyer"  wrote:
> Override the save method on your model, something like:
>
> class MyModel(models.Model):
>     field1 = models.TextField(blank=True)
>     field2 = models.TextField(blank=True)
>
>     def save(self):
>         if (self.field1 and self.field2):
>             raise ModelValidationError, "only one can live"
>         elif (not self.field1 and not self.field2):
>             raise ModelValidationError, "one must live"
>         else:
>             super(MyModel, self).save()
>
> Untested code.  I don't remember if ModelValidationError exists, and I
> don't know if you need to tweak the signature on your save method, but
> that should get you pointed in the right direction.
>
> Cheers,
> Cliff
>
> On Tue, 2009-09-15 at 14:33 -0700, Sonal Breed wrote:
> > Hi all,
>
> > I have a model wherein I want to put a validation as
> > You must enter Field1 or Field2, but not both.
>
> > This model is at the back end and not visible through forms.
> > How do I accomplish it?
>
> > Thanks,
>
> > Sincerely,
> > Sonal
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Mutually exclusive fields in model validation

2009-09-15 Thread J. Cliff Dyer

Override the save method on your model, something like:

class MyModel(models.Model):
field1 = models.TextField(blank=True)
field2 = models.TextField(blank=True)

def save(self):
if (self.field1 and self.field2):
raise ModelValidationError, "only one can live"
elif (not self.field1 and not self.field2):
raise ModelValidationError, "one must live"
else:
super(MyModel, self).save()

Untested code.  I don't remember if ModelValidationError exists, and I
don't know if you need to tweak the signature on your save method, but
that should get you pointed in the right direction.

Cheers,
Cliff


On Tue, 2009-09-15 at 14:33 -0700, Sonal Breed wrote:
> Hi all,
> 
> I have a model wherein I want to put a validation as
> You must enter Field1 or Field2, but not both.
> 
> This model is at the back end and not visible through forms.
> How do I accomplish it?
> 
> Thanks,
> 
> Sincerely,
> Sonal
> > 


--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Mutually exclusive fields in model validation

2009-09-15 Thread Sonal Breed

Hi all,

I have a model wherein I want to put a validation as
You must enter Field1 or Field2, but not both.

This model is at the back end and not visible through forms.
How do I accomplish it?

Thanks,

Sincerely,
Sonal
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: model validation errors

2009-09-01 Thread alain31

Ok so I will write a custom form.

 I think that I  will also write a custom field to do some specific
things (for example add a url method to get
png ...). I need to understand better the methods :

- contribute_to_class,
-validate, validate_full
-formfield

I found nothing in django's doc, and few examples with google. There
are some usuful stuff in  "pro Django" book
but I'm looking for other doc and examples. In particular, I don't
understand how
validate(self, field_data, all_data) works (how to handle
all_data ?).

I would like to find examples or detailled docs on those topics. If
anyone could point a link ...

Thanks, Alain.



On 1 sep, 14:32, Thomas Guettler <h...@tbz-pariv.de> wrote:
> Hi,
>
> Up to now Model Validation is not possible with django. You need to use
> a ModelForm. The documentation contains examples how to do custom validation.
>
> alain31 schrieb:
>
>
>
> > Hello, I wrote a model to manage small TeX fragments:
>
> > class LaTeX(models.Model):
> >     latex = models.TextField(help_text="Un extrait de source LaTeX")
> >     macros = models.ForeignKey(Macros)
>
> > For now, I override save() to compile the latex string using macros
> > strings with LaTeX compilator, and produce a
> > png image that I store with a name made with self.id (so I need to
> > call super...save() before). But in case of
> > LaTeX compilation errors, I just raise an exception that will not
> > appear in production with DEBUG = False.
>
> > I'd like to treat  LaTeX compilation errors as standard validation
> > errors to
> > appear in error list in forms, admin...
>
> >  I don't know how to do this, I looked at
> > - signals (pre-post save) : what about validation ?
> > - write a TextField  subclass and override validate to do compilation
> > here ? But I need to access another field 'macros'  and model.id  ...
> > - I foundhttp://code.djangoproject.com/ticket/6845with a patch to do
> > model validation (1 year ago) that looks
> > like what I need, but is it stable?
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: model validation errors

2009-09-01 Thread Thomas Guettler

Hi,

Up to now Model Validation is not possible with django. You need to use
a ModelForm. The documentation contains examples how to do custom validation.


alain31 schrieb:
> Hello, I wrote a model to manage small TeX fragments:
> 
> class LaTeX(models.Model):
> latex = models.TextField(help_text="Un extrait de source LaTeX")
> macros = models.ForeignKey(Macros)
> 
> For now, I override save() to compile the latex string using macros
> strings with LaTeX compilator, and produce a
> png image that I store with a name made with self.id (so I need to
> call super...save() before). But in case of
> LaTeX compilation errors, I just raise an exception that will not
> appear in production with DEBUG = False.
> 
> I'd like to treat  LaTeX compilation errors as standard validation
> errors to
> appear in error list in forms, admin...
> 
>  I don't know how to do this, I looked at
> - signals (pre-post save) : what about validation ?
> - write a TextField  subclass and override validate to do compilation
> here ? But I need to access another field 'macros'  and model.id  ...
> - I found http://code.djangoproject.com/ticket/6845 with a patch to do
> model validation (1 year ago) that looks
> like what I need, but is it stable?


-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



model validation errors

2009-08-31 Thread alain31

Hello, I wrote a model to manage small TeX fragments:

class LaTeX(models.Model):
latex = models.TextField(help_text="Un extrait de source LaTeX")
macros = models.ForeignKey(Macros)

For now, I override save() to compile the latex string using macros
strings with LaTeX compilator, and produce a
png image that I store with a name made with self.id (so I need to
call super...save() before). But in case of
LaTeX compilation errors, I just raise an exception that will not
appear in production with DEBUG = False.

I'd like to treat  LaTeX compilation errors as standard validation
errors to
appear in error list in forms, admin...

 I don't know how to do this, I looked at
- signals (pre-post save) : what about validation ?
- write a TextField  subclass and override validate to do compilation
here ? But I need to access another field 'macros'  and model.id  ...
- I found http://code.djangoproject.com/ticket/6845 with a patch to do
model validation (1 year ago) that looks
like what I need, but is it stable?

Any hint ?
--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation

2009-07-19 Thread sjtirtha
I just found the error.
This is the correct code
class AbstractContent(models.Model):
viewed   = models.PositiveIntegerField(max_length=7, blank=True,
null=True)
#rating   =
#ranking  =
created_by   = models.ForeignKey(User,
related_name="%(class)s_created_by")
changed_by= models.ForeignKey(User,
related_name="%(class)s_changed_by")
created_at   = models.DateTimeField(auto_now_add=True)
changed_at   = models.DateTimeField(auto_now=True, blank=True,
null=True)

class Meta:
abstract = True

Thanks for response

On Sun, Jul 19, 2009 at 10:23 PM, sjtirtha  wrote:

> Hi,
>
> I did by mistake copy and paste the coding from my editor.
> But in my coding it is "User". Still I have the same error.
>
> Steve
>
>
> On Sun, Jul 19, 2009 at 12:36 AM, Joshua Russo wrote:
>
>> On Sat, Jul 18, 2009 at 9:03 PM, sjtirtha  wrote:
>>
>>> class AbstractContent(models.Model):
>>> viewed   = models.PositiveIntegerField(max_length=7,
>>> blank=True, null=True)
>>> #rating   =
>>> #ranking  =
>>> created_by   = models.ForeignKey(User)
>>> changedBy= models.ForeignKey(Use, related_name='_changedBy')
>>> created_at   = models.DateTimeField(auto_now_add=True)
>>> changed_at   = models.DateTimeField(auto_now=True, blank=True,
>>> null=True)
>>>
>>> class Meta:
>>> abstract = True
>>>
>>
>> Looks like you misspelled User (as Use) for the ChangedBy field
>>
>> >>
>>
>

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation

2009-07-19 Thread sjtirtha
Hi,

I did by mistake copy and paste the coding from my editor.
But in my coding it is "User". Still I have the same error.

Steve

On Sun, Jul 19, 2009 at 12:36 AM, Joshua Russo wrote:

> On Sat, Jul 18, 2009 at 9:03 PM, sjtirtha  wrote:
>
>> class AbstractContent(models.Model):
>> viewed   = models.PositiveIntegerField(max_length=7,
>> blank=True, null=True)
>> #rating   =
>> #ranking  =
>> created_by   = models.ForeignKey(User)
>> changedBy= models.ForeignKey(Use, related_name='_changedBy')
>> created_at   = models.DateTimeField(auto_now_add=True)
>> changed_at   = models.DateTimeField(auto_now=True, blank=True,
>> null=True)
>>
>> class Meta:
>> abstract = True
>>
>
> Looks like you misspelled User (as Use) for the ChangedBy field
>
> >
>

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation

2009-07-18 Thread Joshua Russo
On Sat, Jul 18, 2009 at 9:03 PM, sjtirtha  wrote:

> class AbstractContent(models.Model):
> viewed   = models.PositiveIntegerField(max_length=7,
> blank=True, null=True)
> #rating   =
> #ranking  =
> created_by   = models.ForeignKey(User)
> changedBy= models.ForeignKey(Use, related_name='_changedBy')
> created_at   = models.DateTimeField(auto_now_add=True)
> changed_at   = models.DateTimeField(auto_now=True, blank=True,
> null=True)
>
> class Meta:
> abstract = True
>

Looks like you misspelled User (as Use) for the ChangedBy field

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Model Validation

2009-07-18 Thread sjtirtha
Hi,

I try to call manage.py syncdb for my models, but I always get error
Lasttime, I solve the problem, by defining related_name for changedBy
attribute.
But now, I got the same problem after I define the model as abstract.

Error: One or more models did not validate:
person.person: Accessor for field 'changedBy' clashes with related field
'User._
changedBy'. Add a related_name argument to the definition for 'changedBy'.
person.person: Reverse query name for field 'changedBy' clashes with related
fie
ld 'User._changedBy'. Add a related_name argument to the definition for
'changed
By'.
film.film: Accessor for field 'changedBy' clashes with related field
'User._chan
gedBy'. Add a related_name argument to the definition for 'changedBy'.
film.film: Reverse query name for field 'changedBy' clashes with related
field '
User._changedBy'. Add a related_name argument to the definition for
'changedBy'.

Here is my model:
class AbstractContent(models.Model):
viewed   = models.PositiveIntegerField(max_length=7, blank=True,
null=True)
#rating   =
#ranking  =
created_by   = models.ForeignKey(User)
changedBy= models.ForeignKey(Use, related_name='_changedBy')
created_at   = models.DateTimeField(auto_now_add=True)
changed_at   = models.DateTimeField(auto_now=True, blank=True,
null=True)

class Meta:
abstract = True

class Person(AbstractContent):
GENDER_TYPE = (
  ('MALE','Male'),
  ('FEMALE','Female')
  )

first_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20, blank=True)
last_name = models.CharField(max_length=20)
gender = models.CharField(max_length=6, choices=GENDER_TYPE)
birth_date = models.DateField(blank=True)
birth_country = models.CharField(max_length=20, blank=True)
birth_city = models.CharField(max_length=20, blank=True)
height = models.PositiveIntegerField(max_length=3, blank=True,
null=True)
weight = models.PositiveIntegerField(max_length=3, blank=True,
null=True)
def __unicode__(self):
return self.last_name

--~--~-~--~~~---~--~~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model validation basics

2008-01-12 Thread zobbo

On Jan 12, 6:36 pm, "Karen Tracey" <[EMAIL PROTECTED]> wrote:

> Did you miss the "This is an experimental feature!" note at the top of:
>
> http://www.djangoproject.com/documentation/models/validation/
>
> ?
>
> Last I recall seeing it mentioned here, model validation is still a work in
> progress.  Meaning I don't believe everything is supposed to work just yet.
>
> Karen

I did miss it! Many thanks!

It's a pain because when you're writing doctests you trigger a
postgres error and then receive "current transaction is aborted"
messages for whatever else you try and do to the database within the
test.

Thanks again

Ian
--~--~-~--~~~---~--~~
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: Model validation basics

2008-01-12 Thread Karen Tracey
On Jan 12, 2008 1:17 PM, Ian J Cottee <[EMAIL PROTECTED]> wrote:

>
> I've actually written a couple of basic apps in Django but today I
> thought I'd play around with doc tests and realised I didn't know as
> much as I thought I did. This is all done with latest trunk.
>
> Let's take a model definition that has just the following:
>
> class PartType(models.Model):
>code = models.CharField(max_length=15)
>description = models.CharField(max_length=50)
>
> We can play around with this in the shell and do this:
>
>  >>> pt = PartType()
>  >>> pt.validate()
> {'code': [u'This field is required.'], 'description': [u'This field is
> required.']}
>
> Which is what we expect. These two fields are required.
>
>  >>> pt.code='ACODE'
>  >>> pt.description='A description'
>  >>> pt.validate()
> {}
>  >>> pt.save()
>
> All good, it validates and saves. Now let's give it something a little
> longer than it can't cope with.
>
>  >>> pt.code='THISISLONGERTHANFIFTEENCHARS'
>  >>> pt.validate()
> {}
>
> Odd - it validates but we know our code field can only be 15 characters.
>
>  >>> pt.save()
> Traceback (most recent call last):
>  File "", line 1, in 
>  File
> "/usr/local/lib/python2.5/site-packages/django/db/models/base.py", line
> 238, in save
>db_values + self._meta.pk.get_db_prep_lookup('exact', pk_val))
>  File
> "/usr/local/lib/python2.5/site-packages/django/db/backends/util.py",
> line 18, in execute
>return self.cursor.execute(sql, params)
> ProgrammingError: value too long for type character varying(15)
>
> BANG!
>
> I'd be expecting for Django to tell me before postgres does, that the
> field does not validate. Am I misunderstanding something?
>

Did you miss the "This is an experimental feature!" note at the top of:

http://www.djangoproject.com/documentation/models/validation/

?

Last I recall seeing it mentioned here, model validation is still a work in
progress.  Meaning I don't believe everything is supposed to work just yet.

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



Model validation basics

2008-01-12 Thread Ian J Cottee

I've actually written a couple of basic apps in Django but today I 
thought I'd play around with doc tests and realised I didn't know as 
much as I thought I did. This is all done with latest trunk.

Let's take a model definition that has just the following:

class PartType(models.Model):
code = models.CharField(max_length=15)
description = models.CharField(max_length=50)

We can play around with this in the shell and do this:

 >>> pt = PartType()
 >>> pt.validate()
{'code': [u'This field is required.'], 'description': [u'This field is 
required.']}

Which is what we expect. These two fields are required.
 
 >>> pt.code='ACODE'
 >>> pt.description='A description'
 >>> pt.validate()
{}
 >>> pt.save()

All good, it validates and saves. Now let's give it something a little 
longer than it can't cope with.

 >>> pt.code='THISISLONGERTHANFIFTEENCHARS'
 >>> pt.validate()
{}

Odd - it validates but we know our code field can only be 15 characters.

 >>> pt.save()
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/usr/local/lib/python2.5/site-packages/django/db/models/base.py", line 
238, in save
db_values + self._meta.pk.get_db_prep_lookup('exact', pk_val))
  File 
"/usr/local/lib/python2.5/site-packages/django/db/backends/util.py", 
line 18, in execute
return self.cursor.execute(sql, params)
ProgrammingError: value too long for type character varying(15)

BANG!

I'd be expecting for Django to tell me before postgres does, that the 
field does not validate. Am I misunderstanding something?

Ian

--~--~-~--~~~---~--~~
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: Model Validation - Best practices

2007-11-15 Thread eriku777

Does anyone know if the Model class validate() method will be ready
any time soon?  I am trying to learn Django but don't want to spend a
lot of time hacking save() work-arounds if new core features will
resolve the issue of business logic validation within models.

-- Eric --

On Oct 24, 12:11 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:

> Right now, there's a validate() method on the Model class, but it is
> incomplete and not recommended for production use.
>
> In the interim, doing things in the save() method is possible, although
> it's not a brilliantly nice design, since save() should never raise
> validation errors and, if it does, you won't get feedback to, say, the
> admin interface or places like that. But it's the workaround you need to
> do at the moment.
>
> Regards,
> Malcolm
>
> --
> Atheism is a non-prophet organization.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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation - Best practices

2007-11-11 Thread [EMAIL PROTECTED]



On Nov 11, 4:51 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Sun, 2007-11-11 at 23:30 +, [EMAIL PROTECTED] wrote:
>
> > > At the moment this is work in progress. There is some development going
> > > on to finish upmodel-awarevalidationand complete some earlier work 
> > > onmodelvalidation. At that time, you'll be able to call
> > > my_model.validate() and have things work similarly to how they do with
> > > newforms.
>
> > are their open bugs or a branch where this work is being done?  I
> > would love to help move this work along or contribute in any way
> > possible to completing model validation.  In my project it is the #1
> > missing feature, requiring quite a few violations of DRY.  I have a
> > large backend set of functionality where I want to use my models and
> > define data validation on the model itself not through the forms.
>
> It's not being done on a branch, since it's very self-contained work.
> Jacob Kaplan-Moss is doing it. He and I and a few other people (Simon
> Willison, Jeremy Dunck, maybe Derek Willis was also there) sat down at
> various points during OSCON back in July and did the design work. Adrian
> poked some hole in some small places during the last sprint (Sep 15).
> Jacob now just needs to find some time to finish it (he's been pretty
> busy with Real Life lately, so let's not flame him).
>
> I realise this is frustrating, but I speak from experience when I say
> that sometimes this stuff can't be easily shared around for simultaneous
> development work. Until the back of the work is broken, multiple people
> would just be tripping over each other and I strongly suspect that would
> be the case here. Anyway, search the django-dev archives for a couple of
> recent threads where this came up and you'll see the latest story.
>
> Regards,
> Malcolm
>
> --
> How many of you believe in telekinesis? Raise my 
> hand...http://www.pointy-stick.com/blog/

Wasn't planning to flame anyone, just looking for a status update as I
had heard some rumors about it being worked on, but couldn't find
anything in trak, and the latest thread I could find on dev was from
2006.  I searched a little harder just now and found the short thread
from last month.  Thanks for the info.  I agree and understand needing
to keep things in a very limited sandbox at the beginning.  As soon as
anything is ready to test/break in this regard I'll be here.

-Tom


--~--~-~--~~~---~--~~
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: Model Validation - Best practices

2007-11-11 Thread Malcolm Tredinnick


On Sun, 2007-11-11 at 23:30 +, [EMAIL PROTECTED] wrote:
> 
> >
> > At the moment this is work in progress. There is some development going
> > on to finish upmodel-awarevalidationand complete some earlier work 
> > onmodelvalidation. At that time, you'll be able to call
> > my_model.validate() and have things work similarly to how they do with
> > newforms.
> 
> are their open bugs or a branch where this work is being done?  I
> would love to help move this work along or contribute in any way
> possible to completing model validation.  In my project it is the #1
> missing feature, requiring quite a few violations of DRY.  I have a
> large backend set of functionality where I want to use my models and
> define data validation on the model itself not through the forms.

It's not being done on a branch, since it's very self-contained work.
Jacob Kaplan-Moss is doing it. He and I and a few other people (Simon
Willison, Jeremy Dunck, maybe Derek Willis was also there) sat down at
various points during OSCON back in July and did the design work. Adrian
poked some hole in some small places during the last sprint (Sep 15).
Jacob now just needs to find some time to finish it (he's been pretty
busy with Real Life lately, so let's not flame him).

I realise this is frustrating, but I speak from experience when I say
that sometimes this stuff can't be easily shared around for simultaneous
development work. Until the back of the work is broken, multiple people
would just be tripping over each other and I strongly suspect that would
be the case here. Anyway, search the django-dev archives for a couple of
recent threads where this came up and you'll see the latest story.

Regards,
Malcolm

-- 
How many of you believe in telekinesis? Raise my hand... 
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation - Best practices

2007-11-11 Thread [EMAIL PROTECTED]


>
> At the moment this is work in progress. There is some development going
> on to finish upmodel-awarevalidationand complete some earlier work 
> onmodelvalidation. At that time, you'll be able to call
> my_model.validate() and have things work similarly to how they do with
> newforms.

are their open bugs or a branch where this work is being done?  I
would love to help move this work along or contribute in any way
possible to completing model validation.  In my project it is the #1
missing feature, requiring quite a few violations of DRY.  I have a
large backend set of functionality where I want to use my models and
define data validation on the model itself not through the forms.


--~--~-~--~~~---~--~~
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: Model Validation - Best practices

2007-10-31 Thread Malcolm Tredinnick

On Wed, 2007-10-31 at 18:05 -0700, Ken wrote:
> 
> 
> On Oct 31, 6:07 pm, Ken <[EMAIL PROTECTED]> wrote:
> 
> >
> > I have a similar thing I wish to accomplish.  It's not quite model
> > validation, rather model completion.  The form provides a field that
> > fills one model field but has to be munged to fill a second model
> > field.  I thought the appropriate place is in the model's save()
> > function prior to calling the base class save() function.  Can you
> > show an example of how to access the model's fields?  I tried using
> > self._meta.fields, but I'm apparently indexing it wrong.  models/
> > __init__.py is beyond me. :(
> >
> > I have also wondered why Model.save() returns nothing.  How do you
> > detect if the SQL insert or update fails?
> 
> Duh!  :\ I was making things too complicated.   I was able to redefine
> save() to do what I want.  But, I would still like to hear why save()
> does not confirm if the SQL insert or update succeed or failed?  Or,
> perhaps I've overlooked something in the docs.

It raises an exception. Normal Python error handling process.

Regards,
Malcolm

-- 
If it walks out of your refrigerator, LET IT GO!! 
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Validation - Best practices

2007-10-31 Thread Ken



On Oct 31, 6:07 pm, Ken <[EMAIL PROTECTED]> wrote:

>
> I have a similar thing I wish to accomplish.  It's not quite model
> validation, rather model completion.  The form provides a field that
> fills one model field but has to be munged to fill a second model
> field.  I thought the appropriate place is in the model's save()
> function prior to calling the base class save() function.  Can you
> show an example of how to access the model's fields?  I tried using
> self._meta.fields, but I'm apparently indexing it wrong.  models/
> __init__.py is beyond me. :(
>
> I have also wondered why Model.save() returns nothing.  How do you
> detect if the SQL insert or update fails?

Duh!  :\ I was making things too complicated.   I was able to redefine
save() to do what I want.  But, I would still like to hear why save()
does not confirm if the SQL insert or update succeed or failed?  Or,
perhaps I've overlooked something in the docs.

Thanks! Ken


--~--~-~--~~~---~--~~
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: Model Validation - Best practices

2007-10-31 Thread Ken



On Oct 24, 12:11 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:

> In the interim, doing things in the save() method is possible, although
> it's not a brilliantly nice design, since save() should never 
> raisevalidationerrors and, if it does, you won't get feedback to, say, the
> admin interface or places like that. But it's the workaround you need to
> do at the moment.
>
> Regards,
> Malcolm
>
> --

I have a similar thing I wish to accomplish.  It's not quite model
validation, rather model completion.  The form provides a field that
fills one model field but has to be munged to fill a second model
field.  I thought the appropriate place is in the model's save()
function prior to calling the base class save() function.  Can you
show an example of how to access the model's fields?  I tried using
self._meta.fields, but I'm apparently indexing it wrong.  models/
__init__.py is beyond me. :(

I have also wondered why Model.save() returns nothing.  How do you
detect if the SQL insert or update fails?


--~--~-~--~~~---~--~~
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: Model Validation - Best practices

2007-10-23 Thread Malcolm Tredinnick

On Wed, 2007-10-24 at 04:40 +, Camo wrote:
> Hi Guys,
> 
> I just been working my way through Django, top framework by the way.
> 
> Anyways I just wondering if any one can shed some light model
> validation,
> 
> It seems the only validations are either through the newforms or
> simple validation through the fields.  But there doesn't seem to be
> any bussiness rule validation functions for models.  My concern is
> that validations should really be kept in the model and not in
> forms.
> 
> So I was just wondering how people go about validating models.

At the moment this is work in progress. There is some development going
on to finish up model-aware validation and complete some earlier work on
model validation. At that time, you'll be able to call
my_model.validate() and have things work similarly to how they do with
newforms.

Right now, there's a validate() method on the Model class, but it is
incomplete and not recommended for production use.

In the interim, doing things in the save() method is possible, although
it's not a brilliantly nice design, since save() should never raise
validation errors and, if it does, you won't get feedback to, say, the
admin interface or places like that. But it's the workaround you need to
do at the moment.

Regards,
Malcolm

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



Re: Model Validation - Best practices

2007-10-23 Thread Kenneth Gonsalves


On 24-Oct-07, at 10:10 AM, Camo wrote:

> So I was just wondering how people go about validating models.

overide the save() method and add your own business rules in the model

-- 

regards
kg
http://lawgon.livejournal.com
http://nrcfosshelpline.in/web/



--~--~-~--~~~---~--~~
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: model validation

2007-03-11 Thread Greg Donald

On 3/10/07, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
> Validation happens on the strings submitted from a form, *before* they
> are converted to Python objects (since there's no guarantee we can
> convert them without error). We do not have model-aware validation at
> the moment, but it is coming. Note that what we do have is still good
> for the majority of cases, because you have access to all the submitted
> fields. What you don't have access to is the instance of the model that
> will be affected in the case where you are updating an existing
> instance. That is the feature we will add eventually.

Having to validate the data at every possible form location doesn't
seem very DRY to me.  I should be able to put a single set of
validation rules directly in the model so any form I write in the
future has to validate against them.

> See http://www.djangoproject.com/documentation/forms/#validators for a
> description of how validators work. Although that page talks about
> validators in the context of form submissions, they are the same
> validators that you can specify on models.*Field classes as well.

The newforms page doesn't have much about validation on it:

http://www.djangoproject.com/documentation/newforms/

Do the same validation techniques apply from the old forms system to
the newforms?

> Suffice it to say that, in your case, when you submit a string as part
> of a form submission to go into your field, Django will ensure that it
> is non-empty, because you have blank=False.

That doesn't seem to be the case for this particular field I have:

class List(models.Model):
name = models.CharField(maxlength=32, blank=False, null=False)

> python manage.py shell
In [1]: import datetime
In [2]: from mysite.groceries.models import List
In [3]: l = List(name='', created_at=datetime.datetime.now())
In [4]: l.save()
In [5]: l.name
Out[5]: ''

What am I missing here?


-- 
Greg Donald
http://destiney.com/

--~--~-~--~~~---~--~~
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: model validation

2007-03-10 Thread Malcolm Tredinnick

On Sat, 2007-03-10 at 16:59 -0600, Greg Donald wrote:
> On 3/10/07, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
> > I assume you mean via some way other than a form or the admin interface,
> 
> Model validation doesn't occur in the model itself?

Validation happens on the strings submitted from a form, *before* they
are converted to Python objects (since there's no guarantee we can
convert them without error). We do not have model-aware validation at
the moment, but it is coming. Note that what we do have is still good
for the majority of cases, because you have access to all the submitted
fields. What you don't have access to is the instance of the model that
will be affected in the case where you are updating an existing
instance. That is the feature we will add eventually.

> 
> > because in those two cases, field validation should catch it.
> 
> What is "field validation" exactly?

See http://www.djangoproject.com/documentation/forms/#validators for a
description of how validators work. Although that page talks about
validators in the context of form submissions, they are the same
validators that you can specify on models.*Field classes as well.

Suffice it to say that, in your case, when you submit a string as part
of a form submission to go into your field, Django will ensure that it
is non-empty, because you have blank=False.

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: model validation

2007-03-10 Thread Greg Donald

On 3/10/07, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
> I assume you mean via some way other than a form or the admin interface,

Model validation doesn't occur in the model itself?

> because in those two cases, field validation should catch it.

What is "field validation" exactly?


Thanks,


-- 
Greg Donald
http://destiney.com/

--~--~-~--~~~---~--~~
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: model validation

2007-03-10 Thread Malcolm Tredinnick

On Sat, 2007-03-10 at 11:53 -0600, Greg Donald wrote:
> Why doesn't this prevent me from entering an empty string into the database?
> 
> name = models.CharField(maxlength=32, blank=False, null=False)

I assume you mean via some way other than a form or the admin interface,
because in those two cases, field validation should catch it. At the
database level, the only thing that applies is null=False, which means
the column must contain a non-NULL value. An empty string is non-NULL,
so it satisfies the column constraint.

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
-~--~~~~--~~--~--~---



model validation

2007-03-10 Thread Greg Donald

Why doesn't this prevent me from entering an empty string into the database?

name = models.CharField(maxlength=32, blank=False, null=False)


Thanks,


-- 
Greg Donald
http://destiney.com/

--~--~-~--~~~---~--~~
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: Model validation errors ...

2006-11-09 Thread ZebZiggle

Ah ... of course.

Thanks James!

Keep up the great work!

-Sandy


--~--~-~--~~~---~--~~
 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: Re: Model validation errors ...

2006-11-09 Thread James Bennett

On 11/9/06, ZebZiggle <[EMAIL PROTECTED]> wrote:
> My question is ... why is Accusation any different tan Message,
> ReadMessage or any of the other tables that relate back to Player?

The problem was that Accusation has *two* fields which relate to
Player. When 'related_name' isn't set, that means that you end up with
two things trying to have an attribute of the same name. Setting
'related_name' clears that up.

-- 
"May the forces of evil become confused on the way to your house."
  -- George Carlin

--~--~-~--~~~---~--~~
 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: Model validation errors ...

2006-11-09 Thread ZebZiggle

More on this:

If I change Accusation to:

class Accusation(models.Model):
game = models.ForeignKey(Game)
player = models.ForeignKey(Player, related_name='related_player')
accusedPlayer = models.ForeignKey(Player,
related_name='related_accusedPlayer')
isCommitted = models.BooleanField()
motive = models.CharField(maxlength = 1024)
method = models.CharField(maxlength = 1024)

then it validates and installs (and the session tables, etc get
installed too)

My question is ... why is Accusation any different tan Message,
ReadMessage or any of the other tables that relate back to Player?

Cheers,
Sandy


--~--~-~--~~~---~--~~
 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
-~--~~~~--~~--~--~---



Model validation errors ...

2006-11-09 Thread ZebZiggle

Hi there,

I've decided to drop my old 0.91 database and rebuild, rather than try
to upgrade it. So, in my dev environment I've dropped the database, but
now when I try to 'syncdb' I get the following validation error.

Error: Couldn't install apps, because there were errors in one or more
models:
mydarksecret.accusation: Accessor for field 'player' clashes with
related field 'Player.accusation_set'. Add a related_name argument
 to the definition for 'player'.
mydarksecret.accusation: Accessor for field 'accusedPlayer' clashes
with related field 'Player.accusation_set'. Add a related_name a
rgument to the definition for 'accusedPlayer'.

This strikes me as wierd since there are many other tables that have
similar relationships, but it only seems to complain about
'accusation'. See some sample tables below.

Also, I can't seem to get the "django infrastructure" created. syncdb
doesn't want to create them ... is there another manage.py command I
should be using to get things like the session table created?

Any ideas?

Thx,
Sandy

 (partial) MODEL 

class Player(models.Model):
user = models.ForeignKey(User, null = True)
game = models.ForeignKey(Game)
character = models.ForeignKey(GameElement)
joinedOn = models.DateTimeField(auto_now_add = True)

class Message(models.Model):
gameElement = models.ForeignKey(GameElement)
player = models.ForeignKey(Player)
emotion = models.IntegerField()
dateTime = models.DateTimeField(auto_now_add = True)
subject = models.CharField(maxlength = 100)
text = models.CharField(maxlength = 1024)

class ReadMessage(models.Model):
gameElement = models.ForeignKey(GameElement)
player = models.ForeignKey(Player)
dateTime = models.DateTimeField(auto_now_add = True)

class Accusation(models.Model):
game = models.ForeignKey(Game)
player = models.ForeignKey(Player)
accusedPlayer = models.ForeignKey(Player)
isCommitted = models.BooleanField()


--~--~-~--~~~---~--~~
 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: Errors in model validation

2006-09-25 Thread [EMAIL PROTECTED]

You can disregard this thread.

This was a problem of circular references that i fixed over the weekend
(before the message was moderated) by passing the ForeignKey the string
of the Model name instead of the object (as per Django documentation!)

Also please disregard other messages like these (same content. similar
subject) as i had a problem with the Google Groups spamfilter that was
blocking me and attempted to send the same message from other email
addresses.

I apologize for the mess.

Lorenzo


--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Errors in model validation

2006-09-25 Thread Lorenzo Bolognini

Hi all,

I have a problem with the app below (SVN repo with read access) and i
tried everything to fix it. Probably u guys can help. It seems to me
some problem with namespace import, particularly the *order* in which
the names are imported.

The code in the repo is already broken but u can "fix it" by commenting
the parts that import or use the Department model (though that's not
what i want).

And this is just the minimum to repro the problem... it actually gets
worse when i try to add more models (probably i'm just repeating the
same mistake).

What looks especially funny to me is that "liger.people: cannot import
name Person" since the Person model is defined inside liger.people.

Source code here:
http://lorenzo.textdriven.com/svn/svn.djangoliger

C:\www\liger>python manage.py validate
liger.courses: cannot import name Major
liger.people: cannot import name Person
liger.time: cannot import name Person
liger.departments: cannot import name Department
4 errors found.

Thanks,
Lorenzo


--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Re: model validation and foreign keys

2006-06-28 Thread Russell Keith-Magee
On 6/29/06, Michael Radziej <[EMAIL PROTECTED]> wrote:
Hey russellm,thanks a lot for the extended model validation--it rocks! Youprobably saved me endless hours of debugging twisted things!No problems Michael - glad I could help you out.
Yours,Russ Magee %-)

--~--~-~--~~~---~--~~
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  -~--~~~~--~~--~--~---


model validation and foreign keys

2006-06-28 Thread Michael Radziej

Hey russellm,

thanks a lot for the extended model validation--it rocks! You
probably saved me endless hours of debugging twisted things!

8-)

Michael

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



  1   2   >