How to add a ManyToManyField at runtime?

2012-09-13 Thread James Pic
Hello everybody,

This is what I'm trying to do:

def test_basic_addition(self):
# create field
f = models.ManyToManyField(to=X, related_name='bar')
f.contribute_to_class(Y, 'x')

# create table
field = Y._meta.get_field_by_name('x')[0]
through = field.rel.through

fields = tuple((field.name, field) for field in
through._meta.fields)

db.create_table(through._meta.db_table, fields)
db.create_unique(through._meta.db_table,
['%s_id' % name for name, f in fields
if isinstance(f, models.ForeignKey)])


x = X(name='foo')
x.save()
y = Y()
y.save()
y.x.add(x)

print y.x.all()

The exception thrown is:


E
==
ERROR: test_basic_addition (test_app.tests.SimpleTest)
--
Traceback (most recent call last):
  File "/home/jpic/test_project/test_app/tests.py", line 41, in
test_basic_addition
print y.x.all()
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/manager.py",
line 116, in all
return self.get_query_set()
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py",
line 543, in get_query_set
return super(ManyRelatedManager,
self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/query.py",
line 621, in filter
return self._filter_or_exclude(False, *args, **kwargs)
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/query.py",
line 639, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py",
line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py",
line 1122, in add_filter
process_extras=process_extras)
  File
"/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py",
line 1316, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'bar' into field. Choices are: id,
name, users

--
Ran 1 test in 0.017s

FAILED (errors=1)
Destroying test database for alias 'default'...


`del X._meta._name_map` doesn't do the trick but i guess that's normal
because it's a reverse field that come from the other model, Y.

Anyway, you can checkout my [test_project][1] which isolates my problem,
and then run `./manage.py test test_app` in your working copy to reproduce
the issue.

  [1]: https://github.com/jpic/test_project/

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



Possible issue with admindoc templates

2011-12-19 Thread James Pic
Hello everybody,

Consider such a setup:

templates/base.html: loads jquery in {% block jquery %}
templates/admin/base_site.html: extends base.html, sets {% block
jquery %}{% endblock %} so that the parent template doesn't interfere
with django admin's loading of jquery

That worked pretty well until i installed admindoc: it doesn't load
jquery, but it extends admin/base.html. So no navigation for base.html
in admindoc views.

What's puzzling is that it would be a non issue if only admindoc
templates extended admindoc/base.html which in turn would extend
admin/base_site.html then i could just set {% block jquery %} to load
jquery for admindoc pages without interference.

What do you think ?

What's the best way to get jquery in my base, avoid double loading in
admin views, and get jquery in admindoc ?

Regards

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



Re: DJANGO_SETTINGS_MODULE problem

2011-11-15 Thread James Pic
On Tue, Nov 15, 2011 at 6:48 PM, Tim Sawyer  wrote:
> I've done this.
>
> You should be able to startup the test server with
> --settings=client_settings/foo.py and get all of settings.py and HELLO
> available to you.
>

FTR

>>> ./manage.py shell --settings=client_settings.foo

In [1]: from django.conf import settings

In [2]: settings.HELLO
Out[2]: True


> What's not working?
>

Failure is not working! Thanks

> Tim.
>

James

