Re: Select a list item by index

2008-11-07 Thread Alex Koshelev
The is not way to get list item by variable index with standard django
template tags.


On Fri, Nov 7, 2008 at 03:52, jago <[EMAIL PROTECTED]> wrote:

>
> I have a for loop over a list A.
>
> inside the loop I want to print out the item of list B at the index
> 'forloop.counter0' of list A.
>
> It is really strange. One can select randon items in a list, or the
> first item in a list, but I did not find a way to select the list item
> by index.
>
> Am I missing something?
>
> >
>

--~--~-~--~~~---~--~~
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: Python package names

2008-11-07 Thread stryderjzw

Ah, I've been busy past couple of days.. but there's some interesting
ideas here.

Thanks!
Justin


On Nov 3, 6:35 am, "Valts Mazurs" <[EMAIL PROTECTED]> wrote:
> Sure, I also keep django apps outside site-packages directory but it is not
> really the same level of convenience :)
>
> Valts.
>
> On Mon, Nov 3, 2008 at 4:07 PM, Jonathan Buchanan <
>
> [EMAIL PROTECTED]> wrote:
>
> > On Mon, Nov 3, 2008 at 1:59 PM, Valts Mazurs <[EMAIL PROTECTED]> wrote:
> > > Usually Django applications are specific to Django and are not really
> > usable
> > > outside Django. That's why seeing "tagging" in my site-packages directory
> > > might confuse me as I could think that this package supports some general
> > > tagging.
>
> > > Valts.
>
> > You can put any directory on your PYTHONPATH - it doesn't necessarily
> > have to be in site-packages.
>
> > Personally, I have django_apps and django_projects directories on my
> > PYTHONPATH for obvious purposes, which are nowhere near my
> > site-packages.
>
> > 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-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: getting request.user into a ModelForm?

2008-11-07 Thread Alex Koshelev
For example you can use `thread locals` to store there request object


On Fri, Nov 7, 2008 at 10:58, Rob Hudson <[EMAIL PROTECTED]> wrote:

>
> I have the following:
>
> ## MODELS
>
> class Category(models.Model):
>user = models.ForeignKey(User)
>name = models.CharField(max_length=200)
>
> class Link(models.Model):
>user = models.ForeignKey(User)
>category = models.ForeignKey(Category)
>name = models.CharField(max_length=255)
>url = models.URLField(max_length=255)
>
> ## FORMS
>
> class CategoryField(forms.Field):
>def clean(self, value):
>if not value:
>raise forms.ValidationError('This field is required.')
>try:
>category = Category.objects.get(user=???, name=value)
>except Category.DoesNotExist:
>category = Category(user=???, name=value)
>category.save()
>return category
>
> class LinkForm(ModelForm):
>category = CategoryField()
>class Meta:
>model = Link
>exclude = ('user', 'url')
>
> ## VIEWS
>
> def create(request):
>if request.method == 'POST':
>form = LinkForm(request.POST)
>if form.is_valid():
>link = form.save(commit=False)
>link.user = request.user
>link.save()
>return HttpResponseRedirect(reverse('link_list'))
>else:
>form = LinkForm()
>
>return render_to_response(
>'links/link_form.html', {
>'form': form,
>},
>context_instance=RequestContext(request)
>)
>
> What I don't see is a way to get the user up into my field the way I
> have things set up.  I originally didn't have a user FK on the
> Category model but decided I wanted it so that when adding new Links,
> the Categories can be filtered by user so each user sees only their
> categories.
>
> I'm stuck here.  Any help is much appreciated.
>
> Thanks,
> Rob
> >
>

--~--~-~--~~~---~--~~
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: Is it possible to output JSON like this?

2008-11-07 Thread Dj Gilcrease

On Fri, Nov 7, 2008 at 12:17 AM, Darthmahon <[EMAIL PROTECTED]> wrote:
>
> Hi guys, I'll give both a try tomorrow when I am near my dev box
> again. Can't really do it in the template as I just want to dump out
> JSON only, but I'll give them both a go :)

I use templates for all my JSON output, make it easier for me to
change it if/when I need

--~--~-~--~~~---~--~~
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: Logout- Back Button

2008-11-07 Thread Raja

If you are using "django.contrib.auth", you can use the
logout_then_login method, which logs out a user, then redirects to the
login page. Since its redirected, you will be brought back to the
login page even if the user hits the back button.

-- Raja

On Nov 7, 9:21 am, jai_python <[EMAIL PROTECTED]> wrote:
> But closing browser after logout in not a proper solution for this
> issue right? just take gmail as example, after logout from gmail
> accont and hit back button, it will prompt to login page, this is one
> proper method for secure our data. Does django supports this
> methodology ?

--~--~-~--~~~---~--~~
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: Logout- Back Button

2008-11-07 Thread Raja

If you are using the "django.contrib.auth" app, then the
logout_then_login method should logout the user, then redirect them to
the login screen. Since this is a http redirect,  doing a back after
logout will still bring them back to login page.

-- raja

On Nov 7, 9:21 am, jai_python <[EMAIL PROTECTED]> wrote:
> But closing browser after logout in not a proper solution for this
> issue right? just take gmail as example, after logout from gmail
> accont and hit back button, it will prompt to login page, this is one
> proper method for secure our data. Does django supports this
> methodology ?

--~--~-~--~~~---~--~~
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: Select a list item by index

2008-11-07 Thread Raja

You can use something like {{ array.index}} to get the value of a
specific index.

For e.g.

arr = [1,2,3,4]

In view, if I do a
{{ arr.1 }}, it should return 2

-- Raja

On Nov 7, 5:52 am, jago <[EMAIL PROTECTED]> wrote:
> I have a for loop over a list A.
>
> inside the loop I want to print out the item of list B at the index
> 'forloop.counter0' of list A.
>
> It is really strange. One can select randon items in a list, or the
> first item in a list, but I did not find a way to select the list item
> by index.
>
> Am I missing something?
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Browser detection in Django

2008-11-07 Thread Alex Jonsson

Hey guys,

I'm working on a Django application where I'd like to redirect IE6
users to a specific page encouraging them to update their browser.

How would be the most efficient way of doing this?

Thanks!
Alex

--~--~-~--~~~---~--~~
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: One Question About Cache

2008-11-07 Thread Rodrigo Lopes
Because I want persistent cache in some cases.

2008/11/7 DULMANDAKH Sukhbaatar <[EMAIL PROTECTED]>

>
> > I want to use per-view cache with memcached and low-level cache with
> > filesystem caching.
>
> what's the advantage of having both of them?
>
>
> --
> Regards
> Dulmandakh
>
> >
>


-- 
Rodrigo Lopes

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



sorting a list of model instances

2008-11-07 Thread Thomas Guettler

Hi,

I just discovered, that you can't sort a list of model instances.

This failed with AssertionError:

view_groups=sorted([brg.group for brg in ... ])
change_groups=sorted([...])
if view_groups==change_groups:
...
else:
assert set(view_groups)!=set(change_groups), (view_groups,
change_groups)
 

Is there a reason why this is this way?

   Thomas

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



setting an IntegerField = None???

2008-11-07 Thread PeteDK

Hiii everybody...

I am trying to create this class called "car".
In this car class i have an IntegerField "year". The thing is, this
field should not be required and therefor the user should not be
"forced" to enter anything into this field if the person doesn't want
to.

However i can't seem to ignore this field??

When i try to say "year = pass", "year=None" or anything like that i
get an error.

For several reasons, I am not interested in just giving this field the
number "0" or something like that... I would really like this field to
be just blank/null/none if the user does not enter anything into this
form-field.

Do you know any way around this? Am i missing an optional argument in
my models.py class or forms.py class??? Or is it simply not possible
with an IntegerField.

If it isn't possible, can i then use som "trick" to get these "blank"
fields??

kind regards..

Peter Møller
--~--~-~--~~~---~--~~
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: Apache Segmentation Fault on succesful authentication

2008-11-07 Thread huw_at1

Graham thanks,

First of all here is my httpd.conf file modules:

# Example:
# LoadModule foo_module modules/mod_foo.so
#

LoadModule python_module modules/mod_python.so
#LoadModule dav_svn_module modules/mod_dav_svn.so
#LoadModule authz_svn_module   modules/mod_authz_svn.so



#

So as you can see the only module I am actually using is the
mod_python one. 'httpd -l' reveals:

  core.c
  mod_authn_file.c
  mod_authn_default.c
  mod_authz_host.c
  mod_authz_groupfile.c
  mod_authz_user.c
  mod_authz_default.c
  mod_auth_basic.c
  mod_include.c
  mod_filter.c
  mod_log_config.c
  mod_env.c
  mod_setenvif.c
  prefork.c
  http_core.c
  mod_mime.c
  mod_status.c
  mod_autoindex.c
  mod_asis.c
  mod_cgi.c
  mod_negotiation.c
  mod_dir.c
  mod_actions.c
  mod_userdir.c
  mod_alias.c
  mod_so.c

Running ldd on mod_python reveals:

/usr/local/apache2/modules/mod_python.so:
libpthread.so.0 => /lib64/libpthread.so.0 (0x2af216d13000)
libdl.so.2 => /lib64/libdl.so.2 (0x2af216f2d000)
libutil.so.1 => /lib64/libutil.so.1 (0x2af217131000)
libm.so.6 => /lib64/libm.so.6 (0x2af217335000)
libc.so.6 => /lib64/libc.so.6 (0x2af2175b8000)
/lib64/ld-linux-x86-64.so.2 (0x0039a2c0)

and on the python ldap module:

/usr/local/lib/python2.5/site-packages/python_ldap-2.3.5-py2.5-linux-
x86_64.egg/_ldap.so
libldap_r-2.3.so.0 => /usr/lib64/libldap_r-2.3.so.0
(0x2aad1567e000)
liblber-2.3.so.0 => /usr/lib64/liblber-2.3.so.0
(0x2aad158c7000)
libsasl2.so.2 => /usr/lib64/libsasl2.so.2 (0x2aad15ad5000)
libssl.so.6 => /lib64/libssl.so.6 (0x2aad15cef000)
libcrypto.so.6 => /lib64/libcrypto.so.6 (0x2aad15f38000)
libpython2.5.so.1.0 => /usr/local/lib/libpython2.5.so.1.0
(0x2aad1628)
libpthread.so.0 => /lib64/libpthread.so.0 (0x2aad165ef000)
libc.so.6 => /lib64/libc.so.6 (0x2aad16809000)
libresolv.so.2 => /lib64/libresolv.so.2 (0x2aad16b5c000)
libdl.so.2 => /lib64/libdl.so.2 (0x2aad16d72000)
libcrypt.so.1 => /lib64/libcrypt.so.1 (0x2aad16f76000)
libgssapi_krb5.so.2 => /usr/lib64/libgssapi_krb5.so.2
(0x2aad171ae000)
libkrb5.so.3 => /usr/lib64/libkrb5.so.3 (0x2aad173dd000)
libcom_err.so.2 => /lib64/libcom_err.so.2 (0x2aad1767)
libk5crypto.so.3 => /usr/lib64/libk5crypto.so.3
(0x2aad17872000)
libz.so.1 => /usr/lib64/libz.so.1 (0x2aad17a98000)
libutil.so.1 => /lib64/libutil.so.1 (0x2aad17cac000)
libm.so.6 => /lib64/libm.so.6 (0x2aad17eaf000)
/lib64/ld-linux-x86-64.so.2 (0x0039a2c0)
libkrb5support.so.0 => /usr/lib64/libkrb5support.so.0
(0x2aad18133000)
libkeyutils.so.1 => /lib64/libkeyutils.so.1
(0x2aad1833b000)
libselinux.so.1 => /lib64/libselinux.so.1 (0x2aad1853e000)
libsepol.so.1 => /lib64/libsepol.so.1 (0x2aad18756000)

and:

