Re: ModelForm validation of foreign keys - extra database queries and performance bottleneck

2017-07-25 Thread johan de taeye

I've already tried the select_related in my queryset. No change at all.  

>>Also keep in mind that Django (or any other framework) has no idea 
whether or not fields have "changed" in a form submission without pulling 
the original set of values to compare against, so expect the object to be 
pulled at least once on every request. 

The first query already retrieves the primary key of the original object, 
or the complete object if selected_related is added.  Using select_related 
can keep things to a single query, and we should be good - it's the number 
of db queries that is executed which is drastically reducing the 
performance.


I believe I'll need a custom version of the ModelChoiceField class.


Op dinsdag 25 juli 2017 10:48:41 UTC+2 schreef James Schneider:
>
>
>
> On Jul 24, 2017 4:09 AM, "johan de taeye"  > wrote:
>
>
> I have a model that has a foreign key relation to a number of other 
> objects.
> When saving an instance of this model from the admin (or a ModelForm), I 
> see plenty of extra and redundant database calls. 
> For a single record it wouldn't make much of a difference, but when using 
> the same ModeForm to do some batch upload these become the bottleneck in 
> the process.
>
> Has anyone bumped into the same performance bottleneck? 
> Has anyone developed some solution for this?
>
> By logging all database queries and some digging in the code, here's my 
> analysis of what is happening:
>
>1. Open the admin editing screen for a single record.  
>I leave all fields to the original value, except for a field (not one 
>of the foreign key fields)
>2. When saving the record, the first query reads the existing record:
>  select field1, field2, field3,  from mytable;
>3. During the form/model validation, I get an extra database query for 
>each of the foreign key fields.
>It is generated from the to_python method 
>of django.forms.models.ModelChoiceField:
>  select field_a, field_b, field_c, field, ... from related_table 
>where pk = 'id_from_first_query';
>4. During the form/model validation, I get another database query for 
>each of the foreign key fields.
>It verifies that the values actually exists in the database:
> select (1) from related_table where pk = 'value from form'; 
>
> The queries in step 3 and 4 are redundant if the field hasn't changed. The 
> first query gives enough data to allow us to verify that the new form value 
> and the foreign key field on the existing instance are equal. I am using 
> django 1.11.
>
> The same queries, except 2, are executed when I create a new record. The 
> queries in step 4 are redundant then - we just retrieved the values from 
> the database.
>
> Looking forward to any insights and hints...
>
>
> You should look at modifying the query set that your view is using to pull 
> the main object to include select_related() calls. I don't know if you're 
> using function -based views or class-based views,  so I can't comment 
> further on implementation. 
>
> https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related
>
> The extra calls are likely occurring when the related fields are being 
> accessed during validation, etc. 
>
> Also keep in mind that Django (or any other framework) has no idea whether 
> or not fields have "changed" in a form submission without pulling the 
> original set of values to compare against, so expect the object to be 
> pulled at least once on every request. 
>
> -James 
>

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5cc0b017-2759-4026-ab6e-41f5a6cb3dd3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelForm validation of foreign keys - extra database queries and performance bottleneck

2017-07-25 Thread James Schneider
On Jul 24, 2017 4:09 AM, "johan de taeye"  wrote:


I have a model that has a foreign key relation to a number of other objects.
When saving an instance of this model from the admin (or a ModelForm), I
see plenty of extra and redundant database calls.
For a single record it wouldn't make much of a difference, but when using
the same ModeForm to do some batch upload these become the bottleneck in
the process.

Has anyone bumped into the same performance bottleneck?
Has anyone developed some solution for this?

By logging all database queries and some digging in the code, here's my
analysis of what is happening:

   1. Open the admin editing screen for a single record.
   I leave all fields to the original value, except for a field (not one of
   the foreign key fields)
   2. When saving the record, the first query reads the existing record:
 select field1, field2, field3,  from mytable;
   3. During the form/model validation, I get an extra database query for
   each of the foreign key fields.
   It is generated from the to_python method of django.forms.models.
   ModelChoiceField:
 select field_a, field_b, field_c, field, ... from related_table
   where pk = 'id_from_first_query';
   4. During the form/model validation, I get another database query for
   each of the foreign key fields.
   It verifies that the values actually exists in the database:
select (1) from related_table where pk = 'value from form';

The queries in step 3 and 4 are redundant if the field hasn't changed. The
first query gives enough data to allow us to verify that the new form value
and the foreign key field on the existing instance are equal. I am using
django 1.11.

The same queries, except 2, are executed when I create a new record. The
queries in step 4 are redundant then - we just retrieved the values from
the database.

Looking forward to any insights and hints...


You should look at modifying the query set that your view is using to pull
the main object to include select_related() calls. I don't know if you're
using function -based views or class-based views,  so I can't comment
further on implementation.

https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related

The extra calls are likely occurring when the related fields are being
accessed during validation, etc.

Also keep in mind that Django (or any other framework) has no idea whether
or not fields have "changed" in a form submission without pulling the
original set of values to compare against, so expect the object to be
pulled at least once on every request.