>> Hi all,
>>
>> I don't understand something about DJANGO_SETTINGS_MODULE. My
>> intention is to serve several websites from the same project
>> installation, by creating a subdir of website-specific settings.
>>
>> project_root/
>>   settings.py
>>   client_settings/
>>     __init__.py
>>     foo.py
>>     bar.py
>>     etc 
>>
>> So if foo.py contains::
>>
>>   from settings import *
>>   HELLO=True
>>
>> I'm expecting django.conf.settings.HELLO to be True from a shell spawned
>> with::
>>
>>   DJANGO_SETTINGS_MODULE='client_settings.foo' ./manage.py shell
>>
>> But the result is:
> echo $DJANGO_SETTINGS_MODULE
>> client_settings.foo
>>
> ./manage.py shell
>> In [1]: from django.conf import settings
>> In [2]: settings.HELLO
>> ---
>> AttributeError                            Traceback (most recent call
>> last)
>> /srv/art/art_crm/ in ()
>> > 1 settings.HELLO
>> /srv/art/art_env/lib/python2.7/site-packages/django/utils/functional.pyc
>> in __getattr__(self, name)
>>     275         if self._wrapped is None:
>>     276             self._setup()
>> --> 277         return getattr(self._wrapped, name)
>>     278
>>     279     def __setattr__(self, name, value):
>> AttributeError: 'Settings' object has no attribute 'HELLO'
>>
>> My manage.py should be the default:
>>
>> #!/usr/bin/env python
>> from django.core.management import execute_manager
>> import imp
>> try:
>>     imp.find_module('settings') # Assumed to be in the same directory.
>> except ImportError:
>>     import sys
>>     sys.stderr.write("Error: Can't find the file 'settings.py' in the
>> directory containing %r. It appears you've customized things.\nYou'll
>> have to run django-admin.py, passing it your settings module.\n" %
>> __file__)
>>     sys.exit(1)
>>
>> import settings
>>
>> if __name__ == "__main__":
>>     execute_manager(settings)
>>
>>
>> What am I doing wrong ?
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>>
>
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>



-- 
http://jamespic.info
Customer is king - Le client est roi - El cliente es rey.

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



DJANGO_SETTINGS_MODULE problem

2011-11-15 Thread James Pic
Hi all,

I don't understand something about DJANGO_SETTINGS_MODULE. My
intention is to serve several websites from the same project
installation, by creating a subdir of website-specific settings.

project_root/
  settings.py
  client_settings/
    __init__.py
    foo.py
    bar.py
    etc 

So if foo.py contains::

  from settings import *
  HELLO=True

I'm expecting django.conf.settings.HELLO to be True from a shell spawned with::

  DJANGO_SETTINGS_MODULE='client_settings.foo' ./manage.py shell

But the result is:
>>> echo $DJANGO_SETTINGS_MODULE
client_settings.foo

>>> ./manage.py shell
In [1]: from django.conf import settings
In [2]: settings.HELLO
---
AttributeError                            Traceback (most recent call last)
/srv/art/art_crm/ in ()
> 1 settings.HELLO
/srv/art/art_env/lib/python2.7/site-packages/django/utils/functional.pyc
in __getattr__(self, name)
    275         if self._wrapped is None:
    276             self._setup()
--> 277         return getattr(self._wrapped, name)
    278
    279     def __setattr__(self, name, value):
AttributeError: 'Settings' object has no attribute 'HELLO'

My manage.py should be the default:

#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the
directory containing %r. It appears you've customized things.\nYou'll
have to run django-admin.py, passing it your settings module.\n" %
__file__)
sys.exit(1)

import settings

if __name__ == "__main__":
execute_manager(settings)


What am I doing wrong ?

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



Re: Fill in form + user first time

2010-03-02 Thread James Pic
Hello everybody,

On Tue, Mar 2, 2010 at 11:14 PM, GoSantoni  wrote:
> Is it reasonable easy to achieve a form for users with in the end the
> opportunity to register or login? I'd like to let users who visit the
> site for the first time be able to choose a password and name. This
> needs to registered first and temporarily the data of the form itself
> needs to be saved and after succesful signup stored in the database.
> Or is that mission impossible ? :P
>

It's possible to do and to encapsulate in a loosly coupled application
("module"), which can be reused at will.

You should read the documentation about authentification and an app for that:

http://docs.djangoproject.com/en/1.1/topics/auth

Or install and hack one of the many existing apps shared by other kind users:

http://bitbucket.org/ubernostrum/django-registration/wiki/
http://github.com/policus/django-registration-facebook-backend
http://github.com/nathanborror/django-registration

Or start with any Pinax project, because they all include a configured
app which just works out of the box (ootb) and concentrate on what
makes your project different - which i must recommend if you're on
deadlines.

-- 
http://jamespic.com/contact
Customer is king - Le client est roi - El cliente es rei.

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



Re: SyncDB failure

2009-07-09 Thread James PIC

Hi,

Apparently, this was not triggered by class names, but by verbose_name length:

INSERT INTO "auth_permission" ("name", "content_type_id", "codename")
VALUES (%s, %s, %s) (u"Can change cat\xe9gorie d'immobilier
d'entreprise (LCP)", 44, u'change_categoriedelcp')
Traceback (most recent call last):
  File "./manage.py", line 11, in 
execute_manager(settings)
  File "//usr/lib/python2.5/site-packages/django/core/management/__init__.py",
line 340, in execute_manager
utility.execute()
  File "//usr/lib/python2.5/site-packages/django/core/management/__init__.py",
line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "//usr/lib/python2.5/site-packages/django/core/management/base.py",
line 192, in run_from_argv
self.execute(*args, **options.__dict__)
  File "//usr/lib/python2.5/site-packages/django/core/management/base.py",
line 219, in execute
output = self.handle(*args, **options)
  File "//usr/lib/python2.5/site-packages/django/core/management/base.py",
line 348, in handle
return self.handle_noargs(**options)
  File 
"//usr/lib/python2.5/site-packages/django/core/management/commands/syncdb.py",
line 101, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive)
  File "//usr/lib/python2.5/site-packages/django/core/management/sql.py",
line 205, in emit_post_sync_signal
interactive=interactive)
  File "//usr/lib/python2.5/site-packages/django/dispatch/dispatcher.py",
line 148, in send
response = receiver(signal=self, sender=sender, **named)
  File 
"//usr/lib/python2.5/site-packages/django/contrib/auth/management/__init__.py",
line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
  File "//usr/lib/python2.5/site-packages/django/db/models/manager.py",
line 96, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
  File "//usr/lib/python2.5/site-packages/django/db/models/query.py",
line 339, in get_or_create
obj.save(force_insert=True)
  File "//usr/lib/python2.5/site-packages/django/db/models/base.py",
line 311, in save
self.save_base(force_insert=force_insert, force_update=force_update)
  File "//usr/lib/python2.5/site-packages/django/db/models/base.py",
line 383, in save_base
result = manager._insert(values, return_id=update_pk)
  File "//usr/lib/python2.5/site-packages/django/db/models/manager.py",
line 138, in _insert
return insert_query(self.model, values, **kwargs)
  File "//usr/lib/python2.5/site-packages/django/db/models/query.py",
line 894, in insert_query
return query.execute_sql(return_id)
  File "//usr/lib/python2.5/site-packages/django/db/models/sql/subqueries.py",
line 309, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
  File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py",
line 1734, in execute_sql
cursor.execute(sql, params)
  File "/usr/lib/python2.5/site-packages/django/db/backends/util.py",
line 20, in execute
return self.cursor.execute(sql, params) # calls print sql, params
as you can see
psycopg2.DataError: value too long for type character varying(50)

This should be documented and/or an Exception should be thrown.

Should i file a bug report?

Regards, James.

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



Re: Overloading ModelFormMetaclass, to implement a custom __init__() method and use ModelForm in a factory

2009-01-13 Thread James PIC