/usr/lib64/libldap.so:
liblber-2.3.so.0 => /usr/lib64/liblber-2.3.so.0
(0x0039ad40)
libresolv.so.2 => /lib64/libresolv.so.2 (0x0039ae80)
libsasl2.so.2 => /usr/lib64/libsasl2.so.2 (0x0035dd20)
libssl.so.6 => /lib64/libssl.so.6 (0x003b6960)
libcrypto.so.6 => /lib64/libcrypto.so.6 (0x0039a380)
libc.so.6 => /lib64/libc.so.6 (0x0039a3e0)
libdl.so.2 => /lib64/libdl.so.2 (0x0039a460)
libcrypt.so.1 => /lib64/libcrypt.so.1 (0x0035daa0)
libgssapi_krb5.so.2 => /usr/lib64/libgssapi_krb5.so.2
(0x003b68a0)
libkrb5.so.3 => /usr/lib64/libkrb5.so.3 (0x003b68e0)
libcom_err.so.2 => /lib64/libcom_err.so.2 (0x0039ad80)
libk5crypto.so.3 => /usr/lib64/libk5crypto.so.3
(0x003b6860)
libz.so.1 => /usr/lib64/libz.so.1 (0x0039a4e0)
/lib64/ld-linux-x86-64.so.2 (0x0039a2c0)
libkrb5support.so.0 => /usr/lib64/libkrb5support.so.0
(0x003b6920)
libkeyutils.so.1 => /lib64/libkeyutils.so.1
(0x0039af80)
libselinux.so.1 => /lib64/libselinux.so.1 (0x0039a340)
libsepol.so.1 => /lib64/libsepol.so.1 (0x0039a300)

To me everything matches up. I have had a few other suggestions such
as using strace. This however has so much detail in it is difficult to
trace anything in a multi-thread/child environment. I have also had
suggested mod_backtrace and mod_whatkilledus however these require
recompiling my apache server which is something I am loathed to do as
it is something I have never done before and am worried I will lose my
setup if I do this. So I guess I am open to suggestions as I am trying
to weigh up my options.


On Nov 6, 10:33 pm, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Nov 7, 2:38 am, huw_at1 <[EMAIL PROTECTED]> wrote:
>
> > Hi all. I am having some real problems with this. I have an LDAP
> > authentication 

Re: problem with inlineformset_factory

2008-11-07 Thread Petry

anyone?

On 4 nov, 16:02, Petry <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm having a weird problem when usinginlineformset_factory, he can
> only register up to 2 records, after that causes a validation error
>
> "(Hidden field id) User phone with this None already exists."
>
> Here is my forms [1], models [2] and views [3]
>
> [1]http://dpaste.com/88598/
> [2]http://dpaste.com/88599/
> [3]http://dpaste.com/88600/
>
> --
>
> Marcos DanielPetryhttp://mdpetry.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-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: setting an IntegerField = None???

2008-11-07 Thread Daniel Roseman

On Nov 7, 1:57 pm, PeteDK <[EMAIL PROTECTED]> wrote:
> Hiii everybody...
>
> I am trying to create this class called "car".
> In this car class i have an IntegerField "year". The thing is, this
> field should not be required and therefor the user should not be
> "forced" to enter anything into this field if the person doesn't want
> to.
>
> However i can't seem to ignore this field??
>
> When i try to say "year = pass", "year=None" or anything like that i
> get an error.
>
> For several reasons, I am not interested in just giving this field the
> number "0" or something like that... I would really like this field to
> be just blank/null/none if the user does not enter anything into this
> form-field.
>
> Do you know any way around this? Am i missing an optional argument in
> my models.py class or forms.py class??? Or is it simply not possible
> with an IntegerField.
>
> If it isn't possible, can i then use som "trick" to get these "blank"
> fields??
>
> kind regards..
>
> Peter Møller

You need to have null=True in your model field delcaration:
year = models.IntegerField(blank=True, null=True)

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



Re: Logout- Back Button

2008-11-07 Thread Raja

Sorry for the spam, I thought Google dint record my earlier reply ;)

On Nov 7, 12:36 pm, Raja <[EMAIL PROTECTED]> wrote:
> If you are using the "django.contrib.auth" app, then the
> logout_then_login method should logout the user, then redirect them to
> the login screen. Since this is a http redirect,  doing a back after
> logout will still bring them back to login page.
>
> -- raja
>
> On Nov 7, 9:21 am, jai_python <[EMAIL PROTECTED]> wrote:
>
> > But closing browser after logout in not a proper solution for this
> > issue right? just take gmail as example, after logout from gmail
> > accont and hit back button, it will prompt to login page, this is one
> > proper method for secure our data. Does django supports this
> > methodology ?
--~--~-~--~~~---~--~~
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: Select a list item by index

2008-11-07 Thread jago

Obviously I want to select for each iteration another item from the
array. Unluckily something like:

arr.forloop.counter0

forloop.counter0 is the variable that holds the currently used index
in a for loop: http://www.djangoproject.com/documentation/0.96/templates/#for

Any idea how I could select an item from arr using forloop.counter0 ?

Thx...jago

On Nov 7, 10:38 am, Raja <[EMAIL PROTECTED]> wrote:
> You can use something like {{ array.index}} to get the value of a
> specific index.
>
> For e.g.
>
> arr = [1,2,3,4]
>
> In view, if I do a
> {{ arr.1 }}, it should return 2
>
> -- Raja
>
> On Nov 7, 5:52 am, jago <[EMAIL PROTECTED]> wrote:
>
> > I have a for loop over a list A.
>
> > inside the loop I want to print out the item of list B at the index
> > 'forloop.counter0' of list A.
>
> > It is really strange. One can select randon items in a list, or the
> > first item in a list, but I did not find a way to select the list item
> > by index.
>
> > Am I missing something?
--~--~-~--~~~---~--~~
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: problem with inlineformset_factory

2008-11-07 Thread Daniel Roseman

On Nov 4, 6:02 pm, Petry <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm having a weird problem when using inlineformset_factory, he can
> only register up to 2 records, after that causes a validation error
>
> "(Hidden field id) User phone with this None already exists."
>
> Here is my forms [1], models [2] and views [3]
>
> [1]http://dpaste.com/88598/
> [2]http://dpaste.com/88599/
> [3]http://dpaste.com/88600/
>
> --
>
> Marcos Daniel Petryhttp://mdpetry.net

The problem isn't anything to do with inline forms, it's this in your
model:
user = models.ForeignKey(User
,blank=True
,unique=True)
What you are saying here is that you can only have each value for user
once in the whole table - and that includes the value 'None', ie only
one ShipSalesUser can have an empty user field.

You might want to try OneToOneField there instead and drop the
unique=True.
--
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Select a list item by index

2008-11-07 Thread jago

I tried the slice solution before. Unluckily it returns a list itself
holding 1 item instead of the item itself. Most importantly though I
cannot use a variable like forloop.counter0 to select the item I want
but instead can only use static numeric values like 1,2,3

On Nov 7, 10:39 am, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
> On Nov 7, 12:52 am, jago <[EMAIL PROTECTED]> wrote:
>
> > I have a for loop over a list A.
>
> > inside the loop I want to print out the item of list B at the index
> > 'forloop.counter0' of list A.
>
> > It is really strange. One can select randon items in a list, or the
> > first item in a list, but I did not find a way to select the list item
> > by index.
>
> > Am I missing something?
>
> Use the slice filter.
>
> {{ mylist|slice:"2" }}
>
> --
> 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: sorting a list of model instances

2008-11-07 Thread Jarek Zgoda

Wiadomość napisana w dniu 2008-11-07, o godz. 14:54, przez Thomas  
Guettler:

> I just discovered, that you can't sort a list of model instances.
>
> This failed with AssertionError:
>
>view_groups=sorted([brg.group for brg in ... ])
>change_groups=sorted([...])
>if view_groups==change_groups:
>...
>else:
>assert set(view_groups)!=set(change_groups), (view_groups,
> change_groups)

I always sort lists of model instances using  
sort(key=operator.attrgetter...) idiom (this sorts item in place and  
does not return a copy) and never saw such problems.

-- 
We read Knuth so you don't have to. - Tim Peters

Jarek Zgoda, R, Redefine
[EMAIL PROTECTED]


--~--~-~--~~~---~--~~
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: defaultdict is not working on "for" template tag iteration.

2008-11-07 Thread Karen Tracey
On Fri, Nov 7, 2008 at 2:51 AM, Hyungyong Kim <[EMAIL PROTECTED]> wrote:

>
> Hi,
>
> Since a few hours ago, I've suffered following problem.
> I found this problem is due to collections.defaultdict.
>
> Normal dictionary is working collectly, but defaultdict is not
> working.
>
> >>> from django.template import Template, Context
> >>> t = Template("{% for k,v in data.items %}{{ k }}: {{ v }}{% endfor %}")
> >>> normal_dict = {'a':1, 'b':2}
> >>> t.render(Context({'data':normal_dict}))
> u'a: 1b: 2'
> >>>
> >>> from collections import defaultdict
> >>> default_dict = defaultdict(int)
> >>> default_dict[1]+=1
> >>> default_dict[2]+=1
> >>> default_dict[1]+=1
> >>> default_dict
> defaultdict(, {1: 2, 2: 1})
> >>> t.render(Context({'data':default_dict}))
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> line 176, in render
>return self.nodelist.render(context)
>  File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> line 768, in render
>bits.append(self.render_node(node, context))
>  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> line 81, in render_node
>raise wrapped
> django.template.TemplateSyntaxError: Caught an exception while
> rendering: 'int' object is not iterable
>
> Original Traceback (most recent call last):
>  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> line 71, in render_node
>result = node.render(context)
>  File "/usr/lib/python2.5/site-packages/django/template/
> defaulttags.py", line 122, in render
>values = list(values)
> TypeError: 'int' object is not iterable
>
> >>>
>