-James

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUjjFKSCa-Sdi6yBd-sdLoaPCFmvs-XWCDKYsorKskUAQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelForm Validation Error

2012-04-18 Thread Tom Evans
On Tue, Apr 17, 2012 at 8:07 PM, coded kid  wrote:
> I want to make sure users fill all the fields before they are
> redirected to the next page. And if they don’t fill the fields it
> should raise an error telling them to fill the fields before they
> proceed. So to do that, I wrote the codes below. But the problem I’m
> facing is that when I didn’t fill the fields, it took me to the next
> page, instead of it to return me to the same page, and it didn’t raise
> any error.
>
> How can I make it validate those fields before taking users to the
> next page?
>
> Model:
>
> from django.core.exceptions import ValidationError
>
> class Memb(models.Model):
>    slug=models.CharField(max_length=100)
>    member=models.CharField(max_length=100)
>
>    def __unicode__(self):
>        return self.member, self.slug

Slight nit. The __unicode__ method must always return unicode. Strange
things will happen if it doesn't return unicode, but instead returns a
2-tuple.

Cheers

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



Re: ModelForm Validation Error

2012-04-17 Thread Mario Gudelj
Indent that redirect one more time so that it's wothin the if loop and
you're redirected to good only when the form is valid

On 18/04/2012 5:07 AM, "coded kid"  wrote:

> I want to make sure users fill all the fields before they are
> redirected to the next page. And if they don’t fill the fields it
> should raise an error telling them to fill the fields before they
> proceed. So to do that, I wrote the codes below. But the problem I’m
> facing is that when I didn’t fill the fields, it took me to the next
> page, instead of it to return me to the same page, and it didn’t raise
> any error.
>
> How can I make it validate those fields before taking users to the
> next page?
>
> Model:
>
> from django.core.exceptions import ValidationError
>
> class Memb(models.Model):
>slug=models.CharField(max_length=100)
>member=models.CharField(max_length=100)
>
>def __unicode__(self):
>return self.member, self.slug
>
>def clean_slug(self):
>data=self.cleaned_data['slug']
>if "Testy" not in data:
>raise ValidationError("Enter the correct name for this
> field")
>
> class MembForm(ModelForm):
>class Meta:
>model=Memb
>fields=('slug','member')
>
> Views:
>
> def my_memb(request):
>if request.method=="POST":
>form=MembForm(request.POST)
>if form.is_valid():
>data=form.cleaned_data
>form.save()
>return HttpResponseRedirect('/good/')
>else:
>form=MembForm()
>return render_to_response('member.html',{'MembForm':MembForm},
> context_instance=RequestContext(request))
>
> Template:
>
> {% block content %}
> 
>  {{MembForm.as_p}}
> 
> 
> {% endblock %}
>
> --
> 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: ModelForm validation in 1.2.3

2010-12-30 Thread Burhan
The question is how do I get the modelform to only check for form
validity, and not model validity (like it did before). I don't see
what your link has to do with that.

On Dec 30, 7:32 pm, Ferran  wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA256
>
> On 30/12/10 17:25, Burhan wrote:
>
> >  In 1.2.3, this logic always fails because "is_clean()" fails if an
> > existing customer enter's their email address. How can I do the same
> > using django 1.2.3?
>
> http://docs.python.org/tutorial/errors.html
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.11 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org/
>
> iQIcBAEBCAAGBQJNHLQCAAoJEAWOKfEESaOw/KkQAJpykIq4NuWT2pFlzT/jg2Ck
> ZLPnKTABp7JmvDdNflreKhKDKmhMSmYTu9/ThF8RtGgtstq5oUtdhZmKoRnpnuWe
> GHFPPidSBD9NOs1MFgj1+8kkvcTFLE6kPRupfNN9nJKFm4gZ8dpV602WOJWlK1dJ
> 4ViK5fFU4AwOoGpqZrmMG6J8bzOKs6U6rNJP4YLSvMyRyEOj5qVwAo9x4V+NpgHg
> 5NiWADvWnwISc7QdB84ViYsmF3ocIIZnzAgLbRa7kej/8NQ/ikndc7gAvjpseJi7
> R3GiaW816m/PElkXlbiszKxjJQSYP9uDfzURJ9oJyU5LNa1cNkr1RrWAtlh/j5RI
> mCwyq7I7MbFodsJe7ZGpUzspZfyk9lxSYAfaVZcE9v9fVJc1y6JbW0KyMl3MJyZG
> K0x+PA+X03gEDnr9fso3cijBc1gz3sVGyj3C5rOgaCnlasRQzbjcjOaIx8GpUTgU
> 4OgP5k/Agz6eYr08JES1cvOeug7TYGY4x84MRwe++RgaOhf/1W7v4Hrvm22hBGcA
> ivBr0xt0rdzCQKeX2JriDMcqWE99KTEEqqWX4bA1l47UiaWg16wvyoxgexQT7Y0O
> larKwMr/5G9+2fQOoYzHL9EcDmzzWJHNjrIZmjrIMv+6fQ5b30aTIh+qI8yvg2vw
> roI7MOFS6TYefl0QhP8R
> =jP4n
> -END PGP SIGNATURE-

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

2010-12-30 Thread Axel Bock
Ah :) . I should have thought of that ... pretty stupid of me :)