On Tue, Jan 13, 2009 at 11:57 AM, James PIC <james...@gmail.com> wrote:
> That's what i'm actually trying to do:
>
> # todo : get a more descriptive FC prefix than "jpic"
> class JpicModelFormMetaclass(ModelFormMetaclass):
>"""
>Inherit from this, then use this new keyword argument
>'jpic_field_options' with a dict of dicts such as:
>{
>'field_name_that_is_m2m': {
>'queryset': aqueryset,
>},
>'field_name_that_is_fk': {
>'queryset': anotherqueryset,
>},
>}
>
>This solves the problem of using a queryset made in the view
>as choices for a M2M/FK field ...
>"""
>def __init__(self, *args, **kwargs):
>jpic_field_options = False
>if 'jpic_field_options' in kwargs.keys():
>jpic_field_options = kwargs.pop('jpic_field_options')
>super(JpicModelFormMetaclass, self).__init__(*args, **kwargs)
>if not jpic_field_options:
>return
>for field, args in jpic_field_options.items():
>if field not in self.fields:
>continue
>for arg, value in args.items():
>setattr(self.fields[field], arg, value)
>
> class JpicModelForm(ModelForm):
>__metaclass__ = JpicModelFormMetaclass
>
> This is how i tryed to copy the factory method to use my metaclass:
>
>def get_form_class(self):
># HACK: we should be able to construct a ModelForm without creating
># and passing in a temporary inner class
>class Meta:
>pass
>setattr(Meta, 'model', self.model_class)
>setattr(Meta, 'fields', self.get_fields())
>if Group.objects.get(name='Consultants') in
> self.request.user.groups.all():
>class_name = self.model_class_name + 'ConsultantForm'
>else:
>class_name = self.model_class_name + 'ClientForm'
>return JpicModelFormMetaclass(class_name.encode(),
> (JpicModelForm,), {'Meta': Meta,
>'formfield_callback': lambda
> f: f.formfield()})
>
> This error is thrown:
>
> Traceback:
> File "/home/python/libs/django/core/handlers/base.py" in get_response
>  86. response = callback(request, *callback_args,
> **callback_kwargs)
> File "/home/jpic/sites/devangels/django_tickets/views.py" in root
>  54. return view_class().root(request, url, action, dest_class)
> File "/home/jpic/sites/devangels/django_tickets/views.py" in root
>  210. self.formobj = self.get_form()
> File "/home/jpic/sites/devangels/django_tickets/views.py" in get_form
>  97. form = form_class(instance=self.model,
> jpic_field_options=options)
>
> Exception Type: TypeError at /component/1/ticket/create/
> Exception Value: __init__() got an unexpected keyword argument
> 'jpic_field_options'
>
> Please don't mind the possible problems of my 'formfield_callback'
> argument, i'll fix that ...

Apparently, i should have used the snippet directly (no
JpicModelFormMetaclass) and this factory code:
return ModelFormMetaclass(class_name.encode(), (JpicModelForm,), {'Meta': Meta,
 'formfield_callback': lambda f: f.formfield()})

As simple as that ... Case closed, sorry for posting before reading:
http://www.ibm.com/developerworks/linux/library/l-pymeta.html

Regards, James.

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



Overloading ModelFormMetaclass, to implement a custom __init__() method and use ModelForm in a factory

2009-01-13 Thread James PIC

Hello everybody,

This snippet is working fine, i used this instead of adding custom
arguments when overloading each of my ModelForm's constructore to keep
the same __init__() signature.
http://www.djangosnippets.org/snippets/1272/

Currently refactoring, it makes sense to use a factory in my case.
I tryed to copy the pattern of forms.model.modelform_factory, but now
it seems that my __init__() method is not overloading ModelForm
anymore

Recall the code of forms.model.modelform_factory:

/trunk/django/forms/models.py
326 def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
327formfield_callback=lambda f: f.formfield()):
328 # HACK: we should be able to construct a ModelForm without creating
329 # and passing in a temporary inner class
330 class Meta:
331 pass
332 setattr(Meta, 'model', model)
333 setattr(Meta, 'fields', fields)
334 setattr(Meta, 'exclude', exclude)
335 class_name = model.__name__ + 'Form'
336 return ModelFormMetaclass(class_name, (form,), {'Meta': Meta,
337   'formfield_callback': formfield_callback})

That's what i'm actually trying to do:

# todo : get a more descriptive FC prefix than "jpic"
class JpicModelFormMetaclass(ModelFormMetaclass):
"""
Inherit from this, then use this new keyword argument
'jpic_field_options' with a dict of dicts such as:
{
'field_name_that_is_m2m': {
'queryset': aqueryset,
},
'field_name_that_is_fk': {
'queryset': anotherqueryset,
},
}

This solves the problem of using a queryset made in the view
as choices for a M2M/FK field ...
"""
def __init__(self, *args, **kwargs):
jpic_field_options = False
if 'jpic_field_options' in kwargs.keys():
jpic_field_options = kwargs.pop('jpic_field_options')
super(JpicModelFormMetaclass, self).__init__(*args, **kwargs)
if not jpic_field_options:
return
for field, args in jpic_field_options.items():
if field not in self.fields:
continue
for arg, value in args.items():
setattr(self.fields[field], arg, value)