This is due to the interaction between the way in which Django attempts to
resolve variables containing dots in templates (see
http://docs.djangoproject.com/en/dev/topics/templates/#variables) and the
fact that when you attempt to access a non-existent key in a defaultdict
(that has a default_factory like you have specified) it automatically gets
created.  So, Django's first attempt to resolve data.items is a dictionary
lookup of 'items' in your default dict (default_dict['items']), and instead
of failing it returns the default value of 0.  Since the dictionary acess
attempt works, Django goes ahead and attempts to use the returned value
instead of moving on an trying the other lookup methods.

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



Re: Custom clean methods for admin site?

2008-11-07 Thread krase



On 3 Nov., 16:34, Bülent Aldemir <[EMAIL PROTECTED]> wrote:
> Create methods with  like:
>
> class MyModel(models.Model):
>     mystring = models.CharField(max_length=100)
>
> class MyForm(forms.ModelForm):
>    def clean_mystring(self):
>        raise forms.ValidationError('Error Message')
>

Thanks a lot! It works.
It even works with __getattr__, so i do not have to create a subclass
for
every model.

class MyForm(forms.ModelForm):
   def do_authorisation(self, name):
  print self.Meta.model._meta.verbose_name
  #raise forms.ValidationError('Error Message')
  return self.cleaned_data[name]

   def __getattr__(self, name):
  print name
  if name[:6] == 'clean_':
 return lambda: self.do_authorisation(name[6:])


Greets,
Sebastian

--~--~-~--~~~---~--~~
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: problem with inlineformset_factory

2008-11-07 Thread Karen Tracey
On Fri, Nov 7, 2008 at 9:10 AM, Daniel Roseman <
[EMAIL PROTECTED]> wrote:

>
> On Nov 4, 6:02 pm, Petry <[EMAIL PROTECTED]> wrote:
> > Hi all,
> >
> > I'm having a weird problem when using inlineformset_factory, he can
> > only register up to 2 records, after that causes a validation error
> >
> > "(Hidden field id) User phone with this None already exists."
> >
> > Here is my forms [1], models [2] and views [3]
> >
> > [1]http://dpaste.com/88598/
> > [2]http://dpaste.com/88599/
> > [3]http://dpaste.com/88600/
> >
> > --
> >
> > Marcos Daniel Petryhttp://mdpetry.net
>
> The problem isn't anything to do with inline forms, it's this in your
> model:
>user = models.ForeignKey(User
>,blank=True
>,unique=True)
> What you are saying here is that you can only have each value for user
> once in the whole table - and that includes the value 'None', ie only
> one ShipSalesUser can have an empty user field.
>
>
I have not looked at the original problem in any detail, but the failure to
allow multiple NULL values when unique=True is set for the field was a
Django bug that has been fixed, see:

http://code.djangoproject.com/ticket/9039

So, if this is the cause of the problem, using the 1.0.X branch or current
trunk code instead of 1.0 should fix 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: sorting a list of model instances

2008-11-07 Thread Daniel Roseman

On Nov 7, 1:54 pm, Thomas Guettler <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just discovered, that you can't sort a list of model instances.
>
> This failed with AssertionError:
>
>         view_groups=sorted([brg.group for brg in ... ])
>         change_groups=sorted([...])
>         if view_groups==change_groups:
>             ...
>         else:
>             assert set(view_groups)!=set(change_groups), (view_groups,
> change_groups)
>
> Is there a reason why this is this way?
>
>    Thomas
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de

You haven't given any key or cmp values in the sorted() call to tell
it what to sort on. Certainly this works for me:
sorted([item for item in qs], key=lambda x: x.name)

Although I would have to wonder why you're doing it this way, rather
than using the database to sort them? I understand that you're getting
all group items that are related to a brg, but a better way of doing
it would be something like:
Group.objects.filter(brg__isnull=False).order_by('name')
or whatever.

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



Re: sorting a list of model instances

2008-11-07 Thread Thomas Guettler

Hi,
> Although I would have to wonder why you're doing it this way, rather
> than using the database to sort them? 
Since in my case it is easier. I need to filter out some item before.
This calculation
needs to be in python code.

  Thomas

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



Re: An interesting URL dispatcher problem

2008-11-07 Thread redmonkey

Here's my solutions, for anyone who may be experiencing the same
problem.

In my url config, I have 4 different named patterns corresponding to
each of the possibilities:

url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/$',
'catalogueFilter', name="catalogue_search_no_filters"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P\d+(?=-))?-(?P(?<=-)\d+)?/$',
'catalogueFilter', name="catalogue_search_estimates"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P[a-zA-Z0-9%]+)/$', 'catalogueFilter',
name="catalogue_search_desc"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P\d+(?=-))?-(?P(?<=-)\d+)?/(?
P[a-zA-Z0-9%]+)/$', 'catalogueFilter',
name="catalogue_search_estimates_desc"),

I apologise for them being a bit messy, but you can see that each
pattern starts with "(?P[a-zA-Z]+)/(?P[\+\-].\w+)"
These correspond to the drop down boxes in my form. They will always
be submitted. The first pattern contains just these parameters, and so
the url is called "catalogue_search_no_filters".

Second, we have a pattern for if some estimates are submitted. These
are optional form fields that can be filled in if the user wants to
narrow down the search. In order to allow for this flexibility, there
are a lot of '?' in the regular expression. The regular expression
adds a '-' character in to represent a range of values.

We then have another url for just the optional description field. This
is a simple text search.

Finally I have a named url for the optional estimate fields and an
optional description field. I was trying to write one single url that
allowed for both, but I couldn't. Instead I came up with this
solution. I different named url that points to the same view function.

The view function itself is pretty straight forward. It accepts all
the parameters and includes so default values:

def catalogueFilter(request, site='any', min_estimate=None,
max_estimate=None,
sort_by=LotSearchForm.SORT_CHOICES_URLS[0][1], description=None):

 do stuff, get "results' together ...

return object_list(
request=request,
queryset=results,
page=page,
paginate_by=20,
template_object_name="lot",
extra_context=dict(
search_form=form
)
)

I'm using a generic view to return the HttpResponse.

The messy bit is how I determine which named url to call. I'm afriad
it's a lot of if/else statements branching off to different
HttpResponseRedirects:

if ("min_estimate" in params) or ("max_estimate" in params):
if "description" in params:
return HttpResponseRedirect(
reverse('catalogue_search_estimates_desc', kwargs=params))
else:
return HttpResponseRedirect(
reverse('catalogue_search_estimates', kwargs=params)
else:
if "description" in params:
return HttpResponseRedirect(
reverse('catalogue_search_desc', kwargs=params))
else:
return HttpResponseRedirect(
reverse('catalogue_search_no_filters', kwargs=params))

I admit this isn't elegant at all, but it works. If anyone has any
ideas on how I could improve this, please let me know. If nothing
else, it might clear up what I'm trying to do here.

Thanks,

RM

On Nov 4, 5:48 pm, redmonkey <[EMAIL PROTECTED]> wrote:
> Hi Brian,
>
> Thanks for your comment. I completely understand what you are saying,
> and anyone trying to match the "?" character should take note, but in
> this situation I am using it to try to tell Django that that named
> group in the regular expression may, or may not, be included.
>
> RM
>
> On Nov 4, 5:33 pm, Brian Neal <[EMAIL PROTECTED]> wrote:
>
> > On Nov 4, 10:50 am, redmonkey <[EMAIL PROTECTED]> wrote:
>
> > > My problem is with the URL writing. I first wrote some unit tests to
> > > find the regular expressions that worked but Django doesn't seem to
> > > like the '?' in URL configurations.
>
> > ? is a special character in regular expressions, just like $, ^, etc.
> > You must escape it if you want to use it literally, e.g. \?. However,
> > I don't think the ? as part of any GET arguments in a URL are going to
> > be available to you, from what I remember about django works.
>
> > I'm not really following what you are trying to do however.
--~--~-~--~~~---~--~~
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: problem with inlineformset_factory

2008-11-07 Thread Petry

I changed my template model to use OneToOneField and remove the
Blank=True, but the same error appears...

On 7 nov, 12:30, "Karen Tracey" <[EMAIL PROTECTED]> wrote:
> On Fri, Nov 7, 2008 at 9:10 AM, Daniel Roseman <
>
>
>
> [EMAIL PROTECTED]> wrote:
>
> > On Nov 4, 6:02 pm, Petry <[EMAIL PROTECTED]> wrote:
> > > Hi all,
>
> > > I'm having a weird problem when using inlineformset_factory, he can
> > > only register up to 2 records, after that causes a validation error
>
> > > "(Hidden field id) User phone with this None already exists."
>
> > > Here is my forms [1], models [2] and views [3]
>
> > > [1]http://dpaste.com/88598/
> > > [2]http://dpaste.com/88599/
> > > [3]http://dpaste.com/88600/
>
> > > --
>
> > > Marcos Daniel Petryhttp://mdpetry.net
>
> > The problem isn't anything to do with inline forms, it's this in your
> > model:
> >    user = models.ForeignKey(User
> >                            ,blank=True
> >                            ,unique=True)
> > What you are saying here is that you can only have each value for user
> > once in the whole table - and that includes the value 'None', ie only
> > one ShipSalesUser can have an empty user field.
>
> I have not looked at the original problem in any detail, but the failure to
> allow multiple NULL values when unique=True is set for the field was a
> Django bug that has been fixed, see:
>
> http://code.djangoproject.com/ticket/9039
>
> So, if this is the cause of the problem, using the 1.0.X branch or current
> trunk code instead of 1.0 should fix 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Oracle Clob Field type

2008-11-07 Thread [EMAIL PROTECTED]

You're right -- there's no need to run syncdb.  All of this is a
learning exercise for me.
I'm just running the commands to see the output and behavior as I go
through the docs, with an eye for potential snags and "gotchas" that
might kill me later on.




On Nov 5, 9:06 pm, "Karen Tracey" <[EMAIL PROTECTED]> wrote:
> On Wed, Nov 5, 2008 at 5:54 PM, [EMAIL PROTECTED] <
>
>
>
> [EMAIL PROTECTED]> wrote:
>
> > Noob here...
>
> > I have an existing table with two Clob fields.  While defining the
> > model I use TextField as the filed type.
>
> > running  gives me back the error:
>
> > cx_Oracle.DatabaseError: ORA-01754: a table may contain only one
> > column of type LONG
>
> > Well, what I really want are clobs to begin with.  It sounds like what
> > I really want to do is subclass Field, but this is starting to turn in
> > to more trouble than it's worth...
>
> > This has to be something somebody's come across before.
>
> I've no experience with Oracle but -- you run syncdb to create your tables.
> If you already have the table, why are you running syncdb?
>
> 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
-~--~~~~--~~--~--~---



Re: date formats in settings.py

2008-11-07 Thread Benedict Verheyen

Benedict Verheyen wrote:


I have solved it in my view.
However, i'm not sure this is the best way to deal with it.
In my view i set the input_formats of the datefield like this:

report_f = ReportForm(request.POST,instance=r)
report_f.base_fields['date_reported'].input_formats = ('%d/%m/%Y',)

To display the date correctly in my form:
r.date_reported = r.date_reported.strftime("%d/%m/%Y")

I would feel cleaner if i would be able to set these in the form.
Is there anyway i could move this logic to the form definition?

Regards,
Benedict


--~--~-~--~~~---~--~~
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: Select a list item by index

2008-11-07 Thread Daniel Roseman

On Nov 7, 2:12 pm, jago <[EMAIL PROTECTED]> wrote:
> I tried the slice solution before. Unluckily it returns a list itself
> holding 1 item instead of the item itself. Most importantly though I
> cannot use a variable like forloop.counter0 to select the item I want
> but instead can only use static numeric values like 1,2,3
>

Hmm, if you're already looping through something, you should probably
make sure that all the things you need to refer to are contained in
the same iterable - for example by using zip(list1, list2) in your
view.

If you posted some code showing what you are trying to do, we might be
able to help a bit more.
--
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Select a list item by index

2008-11-07 Thread jago

Sure.

{% for gallerykind in gallerykinds %}

{{ gallerykind.title }}

{% if gallerykind.author %}
by {{ gallerykind.author }}
{% endif %}

{{ agelist.forloop.counter0 
}}

{% endfor %}

My problem is agelist. I tried to indicated my intent by writing
agelist.forloop.counter0.

Where do I do this zip() operation? In the python code before
constructing the template or in the django-code?

wrapper = zip(list1, list2)

Access in the django code is then:

{% for w in wrapper %}
 w.0.title
 w.1

???


On Nov 7, 4:45 pm, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
> On Nov 7, 2:12 pm, jago <[EMAIL PROTECTED]> wrote:
>
> > I tried the slice solution before. Unluckily it returns a list itself
> > holding 1 item instead of the item itself. Most importantly though I
> > cannot use a variable like forloop.counter0 to select the item I want
> > but instead can only use static numeric values like 1,2,3
>
> Hmm, if you're already looping through something, you should probably
> make sure that all the things you need to refer to are contained in
> the same iterable - for example by using zip(list1, list2) in your
> view.
>
> If you posted some code showing what you are trying to do, we might be
> able to help a bit more.
> --
> 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Select a list item by index

2008-11-07 Thread Daniel Roseman

On Nov 7, 12:52 am, jago <[EMAIL PROTECTED]> wrote:
> I have a for loop over a list A.
>
> inside the loop I want to print out the item of list B at the index
> 'forloop.counter0' of list A.
>
> It is really strange. One can select randon items in a list, or the
> first item in a list, but I did not find a way to select the list item
> by index.
>
> Am I missing something?

Use the slice filter.

{{ mylist|slice:"2" }}

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



Easy way to serialize objects

2008-11-07 Thread Ivan Tarradellas

Hi all,

With Django, what is the easy and best way to serialize/deserialize
objects that are no Django objects?

django.core.serializers only works with Django objects. But what
happens if we have other object type?

How to serialize this:

class MyClass(object):
a = 'a'
b = 'b'



xml = serialization.serialize("xml",MyClass())

Tnxs

--~--~-~--~~~---~--~~
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: Browser detection in Django

2008-11-07 Thread Nikolay Panov

Maybe you need something like that: http://www.djangosnippets.org/snippets/267/

Have a nice day,
   Nikolay.



On Fri, Nov 7, 2008 at 13:36, Alex Jonsson <[EMAIL PROTECTED]> wrote:
>
> Hey guys,
>
> I'm working on a Django application where I'd like to redirect IE6
> users to a specific page encouraging them to update their browser.
>
> How would be the most efficient way of doing this?
>
> Thanks!
> Alex
>
> >
>

--~--~-~--~~~---~--~~
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 inheritance - getting data from child objects

2008-11-07 Thread Gerard flanagan

Alistair Marshall wrote:
> As I said, I have the function named the same in each child class but
> I need to be able to access it from a list of all the Places.
> 
> My current thinking is just a long list of try, except: statements
> attempting to call the subclass from the Place model but this feels
> hacky and un-clean.
> 

I don't know if it's clever or stupid, but this is what I have done in a 
similar situation:

#-
class Item(models.Model):
 
   typecode = models.CharField(max_length=30, editable=False)

   def save(self, force_insert=False, force_update=False):
 self.typecode = self.__class__.__name__.lower()
 super(Item, self).save(force_insert, force_update)

   def get_related(self):
 return 
self.__class__.__dict__[self.typecode].related.model.objects.get(id=self.id)

class SubItem(Item):
 

#-


If called from an Item instance, 'get_related' will return the related 
SubItem instance.  In your case, you would first get the 'restaurant', 
then call it's 'get_workforce'. Still working on it, so there may be 
unforseen issues.

Regards

G.


--~--~-~--~~~---~--~~
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: Using Django

2008-11-07 Thread Blu3ness

500 error will generate a error log in your ~/logs/ directory, do a
little research on it, or maybe post it here :)