Thanks for the clarification, I'll try that, makes perfect sense!


/Axel.



2010/12/30 derek 

> Alex
>
> And I seem to have been equally unclear :}
>
> I agree that cleaned_data is only available after is_valid() - the
> point being that your form *will* be valid if you have set the value
> for that field in a hidden input.  I do not see that this can be a
> "security risk" - the default that you are setting beforehand is a
> dummy (meaningless) value which, in any case, you are going to be
> overriding.  How is this done?  Consider this example from the Django
> Book (http://www.djangobook.com/en/1.0/chapter07/):
>
> def contact(request):
>if request.method == 'POST':
>form = ContactForm(request.POST)
>if form.is_valid():
>topic = form.clean_data['topic']
>
> Now if you wanted to overide the topic, you could instead have:
>topic = 'my custom text'
>
>
> Hope this is clearer!
>
> Derek
>
> On Dec 29, 4:07 pm, Axel Bock  wrote:
> > hi derek,
> >
> > thanks for your hints - was I really that unclear? hm.
> >
> > anyway, could you please give an example about how to "override/check the
> > value for that field after the form POST"? I don't seem to be able to do
> > that, and believe me, I have read the docs.
> >
> > I think cleaned_data is only available after is_valid() was called, but
> > is_valid() throws an exception because the required field is missing -
> and I
> > can't set it.
> >
> > The hidden field thing is the last thing I wanted to try. bad style, you
> > know :) , cause security risk.
> >
> > thanks!
> > Axel.
> >
> > 2010/12/29 derek 
> >
> >
> >
> >
> >
> >
> >
> > > Axel
> >
> > > Not sure I have followed all your requirements, but perhaps you can
> > > try:
> > > * set a default value for the required field
> > > * mask the required field on the form being shown to the user (make it
> > > hidden)
> > > * override/check the value for that field after the form POST and data
> > > "clean" (see:
> > >http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#proce.
> ..
> > > )
> >
> > > HTH
> > > Derek
> >
> > > On Dec 28, 10:21 pm, Axel Bock  wrote:
> > > > Hi all,
> >
> > > > I have this little problem. In my little webapp I have a data model
> which
> > > > defines several required fields. Depending on WHO is logged on, some
> of
> > > > these fields should not be changed by the user and be pre-filled (or
> > > better:
> > > > post-filled) by the application.
> >
> > > > Currently I delete the fields out of the formset like this:
> > > > # prevent entering missions for all other bases
> > > > del missionform.fields['base']
> >
> > > > so the field gets not rendered in the view. Which works nicely.
> >
> > > > Unfortunately base is required, so the validation fails. Now how can
> I
> > > > insert the missing values into the POST data? I tried this:
> > > > if request.user.userflag.is_student:
> > > > logging.error("studen")
> > > > inst=FlownMission(
> > > > student=request.user,
> > > > base=request.user.studentinfo.current_base
> > > > )
> > > > flownmission = FlownMissionForm(request.POST, instance=inst)
> >
> > > > which does not work at all :( . The validation fails all the time ...
> . I
> > > > just need to inject 2 required values somewhere in the POST data, but
> I
> > > have
> > > > no clue how.
> >
> > > > Any help would be greatly appreciated, and I am a total django "newb"
> ...
> > > :)
> >
> > > > Thanks & greetings,
> > > > Axel.
> >
> > > --
> > > 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.
>
>

-- 
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: ModelForm validation in 1.2.3

2010-12-30 Thread Ferran
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA256

On 30/12/10 17:25, Burhan wrote:
>  In 1.2.3, this logic always fails because "is_clean()" fails if an
> existing customer enter's their email address. How can I do the same
> using django 1.2.3?

http://docs.python.org/tutorial/errors.html
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQIcBAEBCAAGBQJNHLQCAAoJEAWOKfEESaOw/KkQAJpykIq4NuWT2pFlzT/jg2Ck
ZLPnKTABp7JmvDdNflreKhKDKmhMSmYTu9/ThF8RtGgtstq5oUtdhZmKoRnpnuWe
GHFPPidSBD9NOs1MFgj1+8kkvcTFLE6kPRupfNN9nJKFm4gZ8dpV602WOJWlK1dJ
4ViK5fFU4AwOoGpqZrmMG6J8bzOKs6U6rNJP4YLSvMyRyEOj5qVwAo9x4V+NpgHg
5NiWADvWnwISc7QdB84ViYsmF3ocIIZnzAgLbRa7kej/8NQ/ikndc7gAvjpseJi7
R3GiaW816m/PElkXlbiszKxjJQSYP9uDfzURJ9oJyU5LNa1cNkr1RrWAtlh/j5RI
mCwyq7I7MbFodsJe7ZGpUzspZfyk9lxSYAfaVZcE9v9fVJc1y6JbW0KyMl3MJyZG
K0x+PA+X03gEDnr9fso3cijBc1gz3sVGyj3C5rOgaCnlasRQzbjcjOaIx8GpUTgU
4OgP5k/Agz6eYr08JES1cvOeug7TYGY4x84MRwe++RgaOhf/1W7v4Hrvm22hBGcA
ivBr0xt0rdzCQKeX2JriDMcqWE99KTEEqqWX4bA1l47UiaWg16wvyoxgexQT7Y0O
larKwMr/5G9+2fQOoYzHL9EcDmzzWJHNjrIZmjrIMv+6fQ5b30aTIh+qI8yvg2vw
roI7MOFS6TYefl0QhP8R
=jP4n
-END PGP SIGNATURE-

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