class JpicModelForm(ModelForm):
__metaclass__ = JpicModelFormMetaclass

This is how i tryed to copy the factory method to use my metaclass:

def get_form_class(self):
# HACK: we should be able to construct a ModelForm without creating
# and passing in a temporary inner class
class Meta:
pass
setattr(Meta, 'model', self.model_class)
setattr(Meta, 'fields', self.get_fields())
if Group.objects.get(name='Consultants') in
self.request.user.groups.all():
class_name = self.model_class_name + 'ConsultantForm'
else:
class_name = self.model_class_name + 'ClientForm'
return JpicModelFormMetaclass(class_name.encode(),
(JpicModelForm,), {'Meta': Meta,
'formfield_callback': lambda
f: f.formfield()})

This error is thrown:

Traceback:
File "/home/python/libs/django/core/handlers/base.py" in get_response
  86. response = callback(request, *callback_args,
**callback_kwargs)
File "/home/jpic/sites/devangels/django_tickets/views.py" in root
  54. return view_class().root(request, url, action, dest_class)
File "/home/jpic/sites/devangels/django_tickets/views.py" in root
  210. self.formobj = self.get_form()
File "/home/jpic/sites/devangels/django_tickets/views.py" in get_form
  97. form = form_class(instance=self.model,
jpic_field_options=options)

Exception Type: TypeError at /component/1/ticket/create/
Exception Value: __init__() got an unexpected keyword argument
'jpic_field_options'

Please don't mind the possible problems of my 'formfield_callback'
argument, i'll fix that ...

I asked on IRC and failed to fix it. Any tip will be appreciated, note
that my understanding of metaclasses is currently limited so that's
why i tryed to "just copy and hack".
There might be a better way.

Regards, James.

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



Fwd: Optional fields in admin page

2008-12-21 Thread James PIC

Errata, this email has correct sources, sorry for the pollution.

On Sun, Dec 21, 2008 at 4:46 PM, Mirat Can Bayrak
 wrote:
>
> hi, i have a state selection which has options "exists", "not exists" and 
> "redirected" when it is selected as exists i want to show some more fields, 
> but on other selections i dont want him to show them. can i do that it django?

AFAIK not OOTB. I hope for you that someone is going to post a more
comprehensive reply than this one.

It's hopefully pretty easy to "predict" how django will generate it's
input field, label and fieldset ids in the HTML result. Use your
favorite javascript framework to deal with it:
- attach an event onChange on a field,
- show/hide fields you want when the field's value match something you expected.

I had to create some javascript function to help me (models with
hundred of fields, dozens of conditions), drawbacks are: no
documentation, requires jquery. Reading it might help making your
application specific functions development /slightly/ faster.

function show_field(name)
{
   id = 'id_' + name
   $('.' + name).show();
   $('#' + id).show();
   $('label[for=' + id + ']').show();
}

function hide_field(name)
{
   id = 'id_' + name
   $('.' + name).hide();
   $('#' + id).hide();
   $('label[for=' + id + ']').hide();
}
// geodjango
function show_map(name)
{
   show_field(name);
   $('#' + id).hide();
   $('#id_' + name + '_admin_map').show();
}

function hide_map(name)
{
   $('#id_' + name + '_admin_map').hide();
   hide_field(name);
}

Because of the lack of documentation, this is an example usage which
you'll unfortunnately have to reverse engineer, i've tryed to cut out
everything you don't need and "unfactorized it" to make it "easier" to
understand:

foo_specific_fields = new Array(
   'droits',
   // [...],
   // that's actually a list of field name as they are in your models sources
   'loi_defisc',
);