On Nov 6, 1:58 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I think I had the .htaccess and dispatch.fcgi  files in the wrong
> place. I had them in the django generated mysite directory rather the
> than the domain, but now when I go to mysite.com I get the 500
> internal server error. This happened when I tried the Jeff Croft
> setup:http://jeffcroft.com/blog/2006/may/11/django-dreamhost/which
> is where I heard about the Gordon Tillman fix. Thanks for the help
> thus far and any related to my new problem.
>
> Jason
>
> On Nov 6, 9:56 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > I used the Gordon Tillman 
> > setup:http://www.gordontillman.info/Development/DjangoDreamhost
> > here are the dispatch.fcgi and .htaccess files:
>
> > // dispatch.fcgi
>
> > #!/usr/bin/env python2.4
> > import sys, os
>
> > # Add a custom Python path.
> > sys.path.insert(0, "/home/USERNAME/projects/django/trunk")
> > sys.path.insert(0, "/home/USERNAME/projects/flup/trunk")
> > sys.path.insert(0, "/home/USERNAME/projects")
>
> > //.htaccess
>
> > # Set the DJANGO_SETTINGS_MODULE environment variable.
> > os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
>
> > from django.core.servers.fastcgi import runfastcgi
> > runfastcgi(method="threaded", daemonize="false")
>
> > AddHandler fastcgi-script .fcgi
> > RewriteEngine On
> > RewriteBase /
> > RewriteRule ^(media/.*)$ - [L]
> > RewriteRule ^(admin_media/.*)$ - [L]
> > RewriteRule ^(dispatch\.fcgi/.*)$ - [L]
> > RewriteRule ^(.*)$ dispatch.fcgi/$1 [L]
>
> > Here is my directory structure:
>
> > home/USERNAME/
> >    www.mysite.com/
> >    www.anothersite.com/
> >    www.yetanothersite.com/
> >    projects/
> >       django/
> >       flup/
> >       django_templates/
> >       media/
> >       mysite/
>
> > On Nov 5, 5:56 pm, AndyB <[EMAIL PROTECTED]> wrote:
>
> > >http://wiki.dreamhost.com/index.php/Django
>
> > > Have you got the .htaccess, dispatch.fcgi etc all set up?
--~--~-~--~~~---~--~~
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 Inheritance - And Signals

2008-11-07 Thread Vitaly Babiy
if I define a model called CustomModel and I attach attach a pre_save signal
to it. Is there any way to have that signal be called any time model that
extends CustomModel is being saved has that method saved.

I know i could do this by overriding the save method on CustomeModel but I
was wondering if there is any way to do it with signals.

Thanks,
Vitaly Babiy

--~--~-~--~~~---~--~~
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 Inheritance - And Signals

2008-11-07 Thread Alex Koshelev
Try to connection handler without `sender` specified. And filter needed
models inside it.

def my_handler(sender, **kwargs):
if not isinstance(sender, CustomModel):
   return

signals.pre_save.connect(my_handler)


On Fri, Nov 7, 2008 at 20:03, Vitaly Babiy <[EMAIL PROTECTED]> wrote:

> if I define a model called CustomModel and I attach attach a pre_save
> signal to it. Is there any way to have that signal be called any time model
> that extends CustomModel is being saved has that method saved.
>
> I know i could do this by overriding the save method on CustomeModel but I
> was wondering if there is any way to do it with signals.
>
> Thanks,
> Vitaly Babiy
>
>

--~--~-~--~~~---~--~~
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 Inheritance - And Signals

2008-11-07 Thread Vitaly Babiy
Thanks Alex that worked great.
Vitaly Babiy


On Fri, Nov 7, 2008 at 12:19 PM, Alex Koshelev <[EMAIL PROTECTED]> wrote:

> Try to connection handler without `sender` specified. And filter needed
> models inside it.
>
> def my_handler(sender, **kwargs):
> if not isinstance(sender, CustomModel):
>return
>
> signals.pre_save.connect(my_handler)
>
>
> On Fri, Nov 7, 2008 at 20:03, Vitaly Babiy <[EMAIL PROTECTED]> wrote:
>
>> if I define a model called CustomModel and I attach attach a pre_save
>> signal to it. Is there any way to have that signal be called any time model
>> that extends CustomModel is being saved has that method saved.
>>
>> I know i could do this by overriding the save method on CustomeModel but I
>> was wondering if there is any way to do it with signals.
>>
>> Thanks,
>> Vitaly Babiy
>>
>>
>
> >
>

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



Apache cookie authentification

2008-11-07 Thread Matt

Hi,

I am trying to enable django cookie based authentification within
apache using the patch at http://code.djangoproject.com/ticket/3583.
Apache seems to be suceffuly passing the request onto django, but then
fails with the following error:

[Fri Nov 07 17:47:40 2008] [error] [client 10.1.0.27]   File "C:\
\Python25\\lib\\site-packages\\mod_python\\importer.py", line 1537, in
HandlerDispatch\ndefault=default_handler, arg=req,
silent=hlist.silent)
[Fri Nov 07 17:47:40 2008] [error] [client 10.1.0.27]   File "C:\
\Python25\\lib\\site-packages\\mod_python\\importer.py", line 1229, in
_process_target\nresult = _execute_target(config, req, object,
arg)
[Fri Nov 07 17:47:40 2008] [error] [client 10.1.0.27]   File "C:\
\Python25\\lib\\site-packages\\mod_python\\importer.py", line 1128, in
_execute_target\nresult = object(arg)
[Fri Nov 07 17:47:40 2008] [error] [client 10.1.0.27]   File "C:\
\Python25\\lib\\site-packages\\django\\contrib\\auth\\handlers\
\modpython.py", line 76, in authenhandler\n
dispatcher.send(signal=signals.request_started)
[Fri Nov 07 17:47:40 2008] [error] [client 10.1.0.27] AttributeError:
'module' object has no attribute 'send'

ny ideas?
--~--~-~--~~~---~--~~
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: getting request.user into a ModelForm?

2008-11-07 Thread Benedict Verheyen

Rob Hudson wrote:
> I have the following:
> 
> ## MODELS
> 
> class Category(models.Model):
> user = models.ForeignKey(User)
> name = models.CharField(max_length=200)
> 
> class Link(models.Model):
> user = models.ForeignKey(User)
> category = models.ForeignKey(Category)
> name = models.CharField(max_length=255)
> url = models.URLField(max_length=255)
> 
> ## FORMS
> 
> class CategoryField(forms.Field):
> def clean(self, value):
> if not value:
> raise forms.ValidationError('This field is required.')
> try:
> category = Category.objects.get(user=???, name=value)
> except Category.DoesNotExist:
> category = Category(user=???, name=value)
> category.save()
> return category
> 
> class LinkForm(ModelForm):
> category = CategoryField()
> class Meta:
> model = Link
> exclude = ('user', 'url')
> 
> ## VIEWS
> 
> def create(request):
> if request.method == 'POST':
> form = LinkForm(request.POST)
> if form.is_valid():
> link = form.save(commit=False)
> link.user = request.user
> link.save()
> return HttpResponseRedirect(reverse('link_list'))
> else:
> form = LinkForm()
> 
> return render_to_response(
> 'links/link_form.html', {
> 'form': form,
> },
> context_instance=RequestContext(request)
> )
> 
> What I don't see is a way to get the user up into my field the way I
> have things set up.  I originally didn't have a user FK on the
> Category model but decided I wanted it so that when adding new Links,
> the Categories can be filtered by user so each user sees only their
> categories.
> 
> I'm stuck here.  Any help is much appreciated.
> 
> Thanks,
> Rob

Everything you have setup looks ok, i do it exactly like this to get the
users in a field so it's not exactly clear to me what's wrong.
I suppose you have enabled the AuthenticationMiddleware in the settings
as well as added django.contrib.auth & django.contrib.sessions to the apps ?
Also did you do a syncdb and check the Link table to verify that it has
a user field?

Regards,
Benedict


--~--~-~--~~~---~--~~
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 inheritance - getting data from child objects

2008-11-07 Thread Alistair Marshall



On Nov 7, 4:19 pm, Gerard flanagan <[EMAIL PROTECTED]> wrote:
> I don't know if it's clever or stupid, but this is what I have done in a
> similar situation:
>

It appears to be a nice solution - it throws an error If I try to
get_related() on a generic non-specialised place rather than just
returning itself, but I don't think that will be a problem for this
application.

-- update actually this can be fixed with a try except statement:
#-
class Item(models.Model):
 
   typecode = models.CharField(max_length=30, editable=False)

   def save(self, force_insert=False, force_update=False):
 self.typecode = self.__class__.__name__.lower()
 super(Item, self).save(force_insert, force_update)

   def get_related(self):
try:
  return
self.__class__.__dict__[self.typecode].related.model.objects.get(id=self.id)
except:
  return self

class SubItem(Item):
 

#-

Thanks

Alistair

--
Alistair Marshall

www.thatscottishengineer.co.uk
--~--~-~--~~~---~--~~
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: i18n strategy

2008-11-07 Thread davidynamic

to quote the django internationizaton documentation...

"Using ugettext_lazy() and ungettext_lazy() to mark strings in models
and utility functions is a common operation. "

Getting data from your models requires you to place
django.utils.translation.ugettext_lazy() functions within the
arguments that you pass to the fields
that you create for your models.

you'll find your examples here.
http://docs.djangoproject.com/en/dev/topics/i18n/?from=olddocs#lazy-translation

Then you can use the same message (po) files you use when rendering
static strings in templates

Hope this helps


--~--~-~--~~~---~--~~
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: defaultdict is not working on "for" template tag iteration.

2008-11-07 Thread Raja

Well, it does, except that when you do a default_dict.items, it adds
"items" to the dict with a value of 0 in the template. To verify this,
try dumping default_dict after the exception is thrown. You will get a
new key called "items".

To fix your problem, pass dict(default_dict) to the Context.
>>> t.render(Context({'data': dict(default_dict)}))

-- Raja