2010-12-30 Thread derek
Alex

And I seem to have been equally unclear :}

I agree that cleaned_data is only available after is_valid() - the
point being that your form *will* be valid if you have set the value
for that field in a hidden input.  I do not see that this can be a
"security risk" - the default that you are setting beforehand is a
dummy (meaningless) value which, in any case, you are going to be
overriding.  How is this done?  Consider this example from the Django
Book (http://www.djangobook.com/en/1.0/chapter07/):

def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
topic = form.clean_data['topic']

Now if you wanted to overide the topic, you could instead have:
topic = 'my custom text'


Hope this is clearer!

Derek

On Dec 29, 4:07 pm, Axel Bock  wrote:
> hi derek,
>
> thanks for your hints - was I really that unclear? hm.
>
> anyway, could you please give an example about how to "override/check the
> value for that field after the form POST"? I don't seem to be able to do
> that, and believe me, I have read the docs.
>
> I think cleaned_data is only available after is_valid() was called, but
> is_valid() throws an exception because the required field is missing - and I
> can't set it.
>
> The hidden field thing is the last thing I wanted to try. bad style, you
> know :) , cause security risk.
>
> thanks!
> Axel.
>
> 2010/12/29 derek 
>
>
>
>
>
>
>
> > Axel
>
> > Not sure I have followed all your requirements, but perhaps you can
> > try:
> > * set a default value for the required field
> > * mask the required field on the form being shown to the user (make it
> > hidden)
> > * override/check the value for that field after the form POST and data
> > "clean" (see:
> >http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#proce...
> > )
>
> > HTH
> > Derek
>
> > On Dec 28, 10:21 pm, Axel Bock  wrote:
> > > Hi all,
>
> > > I have this little problem. In my little webapp I have a data model which
> > > defines several required fields. Depending on WHO is logged on, some of
> > > these fields should not be changed by the user and be pre-filled (or
> > better:
> > > post-filled) by the application.
>
> > > Currently I delete the fields out of the formset like this:
> > >             # prevent entering missions for all other bases
> > >             del missionform.fields['base']
>
> > > so the field gets not rendered in the view. Which works nicely.
>
> > > Unfortunately base is required, so the validation fails. Now how can I
> > > insert the missing values into the POST data? I tried this:
> > >         if request.user.userflag.is_student:
> > >             logging.error("studen")
> > >             inst=FlownMission(
> > >                 student=request.user,
> > >                 base=request.user.studentinfo.current_base
> > >             )
> > >         flownmission = FlownMissionForm(request.POST, instance=inst)
>
> > > which does not work at all :( . The validation fails all the time ... . I
> > > just need to inject 2 required values somewhere in the POST data, but I
> > have
> > > no clue how.
>
> > > Any help would be greatly appreciated, and I am a total django "newb" ...
> > :)
>
> > > Thanks & greetings,
> > > Axel.
>
> > --
> > 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 > groups.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: ModelForm validation

2010-12-29 Thread Ted
Easiest solution I can see is to create two form classes: StudentForm
and NonStudentForm.  On student form you can then edit form.instance
or form.cleaned_data depending on what your needs are to add the
additional fields before the object is created/updated.

Another approach would be to try setting the fields to "blank = True"
in your model declaration.  I believe this is the exact case for both
a blank=True and a null=True model options.  Blank is for form
validation, Null is for database.

Not a full solution, but perhaps gets you part of the way there.

Ted

On Dec 28, 12:21 pm, Axel Bock  wrote:
> Hi all,
>
> I have this little problem. In my little webapp I have a data model which
> defines several required fields. Depending on WHO is logged on, some of
> these fields should not be changed by the user and be pre-filled (or better:
> post-filled) by the application.
>
> Currently I delete the fields out of the formset like this:
>             # prevent entering missions for all other bases
>             del missionform.fields['base']
>
> so the field gets not rendered in the view. Which works nicely.
>
> Unfortunately base is required, so the validation fails. Now how can I
> insert the missing values into the POST data? I tried this:
>         if request.user.userflag.is_student:
>             logging.error("studen")
>             inst=FlownMission(
>                 student=request.user,
>                 base=request.user.studentinfo.current_base
>             )
>         flownmission = FlownMissionForm(request.POST, instance=inst)
>
> which does not work at all :( . The validation fails all the time ... . I
> just need to inject 2 required values somewhere in the POST data, but I have
> no clue how.
>
> Any help would be greatly appreciated, and I am a total django "newb" ... :)
>
> Thanks & greetings,
> Axel.

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