$(document).ready(function() {
   $('#id_foo_bar').change(function() {
   if ($(this).val() == "Foo")
   {
   for (i=0; i

Re: Optional fields in admin page

2008-12-21 Thread James PIC

On Sun, Dec 21, 2008 at 4:46 PM, Mirat Can Bayrak
 wrote:
>
> hi, i have a state selection which has options "exists", "not exists" and 
> "redirected" when it is selected as exists i want to show some more fields, 
> but on other selections i dont want him to show them. can i do that it django?

AFAIK not OOTB. I hope for you that someone is going to post a more
comprehensive reply than this one.

It's hopefully pretty easy to "predict" how django will generate it's
input field, label and fieldset ids in the HTML result. Use your
favorite javascript framework to deal with it:
- attach an event onChange on a field,
- show/hide fields you want when the field's value match something you expected.

I had to create some javascript function to help me (models with
hundred of fields, dozens of conditions), drawbacks are: no
documentation, requires jquery. Reading it might help making your
application specific functions development /slightly/ faster.

function show_field(name)
{
id = 'id_' + name
$('.' + name).show();
$('#' + id).show();
$('label[for=' + id + ']').show();
}

function hide_field(name)
{
id = 'id_' + name
$('.' + name).hide();
$('#' + id).hide();
$('label[for=' + id + ']').hide();
}
// geodjango
function show_map(name)
{
show_field(name);
$('#' + id).hide();
$('#id_' + name + '_admin_map').show();
}

function hide_map(name)
{
$('#id_' + name + '_admin_map').hide();
hide_field(name);
}

Because of the lack of documentation, this is an example usage which
you'll unfortunnately have to reverse engineer, i've tryed to cut out
everything you don't need and "unfactorized it" to make it "easier" to
understand:

residence_specific_fields = new Array(
'departement',
'cp',
'ville',
'addresse1',
'addresse2',
'secteur',
'quartier',
'ville_diffusion'
);

function show_residence_specific()
{
for (i=0; i

Re: Restricting add in the admin

2008-12-20 Thread James PIC

On Sat, Dec 20, 2008 at 3:17 PM, Peter  wrote:
>
>
>
> On Dec 20, 1:03 pm, felix  wrote:
>> just a thought:
>>
>> you might consider allowing multiple front page objects and having a way to
>> select the current one.
>> this could come in handy to switch what is currently the front page (or to
>> audition the new front page).
>>
>
> Yes - perhaps add a Boolean field (not shown in the admin)
> 'is_active'

Very relevant, don't forgot to overload the save method to set
other is_active to 0!

Regards, James.

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



Re: SyncDB failure

2008-12-20 Thread James PIC

>> Just for kidding:
>> class Lot(Mandat, Bien, PourLocation, PourVente, LotAddresse,
>>  AvecEquipementsAnnexes, Textes, Immeuble):
>> It was that, or models with thousands of similar fields, high WTF/hour :)
>
> just be thankful you aren't coding in german :)

It's very business-specific, i ignore 90% of the terms in english.
Also, the program is country-legislation specific.
But as you can see, not using acronyms is part of the coding standart.

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



Re: Restricting add in the admin

2008-12-19 Thread James PIC

On 12/19/08, Peter  wrote:
>
>
>  >
>  > You could make such a check and deny the saving of a new FrontPage
>  > object by overloading the save() method of class FrontPage.
>  > Source in trunk: django/db/models/base.py.
>  >
>  > Regards, James.
>
>
> Thanks James.
>
>  Yes - I see that would work - but it involves coding and I was looking
>  for a more 'declarative'
>  way.

Why?
The really proper way to do that is to store the sole FrontPage model
in a json file, the file-system is better suited than a RDBMS to store
one single instance of a single structure IMHO.

>  I'll give the user permission to change a FrontPage instance but not
>  delete or add one. The real admin user
>  will have just to avoid adding / deleting but this user ain't used
>  (much). In the FrontPage view I can check
>  that the original view is being used (perhaps by looking for pk==1 or
>  something).   The main thing is that this
>  switches off the admin template buttons 'x delete' '+add' etc.

You might also overload default admin templates for FrontPage, but
permissions allow security.

>  What I was looking for was a global permission that could be set on a
>  model when it was defined which set
>  default permissions for 'staff' on the model (or even for superuser)
>  on that model.

Why not just create another group?

Don't forget to save your permissions in
yourapp/data/initial_data.json with the help of the dumpdata
management command, since it's consistence critical.

Regards, James.

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



Re: Restricting add in the admin

2008-12-19 Thread James PIC

On 12/19/08, Peter  wrote:
>
>  I have two models in my app - one is standard in that it allows
>  changing existing records/instances and adding new ones. But the other
>  - actually a FrontPage model - does not permit adding another
>  instance. There are ways to do this but I am wondering if there is a
>  standard way as it seems a common use-case. I am still pretty new to
>  Django so excuse if this is a FAQ.

You could make such a check and deny the saving of a new FrontPage
object by overloading the save() method of class FrontPage.
Source in trunk: django/db/models/base.py.

Regards, James.

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



Re: SyncDB failure

2008-12-19 Thread James PIC

On 12/17/08, Russell Keith-Magee <freakboy3...@gmail.com> wrote:
>
>  On Wed, Dec 17, 2008 at 9:30 PM, James PIC <james...@gmail.com> wrote:
>  >
>  > Is it worth reporting the bug?
>
>  However, at a guess, I'm going to say that the problem has been caused
>  by your choice of model names. You appear to have named one of your
>  models something like TypedEInformationComplementaireContact. This is
>  a pretty long class name, and it is overflowing a column somewhere
>  that is using the class name as a starting point.
>  Your proposed fix (increasing the size of the columns) is really just
>  deferring the problem.

(I did not actually propose it, but used it to describe the problem).

>  No matter what maximum size we pick, someone
>  will choose a model name that will overflow it. I would have thought a
>  50 character limit was plenty, but obviously I was wrong. Your
>  solution also suffers from the problem of backwards compatibility -
>  there is a lot of existing code out there that relies on the existing
>  size definition.
>
>  A better solution would be to come up with a name munging scheme that
>  guaranteed to give unique permission names that will always fit into
>  the available space. 50 characters is plenty to establish a unique
>  name; we already perform a similar munging with the names for database
>  constraints.

That would be much smarter indeed!

>  Of course, the simplest solution is for you to pick shorter class
>  names, and for us to document the limitation.

I can change "Information" to "Info", but you have the point that it doesn't
 fix the problem ... I just wanted to point it out.

>  This solution has the
>  additional benefit of enforcing good programming practice. Having
>  descriptive class names is good, but I for one wouldn't derive much
>  joy from using an API that had class names that spanned 50% of the
>  width of a 80 character terminal :-)

Just for kidding:
class Lot(Mandat, Bien, PourLocation, PourVente, LotAddresse,
  AvecEquipementsAnnexes, Textes, Immeuble):
It was that, or models with thousands of similar fields, high WTF/hour :)

Regards, James.

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



SyncDB failure

2008-12-17 Thread James PIC

Hello everybody,

Description:

margaux mmm # ./manage.py syncdb
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table immo_zipcode
Creating table immo_zone
Creating table immo_configurationdeterrain
Creating table immo_formedeterrain
Creating table immo_terraintype
Creating table immo_secteur
Creating table immo_ville
Creating table immo_quartier
Creating table immo_departement
Creating table immo_pubpresse
Creating table immo_pubinternet
Creating table immo_categoriedelot
Creating table immo_categoriedeterrain
Creating table immo_categoriedehabitable
Creating table immo_categoriedelcp
Creating table immo_souscategoriedehabitable
Creating table immo_souscategoriedelcp
Creating table immo_genredebien
Creating table immo_loidefiscalisation
Creating table immo_equipementprivatif
Creating table immo_equipementcollectif
Creating table immo_annexe
Creating table immo_typedemandat
Creating table immo_typedebail
Creating table immo_activite
Creating table immo_activitepourlcp
Creating table immo_statutdebien
Creating table immo_typedecode
Creating table immo_code
Creating table immo_typedenvironnement
Creating table immo_environnement
Creating table immo_typedemeuble
Creating table immo_meuble
Creating table immo_typedepiece
Creating table immo_piece
Creating table immo_typedeinformationcomplementaire
Creating table immo_informationcomplementaire
Creating table immo_typedepiecelcp
Creating table immo_piecelcp
Creating table immo_typedeprestation
Creating table immo_mandat
Creating table immo_lotaddresse
Creating table immo_textes
Creating table immo_categoriededocument
Creating table immo_document
Creating table immo_imagepublique
Creating table immo_bien
Creating table immo_pourvente
Creating table immo_pourlocation
Creating table immo_terrain
Creating table immo_descriptifdeimmeuble
Creating table immo_lot
Creating table immo_lcp
Creating table immo_typetransactionlcp
Creating table immo_userprofile
Creating table immo_typedeinformationcomplementairecontact
Creating table immo_informationcomplementairecontact
Creating table immo_typedeclient
Creating table immo_civilite
Creating table immo_contactclassification
Creating table immo_location
Creating table immo_lotissement
Creating table immo_residence
Creating table immo_descriptifderesidence
Creating table immo_prestationderesidence
Creating table registration_registrationprofile
Creating table django_project_version
Creating table django_evolution

You just installed Django's auth system, which means you don't have
any superusers defined.
Would you like to create one now? (yes/no): no
Installing baseline version
Traceback (most recent call last):
  File "./manage.py", line 11, in 
execute_manager(settings)
  File "/home/mmm/sites/mmm/__init__.py", line 340, in execute_manager

  File "/home/mmm/sites/mmm/__init__.py", line 295, in execute

  File "/home/mmm/django/core/management/base.py", line 195, in run_from_argv
  File "/home/mmm/django/core/management/base.py", line 222, in execute
  File "/home/mmm/django/core/management/base.py", line 351, in handle
  File "/home/mmm/lib/django/core/management/commands/syncdb.py", line
98, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive)
  File "/home/mmm/lib/django/core/management/sql.py", line 205, in
emit_post_sync_signal
interactive=interactive)
  File "/home/mmm/django/dispatch/dispatcher.py", line 148, in send
  File "/home/mmm/lib/django/contrib/auth/management/__init__.py",
line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
  File "/home/mmm/django/db/models/manager.py", line 96, in get_or_create
  File "/home/mmm/django/db/models/query.py", line 339, in get_or_create
  File "/home/mmm/django/db/models/base.py", line 328, in save
  File "/home/mmm/django/db/models/base.py", line 400, in save_base
  File "/home/mmm/django/db/models/manager.py", line 138, in _insert
  File "/home/mmm/django/db/models/query.py", line 894, in insert_query
  File "/home/mmm/django/db/models/sql/subqueries.py", line 309, in execute_sql
  File "/home/mmm/django/db/models/sql/query.py", line 1756, in execute_sql
  File "/home/mmm/django/db/backends/util.py", line 19, in execute
psycopg2.ProgrammingError: value too long for type character varying(50)

Apparently, this patch fixed it:
Index: ../../lib/django/contrib/auth/models.py
===
--- ../../lib/django/contrib/auth/models.py (revision 9637)
+++ ../../lib/django/contrib/auth/models.py (working copy)
@@ -60,9 +60,9 @@

 Three basic permissions -- add, change and delete -- are
automatically created for each Django model.
 """
-name = models.CharField(_('name'), max_length=50)
+name = models.CharField(_('name'), max_length=100)
 

Re: Model Meta verbose_name setter

2008-07-22 Thread James PIC

Hi Marty,

On Mon, Jul 21, 2008 at 9:18 PM, Marty Alchin <[EMAIL PROTECTED]> wrote:
>
> On Mon, Jul 21, 2008 at 2:55 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> This is why i need to code a little mechanism to set the verbose_name
>> property of Meta subclass of Model.
>> I can't get it to work!
>
> All of the options you're suggesting would work just fine if only Meta
> ever got instantiated into an object. Alas, it doesn't. Django doesn't
> really use it as a means to create an object, but more as a way to
> create a separate namespace for all the various options you can set,
> without getting in the way of model fields and methods.

Thanks for the tip!

> Unfortunately, from your examples, I can't really figure out what
> problem you're trying to solve, so I don't know what to recommend for
> you. All I can say is that none of your attempts will work without
> Meta being instantiated, which Django doesn't (and likely won't) do.

I'm trying to use the value of a field of the model for Meta verbose_name.

James

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