On Nov 7, 12:51 pm, Hyungyong Kim <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Since a few hours ago, I've suffered following problem.
> I found this problem is due to collections.defaultdict.
>
> Normal dictionary is working collectly, but defaultdict is not
> working.
>
> >>> from django.template import Template, Context
> >>> t = Template("{% for k,v in data.items %}{{ k }}: {{ v }}{% endfor %}")
> >>> normal_dict = {'a':1, 'b':2}
> >>> t.render(Context({'data':normal_dict}))
> u'a: 1b: 2'
>
> >>> from collections import defaultdict
> >>> default_dict = defaultdict(int)
> >>> default_dict[1]+=1
> >>> default_dict[2]+=1
> >>> default_dict[1]+=1
> >>> default_dict
>
> defaultdict(, {1: 2, 2: 1})>>> 
> t.render(Context({'data':default_dict}))
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> line 176, in render
> return self.nodelist.render(context)
>   File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> line 768, in render
> bits.append(self.render_node(node, context))
>   File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> line 81, in render_node
> raise wrapped
> django.template.TemplateSyntaxError: Caught an exception while
> rendering: 'int' object is not iterable
>
> Original Traceback (most recent call last):
>   File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> line 71, in render_node
> result = node.render(context)
>   File "/usr/lib/python2.5/site-packages/django/template/
> defaulttags.py", line 122, in render
> values = list(values)
> TypeError: 'int' object is not iterable
>
>
>
> I think defaultdict have to work as normal dict.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Django with Apache2 on Ubuntu

2008-11-07 Thread project2501

Hi,
  I got Django to work behind Apache2 with mod_python, but had some
questions for the experts.

1) Is there an easy way to log stdout without re-writing all my output
statements? What about python logging?
2) Is there a good way in Django to put startup code when deployed in
Apache that only gets run once per server restart? I build some
indexes that are used by my Django apps but it only needs to be done
at initialize time once.

thanks,
Darren
--~--~-~--~~~---~--~~
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: getting request.user into a ModelForm?

2008-11-07 Thread Daniel Roseman

On Nov 7, 9:02 am, "Alex Koshelev" <[EMAIL PROTECTED]> wrote:
> For example you can use `thread locals` to store there request object

Really, don't. As James has posted here many times, this was only ever
at best a horrible hack, and is now completely unnecessary.

In response to the OP, I'm not sure what the code is doing in the
CategoryField's clean() method. It doesn't seem to be the right place
to be saving changes to objects - for instance, what if you category
field is valid, but other fields on the form fail validation?

Instead of doing it there, I would do it in the Form's save() method.
To get access to the user, override the __init__ method of your form
to take a request parameter, and cache this as self.request. Something
like (untested):

class LinkForm(forms.ModelForm):
class Meta:
model = Link
exclude = ('user', 'url')

def __init__(self, request, *args, **kwargs):
self.request = request
super(LinkForm, self).__init__(*args, **kwargs)

def save(self, *args, **kwargs):
self.cleaned_data['category'] =
Category.objects.get_or_create(
category=self.cleaned_data['category'],
user=request.user
)
obj = super(LinkForm, self).save(*args, **kwargs)

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



Using just one custom manager

2008-11-07 Thread John M

I wanted to get some feedback on how I'm using custom model managers.

I've put all my queries into one manager, each in a different method.
Is this the right way to go?

So for example:

CHOICES_TASK = (
("NO", "None"),
("GR", "Green"),
("YL", "Yellow"),
("RD", "Red"),
)

class TaskManager(models.Manager):
use_for_related_fields = True

# Task.objects.all()
def get_query_set(self):
return super(TaskManager, self).get_query_set()

# Task.milestones()
def Milestones(self):
return super(TaskManager,
self).get_query_set().filter(milestone=True)

def Accomplishments(self):
return super(TaskManager,
self).get_query_set().filter(milestone=False).filter(completed=True)

def Nextsteps(self):
return super(TaskManager,
self).get_query_set().filter(milestone=False).filter(completed=False)

class Task(models.Model):
report = models.ForeignKey(Report)
name = models.CharField(max_length=50)
started = models.BooleanField(default=False)
status = models.CharField(max_length=20, choices=CHOICES_TASK,
default="NO")
completed = models.BooleanField(default=False)
duedate = models.DateField(blank=True, null=True)
milestone = models.BooleanField(default=False)

# Managers
objects = TaskManager()
milestones = TaskManager().Milestones
accomplishments = TaskManager().Accomplishments
nextsteps = TaskManager().Nextsteps

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



Custom Form Widget that can render different HTML form elements?

2008-11-07 Thread Ken Cochrane

Hello,

I was wondering if I could get some advice for the following problem I
am trying to solve.  Is it possible to have a form field (or widget)
render different html elements depending on different situations?

To help illustrate my point, I have come up with the following fake
scenario which is similar to what I want to do.  Suppose you have a
database table with product information. Lets say you have different
types of Shoes, Nails, and Rulers. The Shoes can have multiple sizes
(9,10,12,etc.) , The Nails are ordered by the pound, and you can
select any size you want as long as it is between the range (25-300
pounds). The Rulers only come in one size.

If I wanted to use the same html form for all three products, I would
normally have to use the same html field for size for all three and
this doesn't quite work out. If I use a text field, It would work but
I would have to have complex validations to make sure they type in a
value that is correct, and that isn't ideal. I could use a pull down
box, but displaying every value between 25-300 in a pull down would be
pretty long, and having a pull down value for one element is also
annoying.

Ideally I would like to use a different element for each situation, I
would like to use a hidden field for the ruler since they don't need
to pick the value, but we still need the size. For shoes I would like
to use a pull down, and for Nails, I would like to use a text field.

My first thought was to create a custom widget and I would pass in
some parameters and depending on those parameters it would display the
appropriate HTML form element. I started down this road, and the code
doesn't seem very clean, so either I am doing it wrong, or what I am
doing isn't supported.  The complex part that I am trying to figure
out is how do I pass the parameters that I need from the view to the
Custom Widget? I have this working, but it looks very ugly.

I also thought about doing this as a template tag, but I am not sure
if this is any better. The main downfall for this approach is that I
don't think that I can use any of the django form stuff when I do it
this way. Or could I?

Has anyone done something like this before? Does anyone have a better
way to do this?

Any advice that you could give, would be great.

Thanks,

Ken Cochrane


Note: In my real life example I get my Product Size from a REST web
service, but I figured the database table would make it easier to
explain.


(this is only pseudo code) excuse the formatting.

Models:

class ProductSize(models.Model):
values = models.CharField(max_length=50)  # The values could be
"25" , or "25,50,100" , "25-300"
type = models.CharField(max_length=50)  # types could be "fixed" ,
"multi" , "range"

class Product(models.Model):
sizes = models.ForeignKey(ProductSize)
name = models.CharField(max_length=50)
description = models.CharField(max_length=50)

class Order(models.Model):
size =  models.CharField(max_length=50) # I don't want the foreign
key, I just want the value.
name = models.CharField(max_length=50) # name of product
order_date = models.DateTimeField() # date of order


ModelForm:

class ProductForm(ModelForm):
size = CharField(widget=TextInput())
name = CharField(widget=TextInput())
description = CharField(widget=Textarea())


View :

def product_view(request):
product_form = ProductForm()
return render_to_response({'product_form': product_form})

--~--~-~--~~~---~--~~
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: Select a list item by index

2008-11-07 Thread Daniel Roseman

On Nov 7, 4:11 pm, jago <[EMAIL PROTECTED]> wrote:
> Sure.
>
>                 {% for gallerykind in gallerykinds %}
>                         
>                                         {{ gallerykind.title }}
>
>                                         {% if gallerykind.author %}
>                                                 by  rel="nofollow" href="/gallery?
> username={{ gallerykind.author }}">{{ gallerykind.author }}
>                                         {% endif %}
>
>                                         {{ 
> agelist.forloop.counter0 }}
>                         
>                 {% endfor %}
>
> My problem is agelist. I tried to indicated my intent by writing
> agelist.forloop.counter0.

What is agelist, though? Is it another queryset? How is it related to
the gallerykinds queryset?


> Where do I do this zip() operation? In the python code before
> constructing the template or in the django-code?
>
> wrapper = zip(list1, list2)
>
> Access in the django code is then:
>
> {% for w in wrapper %}
>      w.0.title
>      w.1
>
> ???

That depends on what agelist is, but yes that's the right idea.
--
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Using just one custom manager

2008-11-07 Thread Daniel Roseman

On Nov 7, 7:13 pm, John M <[EMAIL PROTECTED]> wrote:
> I wanted to get some feedback on how I'm using custom model managers.
>
> I've put all my queries into one manager, each in a different method.
> Is this the right way to go?
>
> So for example:
>
> CHOICES_TASK = (
>                         ("NO", "None"),
>                         ("GR", "Green"),
>                         ("YL", "Yellow"),
>                         ("RD", "Red"),
>                 )
>
> class TaskManager(models.Manager):
>         use_for_related_fields = True
>
>         # Task.objects.all()
>         def get_query_set(self):
>                 return super(TaskManager, self).get_query_set()
>
>         # Task.milestones()
>         def Milestones(self):
>                 return super(TaskManager,
> self).get_query_set().filter(milestone=True)
>
>         def Accomplishments(self):
>                 return super(TaskManager,
> self).get_query_set().filter(milestone=False).filter(completed=True)
>
>         def Nextsteps(self):
>                 return super(TaskManager,
> self).get_query_set().filter(milestone=False).filter(completed=False)
>
> class Task(models.Model):
>         report = models.ForeignKey(Report)
>         name = models.CharField(max_length=50)
>         started = models.BooleanField(default=False)
>         status = models.CharField(max_length=20, choices=CHOICES_TASK,
> default="NO")
>         completed = models.BooleanField(default=False)
>         duedate = models.DateField(blank=True, null=True)
>         milestone = models.BooleanField(default=False)
>
>         # Managers
>         objects = TaskManager()
>         milestones = TaskManager().Milestones
>         accomplishments = TaskManager().Accomplishments
>         nextsteps = TaskManager().Nextsteps
>
>         def __unicode__(self):
>                 return self.name


There's nothing wrong with the general idea - that's how I do it
myself, although the official docs say to use multiple managers and
override get_query_set on each one. A couple of comments on your
implementation though:

1. There's no point in defining a get_query_set model simply to pass
to super. If you don't define it at all, it will just inherit from the
parent class anyway, which is exactly the same as what happens in your
version, so you may as well save two lines of code.

2. The convention in Python/Django is to have all lower case names for
functions and methods - so it should be milestones, accomplishments,
etc.

3. I don't think there's any point in defining all the extra manager
attributes that you have. Leave objects as TaskManager, then you can
do things like:
Task.objects.milestones()
Task.objects.accomplishments().filter(started=False)
or whatever.

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



SQL Join in Django

2008-11-07 Thread Hossein

Hi,

I am a newbie and am trying to select fields from two table related to
each other using a foreign key:

class Reporter()
 id  primary key
 name
 e-mail
 ...

class Article()
reporter = model.ForeignKey(reporter)
date
...

Now I want to implement the following SQL statement in Django:

select name,e-mail,date from Reporter,Article where reporter = 10

I tried filter, select_related, etc. but I could not get what I want.

Any help will be greatly appreciated

--~--~-~--~~~---~--~~
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: SQL Join in Django

2008-11-07 Thread Tim Chase

> class Reporter()
>  id  primary key
>  name
>  e-mail
>  ...
> 
> class Article()
> reporter = model.ForeignKey(reporter)
> date
> ...
> 
> Now I want to implement the following SQL statement in Django:
> 
> select name,e-mail,date from Reporter,Article where reporter = 10


Are you sure this is the query you want?  It's a cartesian join 
that will return *all* reporters associated with *every* article 
written by reporter=10.  I suspect you _mean_

  select
   name, email, date
  from reporter r
   inner join article a  -- use an inner join, not cart' join
   on r.id = a.reporter_id
  where r.id = 10

which can be done with something like

   arts = Article.objects.filter(reporter_id=10).select_related()
   for article in arts:
 print article.reporter.name, str(article)

-tim





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



Fixtures erase data?

2008-11-07 Thread Dana

Hey everyone,

I just set up a few fixtures for some of my models and realized that
every time I syncdb it changes the existing data in my database. I
assume this is normal behavior, but I was wondering if it is possible
to have the fixtures only *add* data and not change it?

For example:

I have a fixture that adds a row to my model with the value "foo",
then I change it in the admin to "bar", then syncdb, it gets changed
back to "foo". Is there a way to keep the changed value of "bar"?