2010-12-29 Thread Axel Bock
hi derek,

thanks for your hints - was I really that unclear? hm.

anyway, could you please give an example about how to "override/check the
value for that field after the form POST"? I don't seem to be able to do
that, and believe me, I have read the docs.

I think cleaned_data is only available after is_valid() was called, but
is_valid() throws an exception because the required field is missing - and I
can't set it.

The hidden field thing is the last thing I wanted to try. bad style, you
know :) , cause security risk.


thanks!
Axel.



2010/12/29 derek 

> Axel
>
> Not sure I have followed all your requirements, but perhaps you can
> try:
> * set a default value for the required field
> * mask the required field on the form being shown to the user (make it
> hidden)
> * override/check the value for that field after the form POST and data
> "clean" (see:
> http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#processing-the-data-from-a-form
> )
>
> HTH
> Derek
>
> On Dec 28, 10:21 pm, Axel Bock  wrote:
> > Hi all,
> >
> > I have this little problem. In my little webapp I have a data model which
> > defines several required fields. Depending on WHO is logged on, some of
> > these fields should not be changed by the user and be pre-filled (or
> better:
> > post-filled) by the application.
> >
> > Currently I delete the fields out of the formset like this:
> > # prevent entering missions for all other bases
> > del missionform.fields['base']
> >
> > so the field gets not rendered in the view. Which works nicely.
> >
> > Unfortunately base is required, so the validation fails. Now how can I
> > insert the missing values into the POST data? I tried this:
> > if request.user.userflag.is_student:
> > logging.error("studen")
> > inst=FlownMission(
> > student=request.user,
> > base=request.user.studentinfo.current_base
> > )
> > flownmission = FlownMissionForm(request.POST, instance=inst)
> >
> > which does not work at all :( . The validation fails all the time ... . I
> > just need to inject 2 required values somewhere in the POST data, but I
> have
> > no clue how.
> >
> > Any help would be greatly appreciated, and I am a total django "newb" ...
> :)
> >
> > Thanks & greetings,
> > Axel.
>
> --
> 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: ModelForm validation

2010-12-29 Thread derek
Axel

