Re: Do fixtures in tests overwrite default model field values?

2010-02-25 Thread Russell Keith-Magee
On Thu, Feb 25, 2010 at 8:43 PM, filias  wrote:
> Hi,
>
> I am running several tests and created a fixture with the test data.
> I have one model with a custom field which has a default value.
>
> I thought my test fixture should overwrite this field for some of the
> objects but when run the test the value for the field is always the
> default value.
>
> Is this the normal behavior or do I have some bug in my custom field?

Sounds like a bug in your custom field. As long as the fixture
provides data, it will attempt to overwrite any field-based default.

Yours,
Russ Magee %-)

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



Re: Multiple DB in django 1.2

2010-02-25 Thread Russell Keith-Magee
On Fri, Feb 26, 2010 at 2:08 AM, Roach, Marshall (MROACH)
 wrote:
> Hi, I was at pycon last week and heard about the db routers in django 1.2
> and I have the alpha version of django running for a project I’m running and
> trying to figure out how to do the following.
>
> I have 2 databases on different machines and if its one of the models I want
> the database to write everything to both machines.

Writing a single object to two different databases wasn't one of the
design goals of multi-db. I can't think of an easy way to do this with
a router.

The easiest way I can think of would be to overwrite the save() method
on a model to do something like the following:

class MyModel(models.Model):
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **dict(kwargs, using='database1'))
return super(MyModel, self).save(*args, **dict(kwargs,
using='database2'))

That is, intercept the save to force a model save to do 2 saves, one
on each database you want to target.

Yours,
Russ Magee %-)

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



Re: Admin Site Performance Problem

2010-02-25 Thread Matt Schinckel
On Feb 26, 11:45 am, sixpackistan  wrote:
> Anybody have any ideas on this?
> I am running django 1.1.1 using mod_python on apache 2.2.
> We have a large database of items (defined in the model as "item")
> that are searchable by serial number (which is indexed in the
> database).  On the public site, one can enter in a serial number and
> the appropriate item is displayed for edit quite fast.  On the admin
> site, if one selects an item from the list display it takes almost a
> minute for the same item to come up for edit.  Does the django admin
> site use a different API or methodology for retrieving data?  Any
> ideas why the admin site would be so much slower when it is displaying
> the same data as the public site?

If you are displaying inlines, that also have a Foreign Key reference
to another object, that is almost certainly the reason.

Try having a look at the django-debug-toolbar, or the queries
generated in your DBMS (or try devserver) to find out where the
slowdown is.

You can use raw_id_fields in the admin to improve performance
significantly.

Matt.

-- 
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: RV: photos sexy

2010-02-25 Thread Nicolas Couture
This is probably the funniest post I've seen on a technical mailing list
this year.

2010/2/26 Gisela Cartaya 

>
>
>
>
> *De:* Raven Riley [mailto:ravenriley2...@yahoo.fr]
> *Enviado el:* Thursday, February 25, 2010 4:17 PM
> *Para:* gcart...@infomed.sld.cu
> *Asunto:* Re : photos sexy
>
>
>
>  sache que si je t'envoie c'est photo c'est que j'ai confiance en toi meme
> si je ne te connais pas assez mais je pense que tu sauras en faire bonne
> usage.
>
>
>
> [image: ]
>
>
>
> [image: PML]
>
>
> [image: LMP]
>
>
>
> [image: FFGGHHH]
>
>
>
> [image: GHFGDFJGHDF]
>
>
>
> ok c'est tout se que je peux faire pour toi et j'espere quel te plairons.
>
> Et n'oublie pas prends en soins.
>
> bisou carolle
>
>
>  --
>
> *De :* "gcart...@infomed.sld.cu" 
> *À :* ravenriley2...@yahoo.fr
> *Envoyé le :* Dim 21 Février 2010, 2 h 19 min 55 s
> *Objet :* photos
>
> Photos
>
> bisou
> Ariel
>
>
>
> --
> Infomed - Red de Salud de Cuba
> http://www.sld.cu/
>
>
> --
>
> Este mensaje le ha llegado mediante el servicio de correo electronico que
> ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema
> Nacional de Salud. La persona que envia este correo asume el compromiso de
> usar el servicio a tales fines y cumplir con las regulaciones establecidas
>
> Infomed: http://www.sld.cu/
>
>
>
>
> __ Information from ESET NOD32 Antivirus, version of virus
> signature database 4220 (20090706) __
>
> The message was checked by ESET NOD32 Antivirus.
>
> http://www.eset.com
>
>
> __ Information from ESET NOD32 Antivirus, version of virus
> signature database 4220 (20090706) __
>
> The message was checked by ESET NOD32 Antivirus.
>
> http://www.eset.com
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



RV: photos

2010-02-25 Thread Gisela Cartaya
 

 

De: Raven Riley [mailto:ravenriley2...@yahoo.fr] 
Enviado el: Thursday, February 25, 2010 4:11 PM
Para: gcart...@infomed.sld.cu
Asunto: Re : photos

 

 HUY  

 


 POUIT  

 

 GYH  

 

 BHHJ  

 

je t'enverais d'autre plus sexy si tu veux pour que tu ai un avans gout de
moi au cas ou sa marche entre nous et sache que si je t'envoie mais photo
c'est parce que je n'es pas de cam et je prefere que tu puisse au minimun
avoir une image de moi a tes coter.

 

bisou carolle

 

  _  

De : "gcart...@infomed.sld.cu" 
À : ravenriley2...@yahoo.fr
Envoyé le : Dim 21 Février 2010, 2 h 19 min 55 s
Objet : photos

Photos

bisou
Ariel



--
Infomed - Red de Salud de Cuba
http://www.sld.cu/


--

Este mensaje le ha llegado mediante el servicio de correo electronico que
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema
Nacional de Salud. La persona que envia este correo asume el compromiso de
usar el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/




__ Information from ESET NOD32 Antivirus, version of virus signature
database 4220 (20090706) __

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com



--

Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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



RV: photos

2010-02-25 Thread Gisela Cartaya
 

 

De: Raven Riley [mailto:ravenriley2...@yahoo.fr] 
Enviado el: Thursday, February 25, 2010 4:11 PM
Para: gcart...@infomed.sld.cu
Asunto: Re : photos

 

Imagen quitada por el remitente. HUY

 


Imagen quitada por el remitente. POUIT

 

Imagen quitada por el remitente. GYH

 

Imagen quitada por el remitente. BHHJ

 

je t'enverais d'autre plus sexy si tu veux pour que tu ai un avans gout de
moi au cas ou sa marche entre nous et sache que si je t'envoie mais photo
c'est parce que je n'es pas de cam et je prefere que tu puisse au minimun
avoir une image de moi a tes coter.

 

bisou carolle

 

  _  

De : "gcart...@infomed.sld.cu" 
À : ravenriley2...@yahoo.fr
Envoyé le : Dim 21 Février 2010, 2 h 19 min 55 s
Objet : photos

Photos

bisou
Ariel



--
Infomed - Red de Salud de Cuba
http://www.sld.cu/


--

Este mensaje le ha llegado mediante el servicio de correo electronico que
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema
Nacional de Salud. La persona que envia este correo asume el compromiso de
usar el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/




__ Information from ESET NOD32 Antivirus, version of virus signature
database 4220 (20090706) __

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com



--

Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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

<<~WRD000.jpg>>

Weird transaction problem with postgresql

2010-02-25 Thread Julien Phalip
Hi,

After looking through this mailing list I've seen many threads
discussing issues relating to transaction issues with postgresql, but
none like the one I'm facing. If I've missed any relevant thread,
please let me know.

I've got a Profile model which is instantiated each time a new user is
created:

from models import Profile

def create_profile_for_user(sender, instance, signal, created,
*args, **kwargs):
if kwargs['raw'] == False: # Test if we're not loading
fixtures
if created:
profile = Profile(user=instance)
profile.save()

signals.post_save.connect(create_profile_for_user, sender=User)

But when I try to create a new user from the admin, it crashes with
the following traceback:

File "/home/myuser/.virtualenvs/mysite/src/django/django/core/handlers/
base.py" in get_response
  101. response = callback(request,
*callback_args, **callback_kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/contrib/admin/
options.py" in wrapper
  240. return self.admin_site.admin_view(view)(*args,
**kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in _wrapped_view
  68. response = view_func(request, *args,
**kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/views/
decorators/cache.py" in _wrapped_view_func
  69. response = view_func(request, *args, **kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/contrib/admin/
sites.py" in inner
  194. return view(request, *args, **kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in _wrapper
  21. return decorator(bound_func)(*args, **kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in _wrapped_view
  68. response = view_func(request, *args,
**kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in bound_func
  17. return func(self, *args2, **kwargs2)
File "/home/myuser/.virtualenvs/mysite/src/django/django/db/
transaction.py" in _commit_on_success
  295. res = func(*args, **kw)
File "/home/myuser/.virtualenvs/mysite/src/django/django/contrib/auth/
admin.py" in add_view
  104. return super(UserAdmin, self).add_view(request,
form_url, extra_context)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in _wrapper
  21. return decorator(bound_func)(*args, **kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in _wrapped_view
  68. response = view_func(request, *args,
**kwargs)
File "/home/myuser/.virtualenvs/mysite/src/django/django/utils/
decorators.py" in bound_func
  17. return func(self, *args2, **kwargs2)
File "/home/myuser/.virtualenvs/mysite/src/django/django/db/
transaction.py" in _commit_on_success
  306. leave_transaction_management(using=using)
File "/home/myuser/.virtualenvs/mysite/src/django/django/db/
transaction.py" in leave_transaction_management
  87. raise TransactionManagementError("Transaction managed
block ended with pending COMMIT/ROLLBACK")

Exception Type: TransactionManagementError at /admin/auth/user/add/
Exception Value: Transaction managed block ended with pending COMMIT/
ROLLBACK


My database settings are as follows:

DATABASES = {
'default': {
'NAME': 'mydb',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'myuser',
'PASSWORD': 'secret',
}
}

I've also tried to add 'OPTIONS': { "autocommit": True, } (following
the recommendation in 
http://docs.djangoproject.com/en/dev/ref/databases/#autocommit-mode)
but I still get the same error.

Disconnecting the create_profile_for_user signal makes it work (but
obviously no Profile object is instantiated).

The weird thing is that everything works fine with Sqlite. So it's
typically a postgresql issue. I'm using psql version 8.3.1 and a
recent checkout of Django trunk.

Any help would be very welcome, as I'm really baffled here.

Many thanks!

Regards,

Julien

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



Re: Admin Site Performance Problem

2010-02-25 Thread Timothy Kinney
If it takes 60 seconds for a single item to come up on the admin site,
something is seriously wrong. You configure which items show up on the admin
site and if you configure it a certain way it may have many, many queries to
make.

If you only have one table, your query should be pretty fast.

How many items are in the database and how are you calling the item?

-Tim


On Thu, Feb 25, 2010 at 7:45 PM, sixpackistan  wrote:

> Anybody have any ideas on this?
> I am running django 1.1.1 using mod_python on apache 2.2.
> We have a large database of items (defined in the model as "item")
> that are searchable by serial number (which is indexed in the
> database).  On the public site, one can enter in a serial number and
> the appropriate item is displayed for edit quite fast.  On the admin
> site, if one selects an item from the list display it takes almost a
> minute for the same item to come up for edit.  Does the django admin
> site use a different API or methodology for retrieving data?  Any
> ideas why the admin site would be so much slower when it is displaying
> the same data as the public site?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Admin Site Performance Problem

2010-02-25 Thread sixpackistan
Anybody have any ideas on this?
I am running django 1.1.1 using mod_python on apache 2.2.
We have a large database of items (defined in the model as "item")
that are searchable by serial number (which is indexed in the
database).  On the public site, one can enter in a serial number and
the appropriate item is displayed for edit quite fast.  On the admin
site, if one selects an item from the list display it takes almost a
minute for the same item to come up for edit.  Does the django admin
site use a different API or methodology for retrieving data?  Any
ideas why the admin site would be so much slower when it is displaying
the same data as the public site?

-- 
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: Hierarchical data containing different models

2010-02-25 Thread Marco Rogers
Couple of things.

bruno, your save example should maybe look call the superclass save
first.  Otherwise parent may not have been set yet.

     def save(self, *args, **kw):
         super(Node, self).save(*args, **kw)
         if self.parent and type(self.parent) != Group:
             raise ValueError("only Group nodes can be parents")


Also, the issue I see with this is how do you know find out which type
of Node you have so you can query the right model?  For instance when
you query Node.objects.filter(parent_id=parent_id) you'll get a list
of Node objects.  But they will not have any of the properties there
were put on the Group and Item subclasses.  Because the Node class
doesn't know about them.  This is a problem I've had with django for a
while now and i would love to see a solution that addresses it.

:Marco


On Feb 24, 5:01 pm, bruno desthuilliers
 wrote:
> On 24 fév, 18:08, Peter Reimer  wrote:
>
> > Hi folks,
>
> > I'm looking for a solution/tip for the following problem: I need to
> > store hierarchical data, but, with two different kinds of objects
> > (groups and items).
>
> That's something the relational model (at least in it's SQL
> implementation) is not very good at.
>
> > I googled around and found the often suggested
> > mptt package.
>
> The mptt pattern is mostly useful for deep hierarchies that are often
> queried for a whole branch at once and rarely updated.
>
> If you have a not-that-deep tree with frequent updates and don't need
> to retrieve whole branches at once, the adjacency list or materialized
> path patterns (or a combination of both) might yield better results.
>
>
>
> > One idea is, to build the hierarchical structure with one model and
> > mptt and in it, I define two ForeignKeys to the concrete data objects
> > I want to store (ForeignKey(Group) and Foreignkey(Item)). But this
> > sounds a bit strange to me. I think there should be a much smarter
> > way.
>
> From the OOD perspective, this looks like a canonical use case for the
> composite design pattern. Applied to Django's models and using the
> adjacency list pattern, you'd have a Node base class with Groups and
> Items subclasses (Q example, may contains obvious stupid errors):
>
> class Node(models.Model):
>    parent = models.ForeignKey(
>        "self",
>         blank=True,
>         null=True,
>         related_name="children"
>         )
>
>     def save(self, *args, **kw):
>         if self.parent and type(self.parent) != Group:
>             raise ValueError("only Group nodes can be parents")
>         super(Node, self).save(*args, **kw)
>
> class Group(Node):
>    # code here
>
> class Item(Node):
>    # code here
>
> Don't know if and how it would solve your problem, but this might get
> you started one way or another... Else, well, sorry but that's all I
> have :-/

-- 
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: what is up with InternalError current transaction is aborted, commands ignored until end of transaction block

2010-02-25 Thread Carl Zmola

I ran into the same problem, but have avoided the "commit manually" and used
try:
  #do my normal stuff
except psycopg2.InternalError, e:
#transaction.rollback_unless_managed()
django.db.connection._rollback()

Again, I am not sure whether it is a signal handler or some internal 
Django save processing that is causing the problem.


I didn't use rollback_unless_managed because I didn't understand the 
interaction between managed and unmanaged.


Maybe someone can explain the issue.

Carl


On 02/22/2010 09:44 AM, talpay...@gmail.com wrote:

i actually found a solution. i don't know what the problem is... and
it wouldn't mater anyway. I just wanted to catch and show a message
about it. You should you something like this:

from django.db import transaction

@transaction.commit_manually
def view(request):
 try:
 #do something with database
 transaction.commit()
 except:
 transaction.rollback()
 #return error message.


Thank you for the help.

   


--
Carl Zmola
301-562-1900 x315
czm...@woti.com


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



Re: How can I add the Openid session data to the Django test client Client.post() ?

2010-02-25 Thread br...@instantdirectmarketing.com
I looked at how the Django test client class method, Client.login()
stored sessions and attempt to copy the important sections into the
test so the session data could be stored.

When I broke into the test immediately before Client.post() was called
and the session looked OK.
ipdb> request.session.__dict__
{'_session_cache': {'openid': 'https://www.google.com/accounts/o8/id?
id=ItsAFakeOpenID'}, '_session_key':
'decee0b0bdbba7ad7c1a6601bbc60ef1', 'modified': True, 'accessed':
True}

However, after Client.post() the session doesn't seem to contain the
request.session['openid'] any longer.
I broke into the register view and checked:
ipdb> request.session.__dict__
{'_session_cache': {'pagesize': 10}, '_session_key': None, 'modified':
True, 'accessed': True}

Why is the session data not persisting?

class UserTestCAse(TestCase):
def test_register_should_create_UserProfile(self):
from django.test.client import Client
c = Client()

# Create a fake request to store session details.
from django.http import HttpRequest
request = HttpRequest()
from django.contrib.sessions.backends.db import SessionStore
request.session = SessionStore()

request.session['openid'] = 'https://www.google.com/accounts/
o8/id?id=ItsAFakeOpenID'
request.session.save()

response = c.post('/account/register/', {u'username':
[u'john'], u'email': [u'j...@beatles.com'], u'bnewaccount':
[u'Signup']})
self.assertEqual(response.status_code, 200)
user = User.objects.get( username ='john')
self.assertTrue(user.get_profile())

On Feb 24, 5:12 pm, "br...@instantdirectmarketing.com"
 wrote:
> I'm trying to test that a UserProfile model is created as a new User
> is registered in django_authopenid.
> I don't understand how to add the Openidsessiondata to the POST.
>
>     class UserTestCase(TestCase):
>       def test_register_should_create_UserProfile(self):
>         from django.test.client import Client
>         c = Client()
>         response = c.post('/account/register/', {u'username':
> [u'john'], u'email': [u'j...@beatles.com'], u'bnewaccount':
> [u'Signup']},)
>
>         self.assertEqual(response.status_code, 302)
>
>         user = User.objects.get( username ='john')
>         self.assertTrue(user.get_profile())
>
> I'm using django_authopenid and I want to make sure a UserProfile is
> created after the User is created.

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



Dynamic list of checkboxes from database info

2010-02-25 Thread Timothy Kinney
** Background **

In the admin view, I want to generate a form which grabs a list of
items from the database and displays a checkbox next to each item. The
goal is simply to check multiple boxes and hit Submit and they are
deleted.

Because of the way my models are setup, there is no default admin view
for this. I couldn't figure out how to get change_list.html to display
the item info, so I am trying to write my own (it's good practice
anyway).

***
My questions:

1) I don't understand how the InventoryFieldModel fields get populated
in the database. Do I need to do this explicitly? Or is the
get_inventory_form() function handling it?

2) How do I add the checkboxes to each listed item?

3) Inside the view function, if I "print form.as_p()" nothing is
returned. Is this because I didn't populate the database correctly? Or
am I calling get_inventory_form() with not enough keywords?

>From what I understand, get_inventory_form is supposed to take the
samurai instance, get the inventory objects associated with him from
the db, and create a form field for each item in the inventory.

***

Following: http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/
I added the information noted below.

*** My code ***
** models.py **
type_mapping = {'CharField':forms.CharField(max_length = 100),
'TextField': forms.CharField(widget = forms.Textarea),
'BooleanField':forms.BooleanField(required = False),
'URLField': forms.URLField(), 'EmailField': forms.EmailField()
}

class InventoryFieldModel(models.Model):
samurai = models.ForeignKey('Samurai')
item = models.ForeignKey('Item')
condition = models.IntegerField()

** forms.py **

def get_inventory_form(samurai):
inventory_fields =
InventoryFieldModel.objects.filter(samurai=samurai).order_by('item')

class InventoryForm2(forms.Form):
def __init__(self, *args, **kwargs):
forms.Form.__init__(self, *args, **kwargs)
self.samurai = samurai

def save(self):
# do the save
pass

for field in inventory_fields:
setattr(InventoryForm2, field.name,
copy(type_mapping[field.type]))
return type('InventoryForm2', (forms.Form, ),
dict(InventoryForm2.__dict__))

** admin_views.py **

def remove_item_from_samurai(request, samurai_id):
samurai = Samurai.objects.select_related().get(pk=samurai_id)
inv =
Inventory.objects.select_related().filter(samurai=samurai_id).order_by('item')
inventory_form = get_inventory_form(samurai)

if request.method == 'POST':
form = inventory_form(request.POST)
if form.is_valid():

##process data and delete items
return HttpResponse("ok")
else:
form = inventory_form()

return render_to_response("admin/myapp/samurai/remove_item.html",
{
'samurai': samurai,
'inv': inv,
'form': form
})

** remove_item.html **



{{ form.as_table }}





-- 
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: Redirecting to a different view after posting a form

2010-02-25 Thread Timothy Kinney
I have taken a, perhaps, unorthodox tact for my admin views. I use
myproject/urls.py to grab the url and redirect to
myapp.admin_views.samurai_detail

urls.py catches url patterns such as:
r'^admin/myapp/samurai/(?P.*)/add_item/$'
r'^admin/myapp/samurai/(?P.*)/$

I am keeping all of my admin_views in admin_views.py although I keep my
ModelAdmin classes in admin.py, so I sort of have two admin files.

The HttpResponseRedirect is supposed to go from
admin_views.add_item_to_samurai (after a successful request.POST) to
admin_views.samurai_detail

How would I craft the reverse() for that?

Note that if I do just do reverse('add_item_to_samurai') or however I try to
pass in the samurai_id keyword, I get the same error (noted in top post).

-TIm

On Thu, Feb 25, 2010 at 4:14 PM, Karen Tracey  wrote:

> On Thu, Feb 25, 2010 at 4:25 PM, bruno desthuilliers <
> bruno.desthuilli...@gmail.com> wrote:
>
>> On 25 fév, 20:49, Timothy Kinney  wrote:
>> > I think I'll just
>> > stick with urls.
>>
>> Mmmm... Fine for you if it works, but as far as I'm concerned I don't
>> like it. I do use HttpResponseRedirect, but I pass in the result of a
>> call to reverse(), always using named urls. OTHO, I don't know if
>> admin urls are named.
>>
>>
> They are, and reversable, as of 1.1:
> http://docs.djangoproject.com/en/1.1/ref/contrib/admin/#admin-reverse-urls
>
> I'm a little unclear on what's being done here to override admin views with
> views provided by the app, though, so I'm not sure that's relevant for the
> original question. Looking back at the original question I'd expect a view
> named samurai_detail to take an argument that specifies what samurai to show
> details for, yet the call to reverse specified no arguments. That could be
> the cause of the revere() failure.  Without specifics of the actual url
> patterns being used, though, it's hard to ay for ure.
>
> Karen, using laptop with a barely functioning s key and tired of fixing the
> tupid typo that reult. Sorry about that.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



Re: Redirecting to a different view after posting a form

2010-02-25 Thread Karen Tracey
On Thu, Feb 25, 2010 at 4:25 PM, bruno desthuilliers <
bruno.desthuilli...@gmail.com> wrote:

> On 25 fév, 20:49, Timothy Kinney  wrote:
> > I think I'll just
> > stick with urls.
>
> Mmmm... Fine for you if it works, but as far as I'm concerned I don't
> like it. I do use HttpResponseRedirect, but I pass in the result of a
> call to reverse(), always using named urls. OTHO, I don't know if
> admin urls are named.
>
>
They are, and reversable, as of 1.1:
http://docs.djangoproject.com/en/1.1/ref/contrib/admin/#admin-reverse-urls

I'm a little unclear on what's being done here to override admin views with
views provided by the app, though, so I'm not sure that's relevant for the
original question. Looking back at the original question I'd expect a view
named samurai_detail to take an argument that specifies what samurai to show
details for, yet the call to reverse specified no arguments. That could be
the cause of the revere() failure.  Without specifics of the actual url
patterns being used, though, it's hard to ay for ure.

Karen, using laptop with a barely functioning s key and tired of fixing the
tupid typo that reult. Sorry about that.

-- 
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: Subclassing Comments model

2010-02-25 Thread Xavier Ordoquy

Hi,

You should read Django's esp how to use custom comment class.
You should have a line in your setting file for overriding the default  
class.


Xavier

--
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: debugging server code problems in server code that is invoked via ajax request

2010-02-25 Thread bruno desthuilliers


On 25 fév, 17:06, Margie Roginski  wrote:
> Hi - thanks for your responses.  Was on vacation and forgot to check
> back on this thread.  The idea of middleware is good.  I'm not sure,
> however, if the views.py code generates an exception, that it can be
> caught by the middleware?  

How do you think Django display that nice error page instead of a raw
"Internal Servor Error" ?-)

http://docs.djangoproject.com/en/1.1/topics/http/middleware/#process-exception

-- 
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: Redirecting to a different view after posting a form

2010-02-25 Thread bruno desthuilliers
On 25 fév, 20:49, Timothy Kinney  wrote:
> Thanks for the reply, Bruno. For some reason, that still doesn't work for
> me. I can't figure out how to get reverse to work at all. But I took your
> advice about HttpResponseRedirect and this worked fine:
>
> return HttpResponseRedirect('../')
>
> I was always trying to put views in HttpResponseRedirect.

views names or views functions ? IIRC, reverse() takes both.

> I think I'll just
> stick with urls.

Mmmm... Fine for you if it works, but as far as I'm concerned I don't
like it. I do use HttpResponseRedirect, but I pass in the result of a
call to reverse(), always using named urls. OTHO, I don't know if
admin urls are named.

What you could do is try to find out the correct args for reverse -
you can check this out in the shell.

My 2 cents.

-- 
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: Subclassing Comments model

2010-02-25 Thread CrabbyPete
Sorry I did not finish.

How do I get the subclass PictureComment, not Comment.



On Feb 25, 4:13 pm, CrabbyPete  wrote:
> I subclassed the django comment app model, because I wanted to add
> photos.
>
> class PictureComment( Comment ):
>     photos          = models.ManyToManyField(Photos)
>
> In my template I use
> {% get_comment_list for message as comment_list %}
>
> {% for comment in comment_list %}
>
> {% endfor %}
>
> and  the list it returns is a list of comments, not the subclassed
> PictureComment.

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



Subclassing Comments model

2010-02-25 Thread CrabbyPete
I subclassed the django comment app model, because I wanted to add
photos.

class PictureComment( Comment ):
photos  = models.ManyToManyField(Photos)


In my template I use
{% get_comment_list for message as comment_list %}

{% for comment in comment_list %}


{% endfor %}

and  the list it returns is a list of comments, not the subclassed
PictureComment.

-- 
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: Can I use request.user, in the limit_choices_to filter in Model class?

2010-02-25 Thread zinckiwi
> I need to filter a field by a UserProfile function, i.e. how can I do
> something like this?
>
> class Paquet(models.Model):
>     ...
>     profiles = models.ManyToManyField(UserProfile, limit_choices_to =
> {'country': request.user.userprofile.country})

I'd put that restriction inside the ModelForm that derives from
Paquet, rather than into the model itself. I wouldn't even know how to
go about getting the current Request to the model, and there's a
reason for that: not a good idea!

Likewise, in the ModelForm, you won't have native access to the
current request. You're best off passing in request.user when you
instantiate the form.

Regards
Scott

-- 
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: form.has_changed always true?

2010-02-25 Thread Karen Tracey
On Thu, Feb 25, 2010 at 3:03 PM, ducu  wrote:

> Btw, has_changed() doesn't seem to work on non-model forms, does it?
>
>
Yes, it does:

>>> from django import forms
>>> class AForm(forms.Form):
... x = forms.IntegerField()
...
>>> af = AForm({'x': u'1'}, initial={'x': 1})
>>> af.has_changed()
False
>>> af = AForm({'x': u'1'}, initial={'x': 0})
>>> af.has_changed()
True

Karen

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



Re: transaction in django app desktop

2010-02-25 Thread Peter Herndon

On Feb 24, 2010, at 2:51 PM, ktemo wrote:

> hi
> i working in a desktop app with django mysql,  and wxpython, and i
> need to make transaction
> i read the doc online, but i dont know if is possible work with a
> desktop app

If you could provide more detail on what you want to accomplish, we could 
provide better responses.  Barring that, I'll try to guess what you meant; 
please let me know if I am misunderstanding you.

I guess from what you've provided that you are writing a GUI front-end in 
wxPython that makes HTTP calls to a backend server.  That backend server is 
running Django, and storing data in MySQL.

Django itself doesn't care where an HTTP request comes from.  You could be 
making the request from a GUI app, from JavaScript via Ajax in a browser, or 
from HTML in a browser.  Django doesn't care, it treats all requests the same 
way.  So if you write a view function in Django that accepts a request 
containing certain arguments, and that view function uses Django's ORM to 
modify data in the database in a transaction, you can call that view from your 
GUI, from a browser, from curl or wget, or any other means at your disposal to 
generate an HTTP request, and the view function will run inside its transaction 
just fine.  So yes, it is possible.

Does that answer your question?

---Peter Herndon

-- 
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: form.has_changed always true?

2010-02-25 Thread ducu
Btw, has_changed() doesn't seem to work on non-model forms, does it?

On Jan 12, 12:43 am, Alastair Campbell  wrote:
> On Fri, Jan 8, 2010 at 1:09 AM, Karen Tracey  wrote:
> > Using the instance parameter is the POST leg also allows you to simply
> > save() the form to get the changes to the instance saved.  There is then no
> > need to individually copy each of the fields from the form's cleaned_data
> > dict to the model instance.  See:
>
> Thanks Karen, that worked great.
>
> I had done quite a few non-model forms, which is a more manual
> process, I hadn't twigged that you save the form rather than the
> model. After that, the changed form aspect works great and I can
> selectively output the changed data.
>
> Thanks for the help,
>
> -Alastair

-- 
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: Redirecting to a different view after posting a form

2010-02-25 Thread Timothy Kinney
Thanks for the reply, Bruno. For some reason, that still doesn't work for
me. I can't figure out how to get reverse to work at all. But I took your
advice about HttpResponseRedirect and this worked fine:

return HttpResponseRedirect('../')

Since my path structure is: myProject/myApp/samurai/samurai_id/add_item
All I need to do is back up one.

I was always trying to put views in HttpResponseRedirect. I think I'll just
stick with urls.

-Tim


On Thu, Feb 25, 2010 at 3:51 AM, bruno desthuilliers <
bruno.desthuilli...@gmail.com> wrote:

> On Feb 25, 1:15 am, Timothy Kinney  wrote:
> > I have two views:
> > samurai_detail
> > add_item_to_samurai
> >
> > There is a button in samurai_detail that links to add_item_to_samurai.
> > The templates are the same except that add_item_to_samurai includes a
> > form to add an item.
> >
> > After posting the form, I want to redirect back to samurai_detail (the
> > page without the form that shows the items).
> >
> > As in the Django documentation, I thought I could do this with a
> > redirect, like so:
> > return redirect('samurai_detail')
> >
> > But this returns: Reverse for 'samurai_detail' with arguments '()' and
> > keyword arguments '{}' not found.
>
> I personnaly still stick to using an HttpResponseRedirect with an
> explicit call to reverse - mostly because I failed to spot this new
> shortcut FWIW !-)
>
> > This is a little bit cryptic. I think it says it can't find my view.
>
> What it says is that it fails to find any url definition that would
> call the samurai_detail view _without any argument_.
>
> > Both views are contained in myproject.myapp.admin_views.py
> >
> > Am I using reverse() incorrectly? How can I redirect to the
> > samurai_detail view?
>
> What's the signature of your samurai_detail view ?
>
> Ok, assuming it's defined as
>
> def samurai_detail(request, samurai_id):
>  # code
>
> you could try either:
>
>  return redirect('samurai_detail', samurai.id)
>
> or
>
>  return redirect('samurai_detail', samurai_id=samurai.id)
>
> My 2 cents...
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Multiple DB in django 1.2

2010-02-25 Thread Roach, Marshall (MROACH)
Hi, I was at pycon last week and heard about the db routers in django 1.2
and I have the alpha version of django running for a project I¹m running and
trying to figure out how to do the following.

I have 2 databases on different machines and if its one of the models I want
the database to write everything to both machines.

I¹m running postgresql and having issues trying to get my router right and
didn¹t know if anyone else has done this before.

Thanks,

Marshall 

-- 

Marshall Roach
mro...@arinc.com


-
This e-mail (including any attachments) is intended only for the use of the
individual or entity named above and may contain privileged, proprietary, or
confidential information.  The information may also contain technical data
subject to export control laws.
-

Please consider the environment before printing this email.

-- 
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: Lazy model load problem (0.96 -> 1.1 difference)

2010-02-25 Thread Eric Floehr
For posterity, I discovered the difference between 0.96 and 1.1.1.
Django 0.96 doesn't cache related objects passed in via the
constructor of a model, whereas 1.1.1 does.

Here is the setup.  I create a model instance, just populating the
primary key:

>>> s = Station(station_index=1846)

In 0.96 I was doing the following.  "station" on the StationRel object
is a ForeignKey:

>>> badrel = StationRel(station=s)

For reference, here is the ORM-generated relation:

>>> goodrel = StationRel.objects.get(station__station_index=1846)

In Django 0.96, the model sucks out the primary key from the Station
object, but discards the Station object itself:

>>> badrel.__dict__
{'id': None, 'station_id': 1846}
>>> goodrel.__dict__
{'id': 4255L, 'station_id': 1846L}

This causes references to the "station" foreign key on StationRel to
load the full Station model object.  In both cases, the station object
gets loaded.

However, in Django 1.1.1, when a model object involved in a ForeignKey
is passed in, it caches that object, assuming it's fully populated.
Note the '_station_cache' property:

>>> badrel.__dict__
{'_station_cache': , 'station_id': 1846, 'id':
None}
>>> goodrel.__dict__
{'id': 9L, 'station_id': 1846L}

So when the station property is accessed on the relation, it uses the
cached object, which isn't populated when "StationRel.objects.get" is
used.  The solution for me is to just pass in 'station_id'' to the
constructor like:

>> badrel_nowgood = StationProviderRel(station_id=1846)
>> badrel_nowgood.__dict__
{'id': None, 'station_id': 1846}

and not create a Station object at all.

Best Regards,
Eric


On Feb 24, 3:28 pm, Eric Floehr  wrote:
> I am moving an application (finally) from 0.96 to 1.1.1 and I'm
> running into an issue I haven't been able to resolve.
>
> To make things simple, here are the two relevant models:
>
> class Station(models.Model):
>     station_index = models.AutoField(primary_key=True)
>     name = models.CharField()
>
>     ...
>
> class StationRelation(models.Model):
>     station = models.ForeignKey(Station, db_column='station_index')
>
>     objects = CustomStationRelationManager()
>     ...
>
> class CustomStationRelationManager()
>     def get_nearest(zipcode):
>         
>
> In the custom manager code, I set the primary key in a new Station
> object so it (in 0.96) would only get loaded if it was referenced:
>
> def get_nearest(zipcode):
>      ... custom SQL that returns a station_index, etc. ...
>      s = Station(station_index=row[0])  # row[0] is select
> station_index, from the sql result
>      rel = self.model(station=s)
>      return rel
>
> In 0.96, if code that received the StationRelation object accessed,
> say the name field, the Django ORM would do sql to fully populate the
> station object.
>
> print rel.station.name
> COLUMBUS
>
> However, in 1.1.1, the same code does not do that:
>
> print rel.station.name
> None
>
> In either 0.96 or 1.1.1 if I use the standard manager, lazy
> instantiation works as normal:
>
> rel = StationRelation.objects.get(station__station_index=1846) # Note,
> no select_related
> ...
> print rel.station.name # the SQL to get station's properties happens
> here, not before
> COLUMBUS
>
> So, the question is, what do I have to do in 1.1.1 that I didn't in
> 0.96 in order to properly lazy populate a manually created model
> object, beyond just the primary key?
>
> Thanks for your help!
> Eric

-- 
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: transaction in django app desktop

2010-02-25 Thread ktemo
thanks, trying one more time 

On 25 feb, 08:30, rebus_  wrote:
> On 24 February 2010 20:51, ktemo  wrote:
>
> > hi
> > i working in a desktop app withdjangomysql,  and wxpython, and i
> > need to make transaction
> >  i read the doc online, but i dont know if is possible work with a
> > desktop app
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Djangousers" group.
> > To post to this group, send email todjango-us...@googlegroups.com.
> > To unsubscribe from this group, send email 
> > todjango-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
> As far as i know, to use transactions in MySQL you need to use InnoDB
> storage engine because MyISAM does not support transactions.

-- 
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: Django REST and FILEFIELD field

2010-02-25 Thread manu.polline
Hi everyone,
anyone help me??

On 22 Feb, 19:19, "manu.polline"  wrote:
> Hi everyone,
> my name is Manuel. I'm tryng to upload a file directly in a filefield
> of Django model exposed by django-rest-interface.
> It'is possible?
> this is my model :
>
> class File(models.Model):
>     file = models.FileField(upload_to='files',
>         help_text=_("file itself"))
>     page = models.ForeignKey(page)
>
> and my urls.py :
> json_File_resource = Collection(
>     queryset = File.objects.all(),
>         authentication = HttpBasicAuthentication(),
>     permitted_methods = ('GET', 'POST', 'PUT', 'DELETE'),
>     receiver = JSONReceiver(),
>     responder = JSONResponder()
> )
>
> urlpatterns = patterns('',
>     
>     
>     url(r'^json/File/(.*?)/?$',json_File_resource),
>     ...
> )
>
> The GET works and the PUT to other field too but not the POST or the
> PUT on filefield Field.
> How i can pass the local file to the remote Service in the JSON
> string?
>
> Please Help Me!!!
>
> Manuel

-- 
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: debugging server code problems in server code that is invoked via ajax request

2010-02-25 Thread David De La Harpe Golden

Possibly useful tip:

Note that if you use request.is_ajax() in your django views, you can 
also use e.g. the "Modify Headers" firefox plugin to simply pretend to 
django that an ordinary request you've e.g. typed into your browser 
address bar is an "ajax" request, with a rule e.g.


Action   Name   ValueComment
"Modify" "X-Requested-With" "XMLHttpRequest" "Fake AJAX Request"

Quite handy (there's a gui for enabling/disabling rules with a click)

https://addons.mozilla.org/en-US/firefox/addon/967

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



HttpResponseRedirect waiting for something

2010-02-25 Thread adrian

I have a view that takes a form submission with a file, loads orders
from the XML file by parsing it and saving records.  After it is all
done
it redirects to another view, but the redirect hangs for about 30+
seconds then I get this message and it continues normally:

Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/django/core/servers/
basehttp.py", line 280, in run
self.finish_response()
  File "/usr/local/lib/python2.6/dist-packages/django/core/servers/
basehttp.py", line 320, in finish_response
self.write(data)
  File "/usr/local/lib/python2.6/dist-packages/django/core/servers/
basehttp.py", line 416, in write
self._write(data)
  File "/usr/lib/python2.6/socket.py", line 300, in write
self.flush()
  File "/usr/lib/python2.6/socket.py", line 286, in flush
self._sock.sendall(buffer)
error: [Errno 32] Broken pipe

I do not open any pipes and I have closed all open files.   The XML is
parsed with ElementTree.  Can anyone suggest where to start looking
into this?

Thanks

Here is the view:

def handle_uploaded_file(store, file):
# file is an InMemoryUploadedFile, access with methods
from settings import MEDIA_ROOT
filename = MEDIA_ROOT + '/data/' + store.store_name_as_filename()
+ '/' + file.name
d = os.path.dirname(filename)
if not os.path.isdir(d):
os.makedirs(d)

print "filename %s" % filename
destination = open(filename, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()

order_file = open(filename, 'r')
from orders.xmlparser import parse_xml
result = parse_xml(store, order_file)
print "%s: result %s" % (datetime.datetime.now(), result)
order_file.close()
return True if result else False


@login_required
def store_config(request):
# get store for user, see if user can edit settings
profile = check_perms(request, 'can_edit_settings')
if profile == 'error':
return HttpResponseRedirect('/settingsadmin/')

if request.method == 'GET':
form = StoreConfigForm(instance=profile.store)
else:
form = StoreConfigForm(request.POST, request.FILES,
instance=profile.store)

if form.is_valid():
form.save()
request.notifications.create("Modified store settings." ,
'success')

if 'order_import_filename' in request.FILES:
request.notifications.create("Parsing orders from
file..." , 'success')
success = handle_uploaded_file(profile.store,
request.FILES['order_import_filename'])
if success:
request.notifications.create("Parsing orders from
file successful." , 'success')
else:
request.notifications.create("Parsing orders from
file failed" , 'error')


#return HttpResponseRedirect(reverse(jk))   TODO
print "%s: about to return from view" %
datetime.datetime.now()
return HttpResponseRedirect('/settingsadmin/')

else:
pass
# drops through into redisplay of form with errors

title = "Store Configuration"
return render_to_response('settingsadmin/config.html', {
'form': form,
'title': title,
}, context_instance=RequestContext(request))

-- 
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: debugging server code problems in server code that is invoked via ajax request

2010-02-25 Thread Margie Roginski
Hi - thanks for your responses.  Was on vacation and forgot to check
back on this thread.  The idea of middleware is good.  I'm not sure,
however, if the views.py code generates an exception, that it can be
caught by the middleware?  I guess the question is how to catch
exceptions.  The views.py code is invoked by the django code, so on a
normal request, that django code must catch the exception and then
send it as a response to the client.  On a non-ajax request, the
response just gets displayed in the browser.  But on an ajax request,
unless I do some special stuff, I guess that response doesn't get
displayed.  So the question becomes how to catch the exception and put
it somewhere useful, and I'm still not clear if I can use middleware
to do that.

One thing that I realize is that if I just make a request to the same
address that the ajax request is going to, then I do see the error
trace in my browser, so that's helpful and that's the tact I have been
taking lately.

Margie

On Feb 12, 2:33 am, bruno desthuilliers
 wrote:
> On Feb 11, 10:27 pm, MargieRoginski wrote:
>
> > I have a question about debugging django server side code in the case
> > where the request is an ajax request.
>
> From the server-side POV, a request is a request is a request. Truth
> is : there's no such thing as an "ajax request".
>
> >  For example I have an
> > autocomplete widget.  It makes a request to a particular url that
> > takes me to one of my views.py functions, get_users(request).  If I
> > have some sort of error in that function, I don't see the error
> > anywhere and it just silently fails.
>
> It's your client code that fails to handle the case properly.
>
> >  If I explicitly put that url
> > into the address bar then the error comes up in my browser, or if I
> > use pdb to put a break point and then step through my code, I see the
> > error.   In the case of an ajax request,
>
> cf above.
>
> > what happens to the error
> > from the server code and is there any way to see it?
>
> yes : look at the response content. Firebug is your friend - it lets
> you trace and inspect XMLHttpRequests and their responses. Also, you
> may want to have a "logging" middleware that logs unhandled errors -
> this is useful both in dev or in production.
>
> HTH

-- 
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: Dev environnement, Eclipse, pydev, Windows, remote developement

2010-02-25 Thread thanos
How about running your linux in  vmware or virtualbox on your windows
machine.
Its the right way to go. You can then develop in you production
environment. BTW do you use virtualenv. It can save you a lot of pain!

Thanos


On Feb 25, 9:59 am, Eric Brockmann 
wrote:
> Hi all !
>
> Just begining to set up my work environnement...
> Is there a way to develop using Eclipse/Pydev from my workstation on  
> Windows (i know, i know...can't choose )  to create a Linux Django site. ?
> The remote Linux machine is very basic and i can't install any dev
> environnement on it.
> Is Remote editing posssible with Eclipse  ?
> Any advice very welcomed
> Thanks .

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



Dev environnement, Eclipse, pydev, Windows, remote developement

2010-02-25 Thread Eric Brockmann

Hi all !

Just begining to set up my work environnement...
Is there a way to develop using Eclipse/Pydev from my workstation on
Windows (i know, i know...can't choose )  to create a Linux Django site. ?
The remote Linux machine is very basic and i can't install any dev
environnement on it.
Is Remote editing posssible with Eclipse  ?
Any advice very welcomed
Thanks .

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



Dev environnement, Eclipse, pydev, Windows, remote developement

2010-02-25 Thread Eric Brockmann

Hi all !

Just begining to set up my work environnement...
Is there a way to develop using Eclipse/Pydev from my workstation on  
Windows (i know, i know...can't choose )  to create a Linux Django site. ?
The remote Linux machine is very basic and i can't install any dev 
environnement on it.

Is Remote editing posssible with Eclipse  ?
Any advice very welcomed
Thanks .

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



Re: Custom button for imagefield form

2010-02-25 Thread Tom Evans
On Mon, Feb 22, 2010 at 1:06 PM, CrabbyPete  wrote:
> I have form with where users can upload an image. All works well but I
> want a graphic instead of the default browse button that shows up. Can
> I change it and if so how do you change it in the form field or
> template?
>
>
> class ProfileForm(SignUpForm):
>
>    mugshot         = forms.ImageField      (required = False)
>

Please learn to use google, top result for 'styling file input':

http://www.quirksmode.org/dom/inputfile.html

HTH

Tom

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

2010-02-25 Thread rebus_
On 22 February 2010 14:06, CrabbyPete  wrote:
> I have form with where users can upload an image. All works well but I
> want a graphic instead of the default browse button that shows up. Can
> I change it and if so how do you change it in the form field or
> template?
>
>
> class ProfileForm(SignUpForm):
>
>    mugshot         = forms.ImageField      (required = False)
>
> --
> 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.
>
>

I don't really understand what are you trying to do, but if you want
to change the appearance of the forms buttons you should try to use
CSS, it has nothing to do with Django AFAIK (except maybe you could
create your own widget but i don't see how that would help).

-- 
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: preventing template from converting html entities

2010-02-25 Thread Alex Robbins
Oops, it would actually be
title={% filter force_escape %}{{ villa.name }}{% endfilter %}

Sorry.
--
Alex Robbins
5Q Communications, Inc.
http://www.5Qcommunications.com/
alex.robb...@5qcommunications.com
800-747-4214 ext 913 (p)
http://www.ask5q.com/twitter/



On Thu, Feb 25, 2010 at 8:33 AM, Alex Robbins
 wrote:
> I think you can do that with title={% filter force_escape
> %}"{{ villa.name }}"{% endfilter %}. Haven't tried it though.
>
> Alex
>
> On Feb 24, 8:36 am, Federico Capoano  wrote:
>> Hello to all,
>>
>> simple question:
>>
>> I have the following HTML in a template:
>> 
>>
>> But it gets rendered this way:
>> 
>>
>> That is, the  entity is converted to the respective character,
>> ". Very nice, but i'd need 
>>
>> Is there a filter or something i can use to tell the Django Template
>> System to render  ?
>>
>> Thanks in advance.
>>
>> Federico
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: preventing template from converting html entities

2010-02-25 Thread Alex Robbins
I think you can do that with title={% filter force_escape
%}"{{ villa.name }}"{% endfilter %}. Haven't tried it though.

Alex

On Feb 24, 8:36 am, Federico Capoano  wrote:
> Hello to all,
>
> simple question:
>
> I have the following HTML in a template:
> 
>
> But it gets rendered this way:
> 
>
> That is, the  entity is converted to the respective character,
> ". Very nice, but i'd need 
>
> Is there a filter or something i can use to tell the Django Template
> System to render  ?
>
> Thanks in advance.
>
> Federico

-- 
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: transaction in django app desktop

2010-02-25 Thread rebus_
On 24 February 2010 20:51, ktemo  wrote:
> hi
> i working in a desktop app with django mysql,  and wxpython, and i
> need to make transaction
>  i read the doc online, but i dont know if is possible work with a
> desktop app
>
> --
> 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.
>
>

As far as i know, to use transactions in MySQL you need to use InnoDB
storage engine because MyISAM does not support transactions.

-- 
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: Passing RequestContext as dict vs. context_instance=RequestContext

2010-02-25 Thread Alex Robbins
If you get tired of forgetting to add the RequestContext you can use
direct_to_template[1] instead. (I almost always forget it the first
time)

It is almost exactly like render_to_response, you'd use it like this:

def index(request):
return direct_to_template(request, 'index.html', {
'extra_context_var': value,
})

Alex

[1] 
http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-simple-direct-to-template

On Feb 24, 6:00 am, Jesaja Everling  wrote:
> Hi all!
>
> Is there any difference between these two ways of using
> RequestContext?
> I'm asking because I usually use the first approach, but I want to
> make sure that there are no subtle differences.
>
> 1)
> def index(request):
>     return render_to_response('index.html',
>                               RequestContext(request,
>                                              {}
>                                              ))
>
> 2)
> def index(request):
>     return render_to_response('index.html',
>                              {},
>                               context_instance =
> RequestContext(request))
>
> Thanks!
>
> Jesaja Everling

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



Re: how to capture the exception

2010-02-25 Thread Karen Tracey
On Wed, Feb 24, 2010 at 5:13 PM, bruno desthuilliers <
bruno.desthuilli...@gmail.com> wrote:

> But anyway: you already specified the unique constraint in the 'name'
> field definition, so adding this code in your model save() method is
> just useless - the uniqueness constraint WILL be applied at the db
> level.
>
> > this causes 500 error,and causes the traceback displayed on
> > browser..how can I prevent this crash and give the user some useful
> > warning?
>
> Do the test in your ModelForm 'clean_name' method and raise a
> ValidationError there.
>

If the model field has been specified as unique then the default ModelForm
clean() processing should already be checking for uniqueness. It is
necessary to ensure that the superclass clean() is called from any form-wide
clean() override (as noted here:
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method).
There should be no need to add unique checking to either the form clean
methods or the model save() override.

Karen

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



Re: schema migration

2010-02-25 Thread Shawn Milochik
The way to go is South: http://south.aeracode.org/

Shawn

On Feb 24, 2010, at 11:51 PM, vishal d wrote:

> Hi to all
> 
>  Am new to django...plz suggest me which is the better one for the
> schema migration for django apps
> 
>  Thanks in advance
> 
>  vishal
>  2009vis...@gmail.com
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
> 

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



Do fixtures in tests overwrite default model field values?

2010-02-25 Thread filias
Hi,

I am running several tests and created a fixture with the test data.
I have one model with a custom field which has a default value.

I thought my test fixture should overwrite this field for some of the
objects but when run the test the value for the field is always the
default value.

Is this the normal behavior or do I have some bug in my custom field?

Thanks.

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



Noob: Can you use the ORM to do a self join with an aggregate?

2010-02-25 Thread Peter Phillips
Just started in the last few days with django and am having a little
trouble with the orm. Is it possible to do a self join with an
aggregate? My query looks like the following (apologies for the
generic names):


SELECT t.field1, c.field2, c.field3, t.field4, t.field5, (t.field4/
t.field5) as "field6", t.field7
FROM ( SELECT field1, max(field7) as field7 FROM table1 GROUP BY
field1) x
JOIN table1 t
ON x.field1 = t.field1 AND x.field7 = t.field7
JOIN table2 c ON t.field1 = c.field8

For the moment I'm just using a custom manager, but I wasn't sure if
this was the best way to go. My code looks like the following:

class CustomManager(modelsManager):
def curr_quad(self):
cursor = connection.cursor()
cursor.execute("""
SELECT t.field1, c.field2, c.field3, t.field4, t.field5,
(t.field4/t.field5) as "field6", t.field7
FROM ( SELECT field1, max(field7) as field7 FROM table1 GROUP
BY field1) x
JOIN table1 t
ON x.field1 = t.field1 AND x.field7 = t.field7
JOIN table2 c ON t.field1 = c.field8 """)
return [row for row in cursor.fetchall()]


class Rdf_Qt(models.Model):
.
.
.
objects = CustomManager()


Thanks!

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



schema migration

2010-02-25 Thread vishal d
Hi to all

  Am new to django...plz suggest me which is the better one for the
schema migration for django apps

  Thanks in advance

  vishal
  2009vis...@gmail.com

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



Django + Varnish. Keepalive?

2010-02-25 Thread Alessandro Ronchi
I am using Varnish as a frontend proxy for my django apps. I usually
disable keepalive on apache, but in this case I've only one client (the
proxy on localhost) for apache, isn't it good to avoid closing and opening
connections?

Thanks in advance, best regards.

-- 
Alessandro Ronchi

http://www.soasi.com
SOASI - Sviluppo Software e Sistemi Open Source

http://hobbygiochi.com
Hobby & Giochi, l'e-commerce del divertimento

-- 
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: displaying validation errors

2010-02-25 Thread bruno desthuilliers
On Feb 25, 6:10 am, jimgardener  wrote:
> hello guys,
> I wanted to display validation errors in the form .I tried this
>
> class BookForm(ModelForm):
>     class Meta:
>         model=Book
>     def clean_bookname(self):
>         bkname=self.cleaned_data['bookname']
>         bkname=bkname.strip()
>         if Book.objects.filter(bookname__iexact=bkname).count()!=0:
>             self._errors.update({'duplicate book':'a book of this name
> already exists'})

Form._errors is already a dict-like object, so creating a dict to
update it is overkill - just set the appropriate key like you would
with a normal dict. The only gotcha here is that _errors expects to
have ErrorList objects as values, not raw strings. Also, note that you
have to set the *appropriate* key, that is use the field name as key.

But anyway : you don't have to mess with self._errors in a
clean_ method - just raising the ValidationError is enough,
and it should appear in the appropriate place(s).

Also, your test will prevent updating an existing record unless you
change the bookname's value, which would not be very practical !-)
Hint : you can access the form's book instance as 'self.instance', and
test on self.instance.pk to know whether it's a new book or an
existing one.

> This causes validationerror to be raised when user tries to enter a
> duplicate book name in the CharField 'bookname' .But I wish to show an
> error message about the duplicate book name.How do I do this?

Assuming your view and template code are correct, it should already
appear - unless your messings with _errors broke something.

> I tried
> to pass the form to template and print  {{form.errors}} but nothing is
> shown
> Can someone please help

First correct the form's code, then if it still don't show post your
view and template code here.

-- 
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: Set language on per page basis

2010-02-25 Thread Tom Evans
On Wed, Feb 24, 2010 at 8:59 PM, Tor Nordam  wrote:
> Thank you for your reply,
>
> Using the {% trans %} method is indeed what I intend to do. But the
> problem is how to set the language on a page basis, rather than as an
> installation-wide setting, or a user-selectable setting.
>


Just do what django.middleware.locale.LocaleMiddleware does (Use the
source, Luke):

Activate the required language (django.utils.translation.activate).
Set request.LANGUAGE_CODE to the required language.
Set the header 'Content-Language' on the response.
If the page contents vary upon the requested language, set/update the
'Vary' header on the response to include 'Accept-Language', but sounds
as though your pages are in one specific language.
Deactivate the translation after you're done with it.

Cheers

Tom

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

2010-02-25 Thread bruno desthuilliers
On Feb 25, 5:51 am, HARRY POTTRER  wrote:
> Why not something like this:
>
> class Person(models.Model):
>     @classmethod
>     def male(cls):
>         return cls.objects.filter(gender='M')
>
>     @classmethod
>     def female(cls):
>         return cls.objects.filter(gender='F')
>
>     name = models.CharField(maxlength=20)
>     gender = models.CharField(maxlength=1)
>
> instead of defining a 'female' and 'male' custom managers as is
> illustrated in the docs? Whenever I need to define 'table level'
> functionality, I've always gone with the above method rather than
> bother with a custom manager. What am I missing out on?

I don't find the doc example to be really that great FWIW. As far as
I'm concerned, I'd define 'male' and 'female' as methods of the same
custom manager. But anyway:

- custom managers let you do much more than just adding a couple
shortcuts,
- custom managers can be used as "related" managers - that is, when
traversing a relationship between to models.
- personal tastes here, but I like having the 'table-level' operations
properly namespaced.

Point #2 can be really useful for some relatively complex models /
relationships / bussiness rules, even if the way related_managers are
currently created makes for sometimes a bit hackish code.

My 2 cents...

-- 
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: Redirecting to a different view after posting a form

2010-02-25 Thread bruno desthuilliers
On Feb 25, 1:15 am, Timothy Kinney  wrote:
> I have two views:
> samurai_detail
> add_item_to_samurai
>
> There is a button in samurai_detail that links to add_item_to_samurai.
> The templates are the same except that add_item_to_samurai includes a
> form to add an item.
>
> After posting the form, I want to redirect back to samurai_detail (the
> page without the form that shows the items).
>
> As in the Django documentation, I thought I could do this with a
> redirect, like so:
> return redirect('samurai_detail')
>
> But this returns: Reverse for 'samurai_detail' with arguments '()' and
> keyword arguments '{}' not found.

I personnaly still stick to using an HttpResponseRedirect with an
explicit call to reverse - mostly because I failed to spot this new
shortcut FWIW !-)

> This is a little bit cryptic. I think it says it can't find my view.

What it says is that it fails to find any url definition that would
call the samurai_detail view _without any argument_.

> Both views are contained in myproject.myapp.admin_views.py
>
> Am I using reverse() incorrectly? How can I redirect to the
> samurai_detail view?

What's the signature of your samurai_detail view ?

Ok, assuming it's defined as

def samurai_detail(request, samurai_id):
  # code

you could try either:

  return redirect('samurai_detail', samurai.id)

or

  return redirect('samurai_detail', samurai_id=samurai.id)

My 2 cents...

-- 
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: Set language on per page basis

2010-02-25 Thread Ian Lewis
BTW: django-cms does something similar to what you are trying to do.
You can check out it's implementation here:

http://github.com/digi604/django-cms-2.0/blob/master/cms/middleware/multilingual.py

2010/2/25 Ian Lewis :
> In process_request you have access to the request object which knows
> the current path (request.path). You can use that to determine which
> language to show the page in.
>
> Or if you are determining the language based on a url parameter you
> can look at request.GET
>
> Ian
>
> On Thu, Feb 25, 2010 at 8:24 AM, Tor Nordam  wrote:
>> After doing some further research, I have found the following:
>>
>> By writing a small piece of custom middleware, I can change the value
>> of HTTP_ACCEPT_LANGUAGE. If I add this line to a process_request()
>>
>> request.META['HTTP_ACCEPT_LANGUAGE'] = 'no'
>>
>> then the webpage will be displayed with Norwegian translation.
>> However, I want to set the language based on which page the user is
>> trying to view, and process_request() doesn't know this. On the other
>> hand, if I use process_view(), I am able to determine what the
>> language should be, as process_view() gets passed for example the
>> arguments from the url. However, when I add the same line as above to
>> process_view(), nothing happens to the language.
>>
>> Is there an easy way to do this?
>>
>> On Feb 24, 9:59 pm, Tor Nordam  wrote:
>>> Thank you for your reply,
>>>
>>> Using the {% trans %} method is indeed what I intend to do. But the
>>> problem is how to set the language on a page basis, rather than as an
>>> installation-wide setting, or a user-selectable setting.
>>>
>>> On Feb 24, 6:55 pm, Timothy Kinney  wrote:
>>>
>>> > I believe you want to use the {% *trans* %} template 
>>> > method.http://docs.djangoproject.com/en/dev/topics/i18n/internationalization/
>>>
>>> > -Tim
>>>
>>> > On Wed, Feb 24, 2010 at 7:18 AM, Tor Nordam  wrote:
>>> > > I'm currently developing a project for making course webpages at my
>>> > > university. Essentially, each course would be an instance of the model
>>> > > Course, and each course would then get it's own webpage. However, as
>>> > > some courses are taught in Norwegian, and some in English, I want to
>>> > > use django's internationalisation framework, and I want to be able to
>>> > > set the language for each course separately. So I want to use
>>> > > different languages, but I don't want the person viewing the webpage
>>> > > to be able to select the language himself.
>>>
>>> > > As far as I can tell, the standard ways to set the language is either
>>> > > to use one setting for you entire project, or to select language based
>>> > > on the end users preferences. Is there an easy way to do what I want?
>>>
>>> > > --
>>> > > You received this message because you are subscribed to the Google 
>>> > > Groups
>>> > > "Django users" group.
>>> > > To post to this group, send email to django-us...@googlegroups.com.
>>> > > To unsubscribe from this group, send email to
>>> > > django-users+unsubscr...@googlegroups.com
>>> > > .
>>> > > For more options, visit this group at
>>> > >http://groups.google.com/group/django-users?hl=en.
>>
>> --
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To post to this group, send email to django-us...@googlegroups.com.
>> To unsubscribe from this group, send email to 
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at 
>> http://groups.google.com/group/django-users?hl=en.
>>
>>
>
>
>
> --
> ===
> 株式会社ビープラウド  イアン・ルイス
> 〒150-0012
> 東京都渋谷区広尾1-11-2アイオス広尾ビル604
> email: ianmle...@beproud.jp
> TEL:03-5795-2707
> FAX:03-5795-2708
> http://www.beproud.jp/
> ===
>



-- 
===
株式会社ビープラウド  イアン・ルイス
〒150-0012
東京都渋谷区広尾1-11-2アイオス広尾ビル604
email: ianmle...@beproud.jp
TEL:03-5795-2707
FAX:03-5795-2708
http://www.beproud.jp/
===

-- 
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: Set language on per page basis

2010-02-25 Thread Ian Lewis
In process_request you have access to the request object which knows
the current path (request.path). You can use that to determine which
language to show the page in.

Or if you are determining the language based on a url parameter you
can look at request.GET

Ian

On Thu, Feb 25, 2010 at 8:24 AM, Tor Nordam  wrote:
> After doing some further research, I have found the following:
>
> By writing a small piece of custom middleware, I can change the value
> of HTTP_ACCEPT_LANGUAGE. If I add this line to a process_request()
>
> request.META['HTTP_ACCEPT_LANGUAGE'] = 'no'
>
> then the webpage will be displayed with Norwegian translation.
> However, I want to set the language based on which page the user is
> trying to view, and process_request() doesn't know this. On the other
> hand, if I use process_view(), I am able to determine what the
> language should be, as process_view() gets passed for example the
> arguments from the url. However, when I add the same line as above to
> process_view(), nothing happens to the language.
>
> Is there an easy way to do this?
>
> On Feb 24, 9:59 pm, Tor Nordam  wrote:
>> Thank you for your reply,
>>
>> Using the {% trans %} method is indeed what I intend to do. But the
>> problem is how to set the language on a page basis, rather than as an
>> installation-wide setting, or a user-selectable setting.
>>
>> On Feb 24, 6:55 pm, Timothy Kinney  wrote:
>>
>> > I believe you want to use the {% *trans* %} template 
>> > method.http://docs.djangoproject.com/en/dev/topics/i18n/internationalization/
>>
>> > -Tim
>>
>> > On Wed, Feb 24, 2010 at 7:18 AM, Tor Nordam  wrote:
>> > > I'm currently developing a project for making course webpages at my
>> > > university. Essentially, each course would be an instance of the model
>> > > Course, and each course would then get it's own webpage. However, as
>> > > some courses are taught in Norwegian, and some in English, I want to
>> > > use django's internationalisation framework, and I want to be able to
>> > > set the language for each course separately. So I want to use
>> > > different languages, but I don't want the person viewing the webpage
>> > > to be able to select the language himself.
>>
>> > > As far as I can tell, the standard ways to set the language is either
>> > > to use one setting for you entire project, or to select language based
>> > > on the end users preferences. Is there an easy way to do what I want?
>>
>> > > --
>> > > You received this message because you are subscribed to the Google Groups
>> > > "Django users" group.
>> > > To post to this group, send email to django-us...@googlegroups.com.
>> > > To unsubscribe from this group, send email to
>> > > django-users+unsubscr...@googlegroups.com
>> > > .
>> > > For more options, visit this group at
>> > >http://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>



-- 
===
株式会社ビープラウド  イアン・ルイス
〒150-0012
東京都渋谷区広尾1-11-2アイオス広尾ビル604
email: ianmle...@beproud.jp
TEL:03-5795-2707
FAX:03-5795-2708
http://www.beproud.jp/
===

-- 
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: Can't explain this ImportError

2010-02-25 Thread Daniel Roseman
On Feb 25, 6:27 am, Adam Yee  wrote:
> Just started using haystack.  I've created an extended search form of
> SearchForm and have it located at /mysite/search/search_forms.py
>
> The import error happens in haystack.urls
>
> Traceback:
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/core/handlers/base.py" in get_response
>   92.                         request.path_info)
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/core/urlresolvers.py" in resolve
>   222.                     sub_match = pattern.resolve(new_path)
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/core/urlresolvers.py" in resolve
>   220.             for pattern in self.url_patterns:
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/core/urlresolvers.py" in _get_url_patterns
>   249.         patterns = getattr(self.urlconf_module, "urlpatterns",
> self.urlconf_module)
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/core/urlresolvers.py" in _get_urlconf_module
>   244.             self._urlconf_module =
> import_module(self.urlconf_name)
> File "/home/adam/stldata-djangosvn-2.6/lib/python2.6/site-packages/
> django/utils/importlib.py" in import_module
>   35.     __import__(name)
> File "/home/adam/stldata-djangosvn-2.6/mysite/haystack/urls.py" in
> 
>   3. from mysite.search.search_forms import CustomerSearchForm
>
> Exception Type: ImportError at /search/serviceorder/
> Exception Value: No module named search.search_forms
>
> Here is mysite.haystack.urls:
>
> from django.conf.urls.defaults import *
> from haystack.views import SearchView
> from mysite.search.search_forms import CustomerSearchForm # <---
>
> urlpatterns = patterns('haystack.views',
>     url(r'^serviceorder/$', SearchView(), name='haystack_search'),
> )
>
> It should be working.  All that's been added is the directory 'search'
> containing 'search_forms.py'.
> Permissions shouldn't be an issue either.  It's all in my Python
> path...I have no clue.

The search directory needs an __init__.py.
--
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-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.