Thanks for your time,
Dana

--~--~-~--~~~---~--~~
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: SQL Join in Django

2008-11-07 Thread Hossein

Many thanks tim for your quick reply. You are right I meant inner join
not cart product.
I tried your suggested solution and instead of printing the result I
use Django serializer to create an XML file. But it seems that
something is taking too
long and my browser just stalls. Is it because of select_related()
method? I have about 200 articles per each reporter.


On Nov 7, 2:16 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > class Reporter()
> >  id  primary key
> >  name
> >  e-mail
> >  ...
>
> > class Article()
> > reporter = model.ForeignKey(reporter)
> > date
> > ...
>
> > Now I want to implement the following SQL statement in Django:
>
> > select name,e-mail,date from Reporter,Article where reporter = 10
>
> Are you sure this is the query you want?  It's a cartesian join
> that will return *all* reporters associated with *every* article
> written by reporter=10.  I suspect you _mean_
>
>   select
>name, email, date
>   from reporter r
>inner join article a  -- use an inner join, not cart' join
>on r.id = a.reporter_id
>   where r.id = 10
>
> which can be done with something like
>
>arts = Article.objects.filter(reporter_id=10).select_related()
>for article in arts:
>  print article.reporter.name, str(article)
>
> -tim
--~--~-~--~~~---~--~~
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: SQL Join in Django

2008-11-07 Thread Tim Chase

> I tried your suggested solution and instead of printing the result I
> use Django serializer to create an XML file. But it seems that
> something is taking too
> long and my browser just stalls. Is it because of select_related()
> method? I have about 200 articles per each reporter.

Another possibility might be (since you're only looking at one 
author)

   reporter = Reporter.objects.get(id=10)
   arts = reporter.article_set
   for art in arts:
 print reporter, art

Even that considered, 200 articles/reporter is still pretty 
chump-change.  I've worked with data-sets several orders of 
magnitude larger than that and haven't had performance problems. 
  Alternatively, your templating output might be your bottleneck 
(but you don't mention how you're creating your output, so it's 
hard to tell).

-tim





--~--~-~--~~~---~--~~
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: SQL Join in Django

2008-11-07 Thread Hossein

Thanks for your help. I am so close to what I want.

The output that I want is an XML file. So I try:
  reporter = Reporter.objects.get(id=10)
  arts = reporter.article_set.all()
  xmlout = serialize('xml',arts,fields=('date','reporter.name'))

However, it writes date but it does not write reporter.name into the
XML file.

Any help in this regard?

On Nov 7, 2:33 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I tried your suggested solution and instead of printing the result I
> > use Django serializer to create an XML file. But it seems that
> > something is taking too
> > long and my browser just stalls. Is it because of select_related()
> > method? I have about 200 articles per each reporter.
>
> Another possibility might be (since you're only looking at one
> author)
>
>reporter = Reporter.objects.get(id=10)
>arts = reporter.article_set
>for art in arts:
>  print reporter, art
>
> Even that considered, 200 articles/reporter is still pretty
> chump-change.  I've worked with data-sets several orders of
> magnitude larger than that and haven't had performance problems.
>   Alternatively, your templating output might be your bottleneck
> (but you don't mention how you're creating your output, so it's
> hard to tell).
>
> -tim
--~--~-~--~~~---~--~~
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: filtering in a template based on foreign key or query params

2008-11-07 Thread Milan Andric

Any thoughts on this one?  Just checking.

Thanks.

On Nov 6, 9:06 pm, "Milan Andric" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a view that displays hundreds of applications based on some filter
> params.  But I want to render the actual template based on user (an fkey)
> and list their applications as sub objects. but only the applications that
> were filtered on. bleh.
>
> So in the view I do something like:
>
>         # define queryset params from query string.
>         query_params = {
>             'status'   : request.GET.get('status', None),
>             'complete' : request.GET.get('complete', None),
>             'workshop__in' : request.GET.getlist('workshop__in'),
>             'user__is_active':True,
>         }
>         # form params need to be integers
>         query_params['workshop__in'] = [int(i) for i in
> query_params['workshop__
> in']]
>
>         # None or '' means don't filter on it.  Remove it so
>         # Foo.objects.filter() will give the correct results.
>         for key in query_params.keys():
>             if query_params[key] == None or query_params[key] == '':
>                 del query_params[key]
>
>         # Pass query dict we just built as keyword args to filter().
>         queryset = Application.objects.filter(**query_params)
>
> This gives me applications based on the query params that I iterate over in
> my template.  The problem is I want to change the template now to display
> based on the person/user foreign key and have the applications listed
> underneath the person.  If I send a queryset of Users to the template then I
> can get a list of users but I lose the applications filters.  Or is this a
> good solution for some kind of querying filter/template tag?  If I send a
> list of applications then  I can't list by user.
>
> Any suggestions?
>
> Thank you,
>
> --
> Milan
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



__import__(settings) failure

2008-11-07 Thread matthew

Hi,

I'm sure this is a properly neophyte post, but I'm stumped and would
really appreciate some guidance. I am trying to serve a site under
apache2 using django. I have apache2 and mod_python installed (setup
below). I have followed the instructions at
http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs
about configuring apache. My apache2.conf contains:


SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE WORD.settings
PythonDebug On
PythonPath "['/home/matthew/current/django','/home/matthew/current/
django/WORD'] + sys.path"


When I navigate to localhost/WORD/publications (where my app is) I
see:

[START ERROR]
Mod_python error: "PythonHandler django.core.handlers.modpython"

Traceback (most recent call last):

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line
299, in HandlerDispatch
result = object(req)

  File "/var/lib/python-support/python2.4/django/core/handlers/
modpython.py", line 163, in handler
return ModPythonHandler()(req)

  File "/var/lib/python-support/python2.4/django/core/handlers/
modpython.py", line 125, in __call__
if settings.ENABLE_PSYCO:

  File "/var/lib/python-support/python2.4/django/conf/__init__.py",
line 27, in __getattr__
self._import_settings()

  File "/var/lib/python-support/python2.4/django/conf/__init__.py",
line 53, in _import_settings
self._target = Settings(settings_module)

  File "/var/lib/python-support/python2.4/django/conf/__init__.py",
line 81, in __init__
raise EnvironmentError, "Could not import settings '%s' (Is it on
sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE,
e)

EnvironmentError: Could not import settings 'WORD.settings' (Is it on
sys.path? Does it have syntax errors?): No module named WORD.settings
[END ERROR]

So apache2 is handing the request on to django via mod_python
appropriately, but django is failing to load the settings module. To
check that it has placed the module parent directory on the sys.path,
I added to the error message in /var/lib/python-support/python2.4/
django/conf/__init__.py like this:

[START CODE]
 raise EnvironmentError, "Could not import settings '%s' (Is it on
sys.path? Does it have syntax errors?): %s\n\nsys.path=%s" %
(self.SETTINGS_MODULE, e,sys.path)
[END CODE]

which produced:

[START ERROR]
EnvironmentError: Could not import settings 'WORD.settings' (Is it on
sys.path? Does it have syntax errors?): No module named WORD.settings