Not sure I have followed all your requirements, but perhaps you can
try:
* set a default value for the required field
* mask the required field on the form being shown to the user (make it
hidden)
* override/check the value for that field after the form POST and data
"clean" (see: 
http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#processing-the-data-from-a-form)

HTH
Derek

On Dec 28, 10:21 pm, Axel Bock  wrote:
> Hi all,
>
> I have this little problem. In my little webapp I have a data model which
> defines several required fields. Depending on WHO is logged on, some of
> these fields should not be changed by the user and be pre-filled (or better:
> post-filled) by the application.
>
> Currently I delete the fields out of the formset like this:
>             # prevent entering missions for all other bases
>             del missionform.fields['base']
>
> so the field gets not rendered in the view. Which works nicely.
>
> Unfortunately base is required, so the validation fails. Now how can I
> insert the missing values into the POST data? I tried this:
>         if request.user.userflag.is_student:
>             logging.error("studen")
>             inst=FlownMission(
>                 student=request.user,
>                 base=request.user.studentinfo.current_base
>             )
>         flownmission = FlownMissionForm(request.POST, instance=inst)
>
> which does not work at all :( . The validation fails all the time ... . I
> just need to inject 2 required values somewhere in the POST data, but I have
> no clue how.
>
> Any help would be greatly appreciated, and I am a total django "newb" ... :)
>
> Thanks & greetings,
> Axel.

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

2010-03-31 Thread Vinicius Mendes
Test if self.instance.user is not None, if so, change the queryset to
exclude the self.instance.user:

http://gist.github.com/350440

__
Vinícius Mendes
Solucione Sistemas
http://solucione.info/


On Wed, Mar 31, 2010 at 11:24 AM, Emanuel  wrote:

> Hi all!
>
> I have a modelform and I want to customize validation.
>
> I'm overriding the method clean_().
>
> When I'm saving the form I want to see if a specific user has been already
> assigned to a project. The only way he can ben assigned again is if he's an
> inactive user, so:
>
> models.py
> Class User(models.Model):
>name = models.CharField(...)
>active = models.BooleanField()
>...
>
> Class Project(models.Model):
>user = models.ForeignKey(User)
>
> **
>
> forms.py
> Class ProjectForm(ModelForm)
>
>def clean_name(self):
>user = self.cleaned_data['user']
>if User.objecs.filter(user.id, active=True):
>raise forms.ValidationError(_("This man has been
> already assign
> to a partner"))
>return user
>
>
> When I'm creating a new project it works fine (I believe, haven't been
> tested
> yet), but when editing it throws an error because the user already exists,
> and
> that's obvious. So, I want to be able to verify if it is a new instance or
> if
> it is an instance being edited.
>
>
> Thanks,
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-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: modelform validation

2010-03-31 Thread Brandon Taylor
Hi there,

When calling def clean_name(self):, you can see if your instance has
an id or not:

def clean_name(self):
if not self.id:
#this would be a new record
else:
#this would be an existing record

HTH,
Brandon

On Mar 31, 9:24 am, Emanuel  wrote:
> Hi all!
>
> I have a modelform and I want to customize validation.
>
> I'm overriding the method clean_().
>
> When I'm saving the form I want to see if a specific user has been already
> assigned to a project. The only way he can ben assigned again is if he's an
> inactive user, so:
>
> models.py
> Class User(models.Model):
>         name = models.CharField(...)
>         active = models.BooleanField()
>         ...
>
> Class Project(models.Model):
>         user = models.ForeignKey(User)
>         
> **
>
> forms.py
> Class ProjectForm(ModelForm)
>         
>         def clean_name(self):
>                 user = self.cleaned_data['user']
>                 if User.objecs.filter(user.id, active=True):
>                         raise forms.ValidationError(_("This man has been
> already assign
> to a partner"))
>                 return user
>
> When I'm creating a new project it works fine (I believe, haven't been tested
> yet), but when editing it throws an error because the user already exists, and
> that's obvious. So, I want to be able to verify if it is a new instance or if
> it is an instance being edited.
>
> Thanks,

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: ModelForm validation

2009-08-10 Thread nostradamnit

Thanks Karen, that was the problem (blush)...


On Aug 10, 3:02 pm, Karen Tracey  wrote:
> On Mon, Aug 10, 2009 at 6:09 AM, nostradamnit wrote:
>
>
>
> > I have a form that inherits from ModelForm, and in my view,
> > form.is_valid returns true, then save() bombs out with validation
> > errors?!?
>
> is_valid is a method.  If you are checking it "if form.is_valid:" that is
> always going to return True because it always exists.  You need to actually
> call the method: "if form.is_valid():"
>
> 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
-~--~~~~--~~--~--~---



Re: ModelForm validation

2009-08-10 Thread Karen Tracey
On Mon, Aug 10, 2009 at 6:09 AM, nostradamnit wrote:

>
> I have a form that inherits from ModelForm, and in my view,
> form.is_valid returns true, then save() bombs out with validation
> errors?!?
>

is_valid is a method.  If you are checking it "if form.is_valid:" that is
always going to return True because it always exists.  You need to actually
call the method: "if form.is_valid():"

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



Re: modelform validation errors

2009-08-02 Thread zayatzz

Digging in documentation surely helps :)

I had to replace
{% if pform.non_field_errors %}
{{ pform.non_field_errors.as_ul }}
{% endif %}

with {{ pform.errors }} to see that about field was causing it. I
overrid about field with tinymce widget in forms.py and did not set
null=True and blank=True there.

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

2009-08-01 Thread zayatzz

Thanks

This might have solved another issue i had not encountered yet, but it
did not solve my current issue :)

Form is still not valid and i have no idea why. If someone would tell
me how modelform error messages are supposed to be used, then they
might help me.
{% if pform.non_field_errors %}
{{ pform.non_field_errors.as_ul }}
{% endif %}

in template does not work for some reason.

Alan
On Aug 2, 2:54 am, prabhu S  wrote:
> The method create_profile returns profile after saving. But this
> object will not contain primary keys etc generated in the db. To work
> around this common issue with django
>
> profile.save()
> # Get the data again from db.
> profile = Profile.objects.get(user=username)
> return profile
>
> Let me know if this helps.
>
> On Aug 1, 8:59 pm, zayatzz  wrote:
>
> > I figured ill add the code i have so far:
>
> > The models:
> > class ProfileManager(models.Manager):
> >         def create_profile(self, username):
> >                 "Creates and saves a User with the given username, e-mail 
> > and
> > password."
> >                 now = datetime.datetime.now()
> >                 profile = self.model(user=username)
> >                 profile.save()
> >                 return profile
>
> > class Profile(models.Model):
> >         """ Profile model """
> >         user = models.ForeignKey(User, unique=True)
> >         birth_date = models.DateField(help_text="birth date",
> > verbose_name="Birth date", blank=True, null=True, )
> >         gender = models.PositiveSmallIntegerField(help_text="gender",
> > choices=GENDER_CHOICES, blank=True, null=True)
> >         about = tinymce_models.HTMLField(blank=True, null=True,
> > help_text="Write something about yourself here",
> > verbose_name="Something about yourself")
> >         # contacts - email, phone nr, website, image
> >         img = models.ImageField(upload_to=upload_location, blank=True,
> > null=True, verbose_name="Your mugshot")
> >         website = models.CharField(max_length=200, blank=True, null=True,
> > help_text="Do you have personal website or blog? Promote it by
> > entering it here", verbose_name="Your Website address")
> >         phonenr = models.CharField(max_length=30, blank=True, null=True,
> > help_text="Your office or home phone number", verbose_name="Your home
> > or office number")
> >         mobilenr = models.CharField(max_length=30, blank=True, null=True,
> > help_text="Your mobile phone number", verbose_name="Your mobile phone
> > nr")
> >         #Full profile - adress will be visible too
> >         country = models.PositiveIntegerField(choices=COUNTRY_CHOICES,
> > blank=True, null=True)
> >         address1 = models.CharField(max_length=200, blank=True, null=True,
> > help_text="Address info - street and house/apartment number")
> >         address2 = models.CharField(max_length=200, blank=True, null=True,
> > help_text="Address info - town and areacode")
> >         address3 = models.CharField(max_length=200, blank=True, null=True,
> > help_text="Address info - county")
> >         publicprofile = models.PositiveSmallIntegerField(help_text="Profile
> > type", choices=PROFILE_CHOICES, blank=True, null=True)
> >         newsletter = models.BooleanField(help_text="Do you want to recieve
> > our newsletter?", verbose_name="Do you want our newsletter",
> > blank=True, null=True)
> >         objects = ProfileManager()
>
> > The Form:
> > class ProfileForm(ModelForm):
> >         about = forms.CharField(widget=TinyMCE(attrs={'cols': 40, 'rows': 
> > 15,
> > 'theme':"simple"}), label = "Something about yourself")
> >         class Meta:
> >                 model = Profile
> >                 fields = ('gender', 'birth_date', 'about', 'img', 'website',
> > 'phonenr', 'mobilenr', 'country', 'address1', 'address2', 'address3',
> > 'publicprofile', 'newsletter', )
>
> > The view:
> > def profile_edit(request):
> >         if request.user.is_authenticated():
> >                 message = "default"
> >                 try:
> >                         profile = Profile.objects.get(user=request.user)
> >                 except:
> >                         profile = 
> > Profile.objects.create_profile(request.user)
> >                 if request.method == 'POST':
> >                         pform = ProfileForm(request.POST, instance=profile)
> >                         if pform.is_valid():
> >                                 pform.save()
> >                                 message = "form vas saved"
> >                         else:
> >                                 message = "form not valid"
> >                 else:
> >                         #dict vaja saata uue formiga
> >                         message = "new form"
> >                         pform = ProfileForm(instance=profile)
> >                 context = { 'message':message, 'pform':pform, }
> >                 return render_to_response('profile/profile_detail.html', 
> > c

Re: modelform validation errors

2009-08-01 Thread prabhu S

The method create_profile returns profile after saving. But this
object will not contain primary keys etc generated in the db. To work
around this common issue with django

profile.save()
# Get the data again from db.
profile = Profile.objects.get(user=username)
return profile

Let me know if this helps.

On Aug 1, 8:59 pm, zayatzz  wrote:
> I figured ill add the code i have so far:
>
> The models:
> class ProfileManager(models.Manager):
>         def create_profile(self, username):
>                 "Creates and saves a User with the given username, e-mail and
> password."
>                 now = datetime.datetime.now()
>                 profile = self.model(user=username)
>                 profile.save()
>                 return profile
>
> class Profile(models.Model):
>         """ Profile model """
>         user = models.ForeignKey(User, unique=True)
>         birth_date = models.DateField(help_text="birth date",
> verbose_name="Birth date", blank=True, null=True, )
>         gender = models.PositiveSmallIntegerField(help_text="gender",
> choices=GENDER_CHOICES, blank=True, null=True)
>         about = tinymce_models.HTMLField(blank=True, null=True,
> help_text="Write something about yourself here",
> verbose_name="Something about yourself")
>         # contacts - email, phone nr, website, image
>         img = models.ImageField(upload_to=upload_location, blank=True,
> null=True, verbose_name="Your mugshot")
>         website = models.CharField(max_length=200, blank=True, null=True,
> help_text="Do you have personal website or blog? Promote it by
> entering it here", verbose_name="Your Website address")
>         phonenr = models.CharField(max_length=30, blank=True, null=True,
> help_text="Your office or home phone number", verbose_name="Your home
> or office number")
>         mobilenr = models.CharField(max_length=30, blank=True, null=True,
> help_text="Your mobile phone number", verbose_name="Your mobile phone
> nr")
>         #Full profile - adress will be visible too
>         country = models.PositiveIntegerField(choices=COUNTRY_CHOICES,
> blank=True, null=True)
>         address1 = models.CharField(max_length=200, blank=True, null=True,
> help_text="Address info - street and house/apartment number")
>         address2 = models.CharField(max_length=200, blank=True, null=True,
> help_text="Address info - town and areacode")
>         address3 = models.CharField(max_length=200, blank=True, null=True,
> help_text="Address info - county")
>         publicprofile = models.PositiveSmallIntegerField(help_text="Profile
> type", choices=PROFILE_CHOICES, blank=True, null=True)
>         newsletter = models.BooleanField(help_text="Do you want to recieve
> our newsletter?", verbose_name="Do you want our newsletter",
> blank=True, null=True)
>         objects = ProfileManager()
>
> The Form:
> class ProfileForm(ModelForm):
>         about = forms.CharField(widget=TinyMCE(attrs={'cols': 40, 'rows': 15,
> 'theme':"simple"}), label = "Something about yourself")
>         class Meta:
>                 model = Profile
>                 fields = ('gender', 'birth_date', 'about', 'img', 'website',
> 'phonenr', 'mobilenr', 'country', 'address1', 'address2', 'address3',
> 'publicprofile', 'newsletter', )
>
> The view:
> def profile_edit(request):
>         if request.user.is_authenticated():
>                 message = "default"
>                 try:
>                         profile = Profile.objects.get(user=request.user)
>                 except:
>                         profile = Profile.objects.create_profile(request.user)
>                 if request.method == 'POST':
>                         pform = ProfileForm(request.POST, instance=profile)
>                         if pform.is_valid():
>                                 pform.save()
>                                 message = "form vas saved"
>                         else:
>                                 message = "form not valid"
>                 else:
>                         #dict vaja saata uue formiga
>                         message = "new form"
>                         pform = ProfileForm(instance=profile)
>                 context = { 'message':message, 'pform':pform, }
>                 return render_to_response('profile/profile_detail.html', 
> context,
> context_instance=RequestContext(request))
>         else:
>                 return HttpResponseRedirect("/accounts/login/")
>
> What i see in view after posting is - form not valid
>
> I really could use help figuring out, why it is not valid.
>
> Alan
--~--~-~--~~~---~--~~
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: modelform validation errors

2009-08-01 Thread zayatzz

I figured ill add the code i have so far:

The models:
class ProfileManager(models.Manager):
def create_profile(self, username):
"Creates and saves a User with the given username, e-mail and
password."
now = datetime.datetime.now()
profile = self.model(user=username)
profile.save()
return profile

class Profile(models.Model):
""" Profile model """
user = models.ForeignKey(User, unique=True)
birth_date = models.DateField(help_text="birth date",
verbose_name="Birth date", blank=True, null=True, )
gender = models.PositiveSmallIntegerField(help_text="gender",
choices=GENDER_CHOICES, blank=True, null=True)
about = tinymce_models.HTMLField(blank=True, null=True,
help_text="Write something about yourself here",
verbose_name="Something about yourself")
# contacts - email, phone nr, website, image
img = models.ImageField(upload_to=upload_location, blank=True,
null=True, verbose_name="Your mugshot")
website = models.CharField(max_length=200, blank=True, null=True,
help_text="Do you have personal website or blog? Promote it by
entering it here", verbose_name="Your Website address")
phonenr = models.CharField(max_length=30, blank=True, null=True,
help_text="Your office or home phone number", verbose_name="Your home
or office number")
mobilenr = models.CharField(max_length=30, blank=True, null=True,
help_text="Your mobile phone number", verbose_name="Your mobile phone
nr")
#Full profile - adress will be visible too
country = models.PositiveIntegerField(choices=COUNTRY_CHOICES,
blank=True, null=True)
address1 = models.CharField(max_length=200, blank=True, null=True,
help_text="Address info - street and house/apartment number")
address2 = models.CharField(max_length=200, blank=True, null=True,
help_text="Address info - town and areacode")
address3 = models.CharField(max_length=200, blank=True, null=True,
help_text="Address info - county")
publicprofile = models.PositiveSmallIntegerField(help_text="Profile
type", choices=PROFILE_CHOICES, blank=True, null=True)
newsletter = models.BooleanField(help_text="Do you want to recieve
our newsletter?", verbose_name="Do you want our newsletter",
blank=True, null=True)
objects = ProfileManager()

The Form:
class ProfileForm(ModelForm):
about = forms.CharField(widget=TinyMCE(attrs={'cols': 40, 'rows': 15,
'theme':"simple"}), label = "Something about yourself")
class Meta:
model = Profile
fields = ('gender', 'birth_date', 'about', 'img', 'website',
'phonenr', 'mobilenr', 'country', 'address1', 'address2', 'address3',
'publicprofile', 'newsletter', )

The view:
def profile_edit(request):
if request.user.is_authenticated():
message = "default"
try:
profile = Profile.objects.get(user=request.user)
except:
profile = Profile.objects.create_profile(request.user)
if request.method == 'POST':
pform = ProfileForm(request.POST, instance=profile)
if pform.is_valid():
pform.save()
message = "form vas saved"
else:
message = "form not valid"
else:
#dict vaja saata uue formiga
message = "new form"
pform = ProfileForm(instance=profile)
context = { 'message':message, 'pform':pform, }
return render_to_response('profile/profile_detail.html', 
context,
context_instance=RequestContext(request))
else:
return HttpResponseRedirect("/accounts/login/")

What i see in view after posting is - form not valid

I really could use help figuring out, why it is not valid.

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