sys.path=['/home/matthew/current/django', '/home/matthew/current/
django/WORD', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/
python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/
python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/
usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/
Numeric', '/usr/lib/python2.4/site-packages/cairo', '/var/lib/python-
support/python2.4', '/var/lib/python-support/python2.4/gtk-2.0', '/usr/
lib/site-python']
[END ERROR]

Which confirms the appropriate directories are visible. To check that
settings.py has no syntax errors, I ran the interpreter and executed
the following:

[START INTERPRETER]
$ python
Python 2.4.4 (#2, Apr 15 2008, 23:43:20)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path = ['/home/matthew/current/django'] + sys.path
>>> import WORD.settings
>>> WORD.settings.INSTALLED_APPS
('django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.admin', 'django.views.static', 'WORD.publications')
[END INTERPRETER]

so it loads ok with a normal import, but reading /var/lib/python-
support/python2.4/django.conf/__init__.py, the exception is raised in
__import__(), like this:

[START CODE]
try:
mod = __import__(self.SETTINGS_MODULE, '', '', [''])
 except ImportError, e:
raise EnvironmentError, "Could not import settings '%s' (Is it on
sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE,
e)
[END CODE]

so I also ran that command in the interpeter:

[START INTERPRETER]
>>> mod = __import__('WORD.settings', '', '', [''])
>>> mod

>>> WORD.settings.INSTALLED_APPS
('django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.admin', 'django.views.static', 'WORD.publications')
[END INTERPETER]

and it works fine in this instance. I'm sure that I'm missing
something blindingly obvious, but if someone could please point it out
to me I'd be really grateful.

I am using:
Debian Stable (Etch)
Python 2.4.4-2
Django 0.95.1-1etch2
Apache2  2.2.3-4+etch6
mod_python  3.2.10-4

Many thanks in advance,

Matthew

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to 

Checkout and follow @djangopro on twitter (Aggregated Django News and Tips)

2008-11-07 Thread djangopro

Hello everybody,

We will be broadcasting professional django development news and tips
via our twitter http://twitter.com/djangopro. Please follow and let
everybody know. @djangopro is an effort to make the django community
stronger. More to come.

Thanks,

@djangopro

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



DateField() value as 000-00-00

2008-11-07 Thread VP

Hi all,
My question is:

Is there any chance to put into a DB date field a value -00-00
using Django ORM?
My users upload their data into a DB using Django application.

If the data field is empty from their source file, Django generate an
exception that format is not correct.

I was trying to parse their data and replace it empty date fields
values by a '-00-00', no luck.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



How to order a list with a self-referential foreign key? (a category list)

2008-11-07 Thread [EMAIL PROTECTED]

I have a list of categories that allows you to set a parent/child
relationship such as:

  Financial
  Financial > Billing
  Financial > Billing > Collections
  Financial > Invoices

In the example above, "Financial" is a category, then "Billing" is a
category with "Financial" as the parent, etc.


I've got two problems I'm trying to solve:

1. Users shouldn't be able to set the parent object as itself

This can happen if save a category, then go back in and edit it. With
the way I'm returning the get_full_name() method, this causes a
recursion problem.

Is there a way to filter the current object out of the parent dropdown
in the admin? This should be pretty easy to do with logic outside of
the admin, but I'd like it to work properly inside the admin as well.
I was trying to find a way to use a pre or post-save hook to see if
the new value being saved for parent was equal to the object's ID and
causing a validation error, but couldn't quite nail it.

2. I'd like to group the subcategories by their parent categories all
the way down the hierarchy

I thought about trying to use the flattened hierarchy in a character
field and sorting by that (which worked) but if a parent category
changed, you have to go through and resave all the categories and
their flattened structures again to update them. That could work, but
it doesn't feel like the right approach.

I'm at a loss for ideas, does anyone have a clever solution for me?

Here's the model:

class Category(models.Model):
name = models.CharField(max_length=200)
parent = models.ForeignKey('self', null=True, blank=True)

def get_full_name(self):
if self.parent:
return "%s: %s" % (self.parent.get_full_name(), self.name)
else:
return self.name

def save(self, force_insert=False, force_update=False):
# Don't let people save itself as parent
if self.id and self.parent:
if self.id == self.parent.id:
return False
super(Category, self).save(force_insert, force_update)

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



Re: defaultdict is not working on "for" template tag iteration.

2008-11-07 Thread Hyungyong Kim

Thanks for kind expatiation. I can understand why the error occured
easily.

But, it seems that templates' "." has to resolve dir(default_dict)
first before dictionary lookup.
Anyway, I glad to know the reason. Thanks.

Hyungyong Kim


On 11월7일, 오후10시18분, "Karen Tracey" <[EMAIL PROTECTED]> wrote:
> On Fri, Nov 7, 2008 at 2:51 AM, Hyungyong Kim <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > Since a few hours ago, I've suffered following problem.
> > I found this problem is due to collections.defaultdict.
>
> > Normal dictionary is working collectly, but defaultdict is not
> > working.
>
> > >>> from django.template import Template, Context
> > >>> t = Template("{% for k,v in data.items %}{{ k }}: {{ v }}{% endfor %}")
> > >>> normal_dict = {'a':1, 'b':2}
> > >>> t.render(Context({'data':normal_dict}))
> > u'a: 1b: 2'
>
> > >>> from collections import defaultdict
> > >>> default_dict = defaultdict(int)
> > >>> default_dict[1]+=1
> > >>> default_dict[2]+=1
> > >>> default_dict[1]+=1
> > >>> default_dict
> > defaultdict(, {1: 2, 2: 1})
> > >>> t.render(Context({'data':default_dict}))
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> > line 176, in render
> >return self.nodelist.render(context)
> >  File "/usr/lib/python2.5/site-packages/django/template/__init__.py",
> > line 768, in render
> >bits.append(self.render_node(node, context))
> >  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> > line 81, in render_node
> >raise wrapped
> > django.template.TemplateSyntaxError: Caught an exception while
> > rendering: 'int' object is not iterable
>
> > Original Traceback (most recent call last):
> >  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
> > line 71, in render_node
> >result = node.render(context)
> >  File "/usr/lib/python2.5/site-packages/django/template/
> > defaulttags.py", line 122, in render
> >values = list(values)
> > TypeError: 'int' object is not iterable
>
> This is due to the interaction between the way in which Django attempts to
> resolve variables containing dots in templates 
> (seehttp://docs.djangoproject.com/en/dev/topics/templates/#variables) and the
> fact that when you attempt to access a non-existent key in a defaultdict
> (that has a default_factory like you have specified) it automatically gets
> created.  So, Django's first attempt to resolve data.items is a dictionary
> lookup of 'items' in your default dict (default_dict['items']), and instead
> of failing it returns the default value of 0.  Since the dictionary acess
> attempt works, Django goes ahead and attempts to use the returned value
> instead of moving on an trying the other lookup methods.
>
> 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
-~--~~~~--~~--~--~---



How to handle this Error: Error binding parameter 1 - probably unsupported type.

2008-11-07 Thread 为爱而生
Environment: Request Method: POST Request URL:
http://127.0.0.1:8080/save/Django Version: 1.0-final-SVN-unknown
Python Version: 2.5.2 Installed
Applications: ['django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django_bookmarks.bookmarks'] Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File
"C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs) File
"D:\django\django_bookmarks\..\django_bookmarks\bookmarks\views.py" in
bookmark_save_page 79. link=link File
"C:\Python25\Lib\site-packages\django\db\models\manager.py" in get_or_create
96. return self.get_query_set().get_or_create(**kwargs) File
"C:\Python25\Lib\site-packages\django\db\models\query.py" in get_or_create
326. return self.get(**kwargs), False File
"C:\Python25\Lib\site-packages\django\db\models\query.py" in get 298. num =
len(clone) File "C:\Python25\Lib\site-packages\django\db\models\query.py" in
__len__ 154. self._result_cache = list(self.iterator()) File
"C:\Python25\Lib\site-packages\django\db\models\query.py" in iterator 269.
for row in self.query.results_iter(): File
"C:\Python25\Lib\site-packages\django\db\models\sql\query.py" in
results_iter 206. for rows in self.execute_sql(MULTI): File
"C:\Python25\Lib\site-packages\django\db\models\sql\query.py" in execute_sql
1700. cursor.execute(sql, params) File
"C:\Python25\Lib\site-packages\django\db\backends\util.py" in execute 19.
return self.cursor.execute(sql, params) File
"C:\Python25\Lib\site-packages\django\db\backends\sqlite3\base.py" in
execute 167. return Database.Cursor.execute(self, query, params) Exception
Type: InterfaceError at /save/ Exception Value: Error binding parameter 1 -
probably unsupported type.
I use django 1.0 and I learn the 0.96.But I don't know what is been updated
and which one is the unsupported type on the problem above.
So I wan't get answer here,Please help me!!! Thanks!
-- 
"OpenBookProject"-开放图书计划邮件列表
详情: http://groups.google.com/group/OpenBookProject
维基: http://wiki.woodpecker.org.cn/

--~--~-~--~~~---~--~~
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: DateField() value as 000-00-00

2008-11-07 Thread DULMANDAKH Sukhbaatar

> I was trying to parse their data and replace it empty date fields
> values by a '-00-00', no luck.

maybe you should try to set default value in database engine. as I
know mysql supports it, and inserts default value if no value has been
provided.


-- 
Regards
Dulmandakh

--~--~-~--~~~---~--~~
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: Using just one custom manager

2008-11-07 Thread John M

Dave,

Thanks for the quick reply, yea, I figured out what I needed to do,
which turns out just what you said.

I will change to the pythonic way of doing things, thanks.

John

On Nov 7, 11:47 am, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
> On Nov 7, 7:13 pm, John M <[EMAIL PROTECTED]> wrote:
>
>
>
> > I wanted to get some feedback on how I'm using custom model managers.
>
> > I've put all my queries into one manager, each in a different method.
> > Is this the right way to go?
>
> > So for example:
>
> > CHOICES_TASK = (
> >                         ("NO", "None"),
> >                         ("GR", "Green"),
> >                         ("YL", "Yellow"),
> >                         ("RD", "Red"),
> >                 )
>
> > class TaskManager(models.Manager):
> >         use_for_related_fields = True
>
> >         # Task.objects.all()
> >         def get_query_set(self):
> >                 return super(TaskManager, self).get_query_set()
>
> >         # Task.milestones()
> >         def Milestones(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=True)
>
> >         def Accomplishments(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=False).filter(completed=True)
>
> >         def Nextsteps(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=False).filter(completed=False)
>
> > class Task(models.Model):
> >         report = models.ForeignKey(Report)
> >         name = models.CharField(max_length=50)
> >         started = models.BooleanField(default=False)
> >         status = models.CharField(max_length=20, choices=CHOICES_TASK,
> > default="NO")
> >         completed = models.BooleanField(default=False)
> >         duedate = models.DateField(blank=True, null=True)
> >         milestone = models.BooleanField(default=False)
>
> >         # Managers
> >         objects = TaskManager()
> >         milestones = TaskManager().Milestones
> >         accomplishments = TaskManager().Accomplishments
> >         nextsteps = TaskManager().Nextsteps
>
> >         def __unicode__(self):
> >                 return self.name
>
> There's nothing wrong with the general idea - that's how I do it
> myself, although the official docs say to use multiple managers and
> override get_query_set on each one. A couple of comments on your
> implementation though:
>
> 1. There's no point in defining a get_query_set model simply to pass
> to super. If you don't define it at all, it will just inherit from the
> parent class anyway, which is exactly the same as what happens in your
> version, so you may as well save two lines of code.
>
> 2. The convention in Python/Django is to have all lower case names for
> functions and methods - so it should be milestones, accomplishments,
> etc.
>
> 3. I don't think there's any point in defining all the extra manager
> attributes that you have. Leave objects as TaskManager, then you can
> do things like:
> Task.objects.milestones()
> Task.objects.accomplishments().filter(started=False)
> or whatever.
>
> --
> 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Fixtures erase data?

2008-11-07 Thread DULMANDAKH Sukhbaatar

> I just set up a few fixtures for some of my models and realized that
> every time I syncdb it changes the existing data in my database. I
> assume this is normal behavior, but I was wondering if it is possible
> to have the fixtures only *add* data and not change it?

As I understand, and also as documented syncdb doesn't change existing
table. you should modify your model, after or before that you should
alter your table to consist with model.

> I have a fixture that adds a row to my model with the value "foo",
> then I change it in the admin to "bar", then syncdb, it gets changed
> back to "foo". Is there a way to keep the changed value of "bar"?

after changing row you don't need to run syncdb, just save it.


-- 
Regards
Dulmandakh

--~--~-~--~~~---~--~~
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: __import__(settings) failure

2008-11-07 Thread Karen Tracey
On Fri, Nov 7, 2008 at 5:28 PM, matthew <[EMAIL PROTECTED]> wrote:

>
> Hi,
>
> I'm sure this is a properly neophyte post, but I'm stumped and would
> really appreciate some guidance. I am trying to serve a site under
> apache2 using django. I have apache2 and mod_python installed (setup
> below). I have followed the instructions at
>
> http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs
> about configuring apache. My apache2.conf contains:
>
> 
>SetHandler python-program
>PythonHandler django.core.handlers.modpython
>SetEnv DJANGO_SETTINGS_MODULE WORD.settings
>PythonDebug On
>PythonPath "['/home/matthew/current/django','/home/matthew/current/
> django/WORD'] + sys.path"
> 
>
> When I navigate to localhost/WORD/publications (where my app is) I
> see:
>
> [START ERROR]
> Mod_python error: "PythonHandler django.core.handlers.modpython"
>
> Traceback (most recent call last):
>
> [snip]



> ... I'm sure that I'm missing
> something blindingly obvious, but if someone could please point it out
> to me I'd be really grateful.
>

Does the user Apache is running as have read access to the directory with
your code?


>
> I am using:
> Debian Stable (Etch)
> Python 2.4.4-2
> Django 0.95.1-1etch2
> Apache2  2.2.3-4+etch6
> mod_python  3.2.10-4
>

BTW unless you are using pre-existing code written for the 0.95 level of
Django I would not recommend that level.  Django 1.0 would be a much better
place to start from.

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



select for update

2008-11-07 Thread tegbert

SELECT FOR UPDATE has been discussed in this group before, but I don't
think it's been resolved whether it should be implemented in Django. I
think it should.

The idea is to avoid update collisions, i.e., the situation in which
one process is attempting to select a row and update it, and while
doing so, another process selects and updates the row in a manner
inconsistent with the what the first process is trying to do.

For example, I have an application in which a user submits a "job"
through the web interface (web app). This requires uploading a file
and queueing the job into a database row with status='ready'. A
separate "worker" application is looking for jobs that are 'ready', so
it queries the DB with SELECT and gets back the same row. The worker
app then updates the status to 'running' and goes off to handle the
job, using the uploaded file in the process.

But then the user decides to cancel the job, which is allowed so long
as the job status is still 'ready' but not yet 'running'. The user
clicks the 'cancel' button which in turn results in a SELECT for rows
with status='ready'. It so happens that the user makes the query after
the worker app SELECT is executed but before it UPDATEs the status to
'running'. Thus, both the web app and the worker app have the same
record and want to do inconsistent things. The web app wants to cancel
the job, so it deletes the file out from under the worker app and
updates status to 'deleted'. This causes grief for the worker app, so
it Exceptions out. No joy.

A better way would be to perform both SELECTS with the FOR UPDATE
clause inside of transactions. Suppose the worker app does this:

BEGIN;
SELECT * FROM  WHERE status='ready' FOR UPDATE;
UPDATE  SET status='running' WHERE status='ready';
COMMIT;

and concurrently, the web app does this:

BEGIN;
SELECT * FROM  WHERE status='ready' FOR UPDATE;
UPDATE  SET status='deleted' WHERE status='ready';
COMMIT;

The second SELECT to execute will have to wait until the first
transaction is over, at least with Postgresql, and then it will not
find a row because the status is no longer 'ready'. Thus, no collision
and all is well.

Update collision issues must be fairly common. I've seen discussions
in other forums. I've also done some looking around into the lower
levels of django.db.models and think "SELECT FOR UPDATE" could be
implemented with (1) a filter option that appends "FOR UPDATE" at the
end of the SELECT string, and (2) a save() with force_update=True.
But, I'm not all that familiar with how all those low level parts
interact. Any thoughts on how this could be implemented would be
appreciated.

Thanks,

--Tim

--~--~-~--~~~---~--~~
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: select for update

2008-11-07 Thread Karen Tracey
On Fri, Nov 7, 2008 at 9:45 PM, tegbert <[EMAIL PROTECTED]> wrote:

>
> SELECT FOR UPDATE has been discussed in this group before, but I don't
> think it's been resolved whether it should be implemented in Django. I
> think it should.
>
> [snip]
>
... Any thoughts on how this could be implemented would be
> appreciated.
>

There's a ticket for this, with a not-too-old patch:

http://code.djangoproject.com/ticket/2705

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



Re: Fixtures erase data?

2008-11-07 Thread Dana Woodman
>
> As I understand, and also as documented syncdb doesn't change existing
> table.


I wish that were true but its not the case. When I run syncdb, it will alter
the object if it was already created.

Here is what my initial_data.json file looks like:

[
{
"pk": 1,
"model": "myapp.mymodel",
"fields": {
"title": "Foo"
}
}
]

When I first run this, it will create an object with the name "Foo". If I
change it in the admin to "Bar" and save it, then syncdb again, it changes
back to "Foo". Is there a way around this behavior? Is there something I can
put in my initial_data.json file to get it to work the way I want?

Thanks,
D

--~--~-~--~~~---~--~~
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: Fixtures erase data?

2008-11-07 Thread Russell Keith-Magee

On Sat, Nov 8, 2008 at 5:13 AM, Dana <[EMAIL PROTECTED]> wrote:
>
> Hey everyone,
>
> I just set up a few fixtures for some of my models and realized that
> every time I syncdb it changes the existing data in my database. I
> assume this is normal behavior, but I was wondering if it is possible
> to have the fixtures only *add* data and not change it?

The initial data fixture is reloaded every time that syncdb is
executed; this will overwrite any changes that have been made to that
initial data. This is normal, intended behaviour, and there isn't a
setting or option to change this behaviour.

Having an option to add data in the way you describe isn't really a
good idea. If the syncdb behaviour was changed to add rather than
overwrite initial data, you would have a different (and IMHO much
worse) consequence - each time you run syncdb, you will end up with
another copy of the initial data. If you run syncdb 100 times, you
would end up with 100 copies of each fixture object.

The purpose behind the initial data fixture is to provide *absolutely
essential* initial data that must exist in order for the database to
work - for example, the root node of a tree structure. If you have
other data that is required to bootstrap the system - especially if
that data is subject to change over the lifespan of the website -
define that data in a fixture other that initial_data (say
bootstrap_data), and manually load that fixture using loaddata. That
way the bootstrap data will only be loaded (and therefore overwritten)
when you explictly request a reload.

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?hl=en
-~--~~~~--~~--~--~---



Re: Logout- Back Button

2008-11-07 Thread jai_python

thanks alot for your reply. i need to check out this logout_then_login
method. i will update the status after testing.
Thanks
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Fixtures erase data?

2008-11-07 Thread Dana Woodman
> The initial data fixture is reloaded every time that syncdb is
> executed; this will overwrite any changes that have been made to that
> initial data. This is normal, intended behaviour, and there isn't a
> setting or option to change this behaviour.
>

I had a feeling that was the case...

Having an option to add data in the way you describe isn't really a
> good idea. If the syncdb behaviour was changed to add rather than
> overwrite initial data, you would have a different (and IMHO much
> worse) consequence - each time you run syncdb, you will end up with
> another copy of the initial data. If you run syncdb 100 times, you
> would end up with 100 copies of each fixture object.
>

What I was envisioning was a solution that would check if the PK existed, if
it did, it would pass, if not, it would add the rows. The intended use was
to populate a database at first go with the needed data, but still be able
to run syncdb without mucking things up. Guess I'll have to go the other
route.

The purpose behind the initial data fixture is to provide *absolutely
> essential* initial data that must exist in order for the database to
> work - for example, the root node of a tree structure. If you have
> other data that is required to bootstrap the system - especially if
> that data is subject to change over the lifespan of the website -
> define that data in a fixture other that initial_data (say
> bootstrap_data), and manually load that fixture using loaddata. That
> way the bootstrap data will only be loaded (and therefore overwritten)
> when you explictly request a reload.
>

Thanks, that is good advice, I will go ahead and do that. That will
accomplish just about what I am looking for.

Would it suffice to just rename the file/folder to
bootstrap_data/bootstrap_data.json? Does Django look for a file called
initial_data.json in a folder called initial_data, or does it just look for
any file called initial_data.json?

Thanks a lot Russ.

Cheers,
D

--~--~-~--~~~---~--~~
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: Easy way to serialize objects

2008-11-07 Thread Russell Keith-Magee

On Sat, Nov 8, 2008 at 1:35 AM, Ivan Tarradellas <[EMAIL PROTECTED]> wrote:
>
> Hi all,
>
> With Django, what is the easy and best way to serialize/deserialize
> objects that are no Django objects?
>
> django.core.serializers only works with Django objects. But what
> happens if we have other object type?

The short answer is "you have to build the serializer yourself".
Django doesn't provide any mechanism for serializing arbitrary Python
objects.

The long answer depends on the serializer you want to use. Django's
model serialization module builds on a number of other libraries
(Python's builtin XML handling, simpleJSON, YAML, etc). These
libraries handle the logic for how to serialize python primitive types
(integer, list, etc). The Django serialization module describes how to
decompose a django model instance into a series of primitives.

If you want to serialize your own arbitrary object, you will need to
come up with a similar set of rules, and wrap it around the base
serialization libraries.

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?hl=en
-~--~~~~--~~--~--~---



Re: Using just one custom manager

2008-11-07 Thread John M

DR,

Now I have a new problem.  When I use this as a related_manager
(Report.objects.all()[0].task_set.accomplishments()) it returns all
the accomplishments.  I've even added the use_for_related_fields=True
in the manager.  The all() (default) call seems to work fine, but the
others done.

Any ideas?

Thanks

John

On Nov 7, 11:47 am, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
> On Nov 7, 7:13 pm, John M <[EMAIL PROTECTED]> wrote:
>
>
>
> > I wanted to get some feedback on how I'm using custom model managers.
>
> > I've put all my queries into one manager, each in a different method.
> > Is this the right way to go?
>
> > So for example:
>
> > CHOICES_TASK = (
> >                         ("NO", "None"),
> >                         ("GR", "Green"),
> >                         ("YL", "Yellow"),
> >                         ("RD", "Red"),
> >                 )
>
> > class TaskManager(models.Manager):
> >         use_for_related_fields = True
>
> >         # Task.objects.all()
> >         def get_query_set(self):
> >                 return super(TaskManager, self).get_query_set()
>
> >         # Task.milestones()
> >         def Milestones(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=True)
>
> >         def Accomplishments(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=False).filter(completed=True)
>
> >         def Nextsteps(self):
> >                 return super(TaskManager,
> > self).get_query_set().filter(milestone=False).filter(completed=False)
>
> > class Task(models.Model):
> >         report = models.ForeignKey(Report)
> >         name = models.CharField(max_length=50)
> >         started = models.BooleanField(default=False)
> >         status = models.CharField(max_length=20, choices=CHOICES_TASK,
> > default="NO")
> >         completed = models.BooleanField(default=False)
> >         duedate = models.DateField(blank=True, null=True)
> >         milestone = models.BooleanField(default=False)
>
> >         # Managers
> >         objects = TaskManager()
> >         milestones = TaskManager().Milestones
> >         accomplishments = TaskManager().Accomplishments
> >         nextsteps = TaskManager().Nextsteps
>
> >         def __unicode__(self):
> >                 return self.name
>
> There's nothing wrong with the general idea - that's how I do it
> myself, although the official docs say to use multiple managers and
> override get_query_set on each one. A couple of comments on your
> implementation though:
>
> 1. There's no point in defining a get_query_set model simply to pass
> to super. If you don't define it at all, it will just inherit from the
> parent class anyway, which is exactly the same as what happens in your
> version, so you may as well save two lines of code.
>
> 2. The convention in Python/Django is to have all lower case names for
> functions and methods - so it should be milestones, accomplishments,
> etc.
>
> 3. I don't think there's any point in defining all the extra manager
> attributes that you have. Leave objects as TaskManager, then you can
> do things like:
> Task.objects.milestones()
> Task.objects.accomplishments().filter(started=False)
> or whatever.
>
> --
> 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Fixtures erase data?

2008-11-07 Thread Russell Keith-Magee

On Sat, Nov 8, 2008 at 1:19 PM, Dana Woodman <[EMAIL PROTECTED]> wrote:
>
>> Having an option to add data in the way you describe isn't really a
>> good idea. If the syncdb behaviour was changed to add rather than
>> overwrite initial data, you would have a different (and IMHO much
>> worse) consequence - each time you run syncdb, you will end up with
>> another copy of the initial data. If you run syncdb 100 times, you
>> would end up with 100 copies of each fixture object.
>
> What I was envisioning was a solution that would check if the PK existed, if
> it did, it would pass, if not, it would add the rows. The intended use was
> to populate a database at first go with the needed data, but still be able
> to run syncdb without mucking things up. Guess I'll have to go the other
> route.

This idea is a little more sound, and is certainly in the realm of the
possible. I have some plans to improve fixture loading as a part of my
work on ticket #7052; Adding a --noclobber option would be a
reasonable extension to this work. I would suggest opening a ticket so
that the idea isn't forgotten. If you want to work on a patch, that
would be even better.

>> The purpose behind the initial data fixture is to provide *absolutely
>> essential* initial data that must exist in order for the database to
>> work - for example, the root node of a tree structure. If you have
>> other data that is required to bootstrap the system - especially if
>> that data is subject to change over the lifespan of the website -
>> define that data in a fixture other that initial_data (say
>> bootstrap_data), and manually load that fixture using loaddata. That
>> way the bootstrap data will only be loaded (and therefore overwritten)
>> when you explictly request a reload.
>
> Thanks, that is good advice, I will go ahead and do that. That will
> accomplish just about what I am looking for.
>
> Would it suffice to just rename the file/folder to
> bootstrap_data/bootstrap_data.json? Does Django look for a file called
> initial_data.json in a folder called initial_data, or does it just look for
> any file called initial_data.json?

Django looks for a file called initial_data.* in each of the
/fixture directories, plus each of the directories mentioned in
settings.FIXTURE_DIRS, plus the current working directory. The same
rules apply for any other fixture name. So - if you can currently load
initial_data.json, renaming it bootstrap.json is all you need to do.
Django's fixture loader doesn't use directory names as part of the
lookup scheme unless explicitly instructed to do so as part of the
settings.FIXTURE_DIRS option. Unless you particularly want to have
your fixtures in separate directories, there is no need to move
initial_data into a different directory.

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?hl=en
-~--~~~~--~~--~--~---



Re: Fixtures erase data?

2008-11-07 Thread Dana Woodman
> This idea is a little more sound, and is certainly in the realm of the
> possible. I have some plans to improve fixture loading as a part of my
> work on ticket #7052; Adding a --noclobber option would be a
> reasonable extension to this work. I would suggest opening a ticket so
> that the idea isn't forgotten. If you want to work on a patch, that
> would be even better.
>

Glad I'm not crazy :-)

I've submitted a ticket as you suggested here:
http://code.djangoproject.com/ticket/9549
I just hope my explanation wasn't too cryptic...

Django looks for a file called initial_data.* in each of the
> /fixture directories, plus each of the directories mentioned in
> settings.FIXTURE_DIRS, plus the current working directory. The same
> rules apply for any other fixture name. So - if you can currently load
> initial_data.json, renaming it bootstrap.json is all you need to do.
> Django's fixture loader doesn't use directory names as part of the
> lookup scheme unless explicitly instructed to do so as part of the
> settings.FIXTURE_DIRS option. Unless you particularly want to have
> your fixtures in separate directories, there is no need to move
> initial_data into a different directory.
>

Thats good to know, I will make that change.

Thanks for your time Russ.

Cheers,
D

--~--~-~--~~~---~--~~
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: Checkout and follow @djangopro on twitter (Aggregated Django News and Tips)

2008-11-07 Thread Sebastian

Awesome, following.

On Nov 7, 1:28 pm, djangopro <[EMAIL PROTECTED]> wrote:
> Hello everybody,
>
> We will be broadcasting professional django development news and tips
> via our twitterhttp://twitter.com/djangopro. Please follow and let
> everybody know. @djangopro is an effort to make the django community
> stronger. More to come.
>
> Thanks,
>
> @djangopro
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---