Re: login_required for imported apps

2008-10-21 Thread bruno desthuilliers



On 20 oct, 01:33, "James Bennett" <[EMAIL PROTECTED]> wrote:
> On Sun, Oct 19, 2008 at 2:10 PM, bruno desthuilliers
>
> <[EMAIL PROTECTED]> wrote:
> > Indeed. But , OTHO, having to copy/paste a whole urls.py just to a add
> > a simple decorator on the view functions is not really DRY.
>
> Personally, I don't agree; writing code to do what you want, even if
> it starts with copy/pasting someone else's code, isn't really
> "repetition". Far too often on this list, people confuse "DRY" with
> "never write any code at all".

I don't think this last remark apply here. Of course, if what the OP
wanted was to customize the third-part app's urls on a per-url basis,
your answer would have been perfectly appropriate (and that's
certainly what I would have answered too). But the use case here is
somewhat different - it's about wrapping *all* the app's views with a
*same* decorator, without doing _any other change_ to the url's
patterns, args etc. I'm really surprised you don't see this as a
repetition...

"I hereby retrograde you to grade 36" !-)




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



Re: login_required for imported apps

2008-10-21 Thread bruno desthuilliers

On 21 oct, 16:40, Heather <[EMAIL PROTECTED]> wrote:
> I completely agree.  Even the middleware solution doesn't seem quite
> right as it will check each page/request.

Well, that's the whole concept of middlewares, isn't it ?-)

> I've been thinking about
> this a lot and I wonder if maybe the only part that should be reusable
> is the models?

Nope. We've been 'reusing' quite a few django apps so far, and while
there are indeed a couple spots where reusability could be improved
(my own grip is with views returning full responses - often I'd need
just the context and the template name), I can testify that I've
rarely seen such a level of reusability in a web framework.

Also a Django app doesn't have to provide any models (or views or
whatever). There are some app that only provides a set of
templatetags, filters and context_processors.

>I don't know.  But since there is no way (that I know
> of) to use inheritance for apps, apps seem to be sort of limiting.

I wouldn't say so. Getting at the right balance between simplicity and
flexibilty is indeed a difficult task. What you can reuse from a given
app depends on three factors: Django itself, how the app has been
written, and how you want to reuse it. I do think that Django would
benefit from a couple more hooks here and there, but this often
requires some "collaboration" from the app. Something *you* (and I)
can do then is to try and add this part to the apps you want to reuse
and contribute it back - chances are the authors will be grateful.

Same goes for Django itself FWIW (I mean, actively contributing), but
since it has much greater potential impact, we just can hope to have
each and any of our patches accepted - and that's mostly a
GoodThing(tm), since experience has proven that
EverythingButTheKitchenSink is not a sound design principle.


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



Re: template tags with variables as arguments

2008-10-22 Thread bruno desthuilliers

n 22 oct, 12:14, ramya <[EMAIL PROTECTED]> wrote:
> I am probably turning blind.. but I am still not able to figure out
> why string "value" is being passed instead of value "value"

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag

class FormatTimeNode(template.Node):
def __init__(self, date_to_be_formatted):
self.date_to_be_formatted =
template.Variable(date_to_be_formatted)

def render(self, context):
try:
actual_date = self.date_to_be_formatted.resolve(context)
return actual_date.strftime(YOUR_FORMAT_STRING_HERE)
except template.VariableDoesNotExist:
return ''



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



Re: Query

2008-10-22 Thread bruno desthuilliers

On 22 oct, 14:11, Anurag <[EMAIL PROTECTED]> wrote:
> Hello Gerard,
>
> Thank you so much for your suggestion. I have tried working in the
> direction suggested by you.
> The next step of difficulty that I find is that there are lot of
> materials available on the internet in this regard but I could not
> find some really good working examples and tutorials with respect to
> developing a Web-server using Python-CGI.

Why do you want to develop a web server ? Just use Apache.


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



Re: login_required for imported apps

2008-10-23 Thread bruno desthuilliers

On 22 oct, 23:46, Heather <[EMAIL PROTECTED]> wrote:
> That was a really good post - thanks :)  I know you don't *have* to
> use anything from the app you include or even *have* to include
> everything in an app you write.  But I think that I just have this
> idea in my head that I can't let go of that each part should be able
> to be inherited from - not just the models.

s/inherited from/reused/g !-)

Well, the fact is that models are ften the core of an application,
and, if well designed and implemented (IOW : no or extremely minimal
business logic in the views), easily reusable. Views and urls are
usually more project-specific, and let's not talk about templates.

(snip)

> > Well, that's the whole concept of middlewares, isn't it ?-)
>
> :P  Heh - but it's not such a good concept for checking if you are
> logged in.

Authentication is actually handled by a middleware, you know ?-)

Ok, I already expressed MVHO on this, which is that having a clean way
to apply a same decorator to a whole set of urls at once would be a
good thing. Now at least you have two or three (if you count the hack
I proposed) ways to do it - which is by all means better than none.
Believe me or else, I sometimes had to use *way* more *evil* hacks
(Lord forgive me...) to make some existing apps (not Django - nor even
Python FWIW) work together.

>  Or maybe I'm wrong and it's really not that much overhead.

It's mostly of the order of one additionnal function call and a couple
tests per request. Not optimal indeed, but if it happens to become a
problem, you can always trash your middleware and spent 10 minutes
rewriting your urls. Still not optimal indeed, but as far as I'm
concerned, that's something I can live with.



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



Re: Foreign Key Problem

2008-10-23 Thread bruno desthuilliers

On 23 oct, 19:53, cwurld <[EMAIL PROTECTED]> wrote:
> Hi,
(snip)
>
> When I run syncdb, the table is created (I can see it with MySQL
> Admin), but I get the following error:
>
> 
> C:\Documents and Settings\CCM\Desktop\pldev>python manage.py syncdb
> Creating table medical_xyzcontent
> Traceback (most recent call last):
(snip)
>   File "C:\Python24\lib\site-packages\MySQLdb\connections.py", line
> 35, in defaulterrorhandler
> raise errorclass, errorvalue
> _mysql_exceptions.OperationalError: (1005, "Can't create table '.\
> \cwurld_pldev\
> \#sql-f1c_3b.frm' (errno: 150)")
> ---
>
> Here is the sql generated by the model:
>
> BEGIN;
> CREATE TABLE `content_algoxxx` (
> `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
> `name` varchar(256) NOT NULL,
> `disease_id` integer NOT NULL
> )
> ;
> ALTER TABLE `content_algoxxx` ADD CONSTRAINT
> disease_id_refs_id_5c05e27d FOREIGN
>  KEY (`disease_id`) REFERENCES `medical_medicalbranch` (`id`);
> COMMIT;
>
> I do not know if it matters, but the old table that is being
> referenced is MyISAM, while the newly created table that contains the
> reference is InnoDB.

Not a MySQL expert (IOW : you'd better check it in MySQL manual), but
I bet this the cause of your problem. IIRC, there's a simple way to
convert a MyISAM table to InnoDB:

ALTER TABLE  ENGINE=INNODB;

(NB : not tested)



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



Re: Python Script bugs.

2008-10-23 Thread bruno desthuilliers

On 23 oct, 19:48, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hello everyone,
> I would like to know what isn't good in my script.

A couple things here and there.

But there's also something wrong with your whole post: there's nothing
Django-related in it. Python-related questions belongs to
comp.lang.python, not to a group about the web framework Django.

IOW : please post this to comp.lang.python (which you can access thru
google.groups too), and I'll answer there !-)

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



Re: from mysite.polls.models import Poll, Choice

2008-10-23 Thread bruno desthuilliers

On 23 oct, 11:14, tak <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am following the tutorial. One part I get confusion is the import
> statement including the project name. I am referring the last example
> of 1st tutorial.

It's indeed a pretty bad idea to refer to the project name in import
statements (as well as in a couple other places too FWIW), and I
defnitively fail to understand why it's documented that way.

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



Re: from mysite.polls.models import Poll, Choice

2008-10-23 Thread bruno desthuilliers



On 23 oct, 21:30, "James Bennett" <[EMAIL PROTECTED]> wrote:
> On Thu, Oct 23, 2008 at 1:47 PM, bruno desthuilliers
>
> <[EMAIL PROTECTED]> wrote:
> > It's indeed a pretty bad idea to refer to the project name in import
> > statements (as well as in a couple other places too FWIW), and I
> > defnitively fail to understand why it's documented that way.
>
> It's documented that way because it means we can have a tutorial that
> doesn't immediately dump import-path configuration issues onto people
> who are brand-new to Python;


Mmm... Well, I have few experience with, say, developping on exotic
platforms like Windows, but I never had any import-path related
problem skipping the projectname in imports (directs or not...) using
the builtin dev server. And I don't see how one could use a more
"deployment-oriented" configuration (Apache or whatever) without
having to deal with import path somehow. But I'm probably not really
representative of the average Django newcomer, so I may have miss
something obvious here...

> doing things the way the tutorial does
> them, everything automatically ends up on the Python path thanks to
> manage.py.

Except when one doesn't strictly follow the tutorial and use another
name for the project - which happened very recently !-)

> This means, of course, that there is a need for followup documentation
> which explains that this isn't always the best way to develop
> real-world apps (in just the same way as the tutorial shows several
> "wrong" ways to do things like template rendering, etc., before
> showing the "right" way). Any volunteers to write it?

Isn't it what you're already doing in your talks, slides, and on your
blog ?-) FWIW, me not understanding (so far at least) why the tutorial
is written that way also comes from the contradiction between the
tutorial and your own writings.

About volunteering to write an 'advanced' tutorial, as far as I'm
concerned, I'm not sure I'm a great tutorial writer - nor even a great
writer at all. Not being a native english speaker doesn't help
neither. But I'll happily work on translating this follow-up when
it'll comes out (and hopefully will contribute some code until then -
there are a couple things in the pipe).

Oh, and while we're at it: please don't take offense of my occasional
(and very mild) criticism of some minor point of the doc or whatever.
I really think Django is by now the best available Python web
framework, and probably one of the best web frameworks around whatever
the language (ok, a bit biased here...). Almost every points that
bugged me a couple years ago (pre-magic-removal, think it was 0.91 ?)
and made me look at alternatives has been solved since then, and you
guys clearly made a pretty good job, both on the technical and the
'marketing' side, and I'm sincerly *very* grateful you did.

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



Re: Getting a NameError: global name 'Lesson' is not defined

2008-10-28 Thread bruno desthuilliers

On 28 oct, 08:54, Daniel Strasser <[EMAIL PROTECTED]> wrote:
> Hi Daniel
>
> > This is why it's a bad idea to do from x import *. You should always
> > import the things you need explicitly, then you can tell what's going
> > wrong. Try doing
> > from schoolutil.lesson.models import Lesson
> > and see if it still goes wrong - or if you get a more informative
> > error message.
>
> Thanks for your tip. I've done this, now I'm getting the following
> error when I try to start the built-in development server:
>
> [EMAIL PROTECTED]:~/work/schoolutil$ python manage.py runserver
> Validating models...
> could not import in lesson.models
(snip)
> File "/home/daniel/work/schoolutils/../schoolutils/student/
> models.py", line 3, in 
> from schoolutils.lesson.models import Lesson
>   File "/home/daniel/work/schoolutils/lesson/models.py", line 7, in
> 
> class Lesson(models.Model):
>   File "/home/daniel/work/schoolutils/lesson/models.py", line 8, in
> Lesson
> student = models.ForeignKey(Student)
> NameError: name 'Student' is not defined

You have a circular reference between students.models and
lessons.models. The first want to import the second, which want to
import the first, etc... This just can't work.

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



Re: Getting a NameError: global name 'Lesson' is not defined

2008-10-28 Thread bruno desthuilliers

On 28 oct, 14:05, Daniel Strasser <[EMAIL PROTECTED]> wrote:
> > You have a circular reference between students.models and
> > lessons.models. The first want to import the second, which want to
> > import the first, etc... This just can't work.
>
> Thank you very much. I played around but I don't come to a solution. I
> think I'll try again. I just don't understand where this circular
> reference should be (Problem exists also if I remove them from one
> place or another)

Sorry, it appears I jumped to conclusion a bit too fast. Re-reading
the traceback:

1/ students.models imports lessons.models.Lesson
2/ lessons.models.Lesson try to reference students.models.Student -
which is not defined.

IOW : you don't _actually_ have a circular reference, but you would
have one if you tried to solve this NameError by import
students.models in lessons.models.

The solution is to declare the foreign key on Students using a
app_label.model_name string instead of a model object, ie (not
tested...) :

class Lesson(models.Model):
   # ...
   student = models.ForeignKey('students.Student')


cf 
http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey
for more on this.

A bit OT, but using a models.ForeignKey here means that a Lesson can
have *at most one* single student. I can't of course tell whether
that's ok for your app, but it sure looks a bit weird to me.

And while we're at it: given the existence of this foreign key, the
Student.lesson_hours method mentioned in your first post should make
use of it, ie:

class Student(models.Model):
  # ...
  def lesson_hours(self):
  return self.lesson_set.count()

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



Re: How to get value of query string in template

2008-10-28 Thread bruno desthuilliers

On 28 oct, 17:47, "yuanyun.ken" <[EMAIL PROTECTED]> wrote:
> Hi,I am a newbie to Django, and will use it in my latest project right
> away.
> now I encounter a little problem.
>
> How can I get value of query string in 
> template?http://localhost/mysite/login/?next=/mysite/product/

> My aim is to set next value in my login.html, if there is "next" in
> query string, use its value, otherwise set "next" a default value.
> 

If you add "django.core.context_processors.request" to your
settings.CONTEXT_PROCESSORS and use RequestContext objects in your
views, you'll have access to the request object in your templates.
Then it's just a matter of using the appropriate request attribute, in
your case probably something like request.REQUEST['next'] (or, since
it's in a template, {{ request.REQUEST.next }}

cf http://docs.djangoproject.com/en/dev/ref/request-response/ for more
on the request object.

Now note that if you use your own login view, this should be handled
in the view function itself, and passed to the template via the
context.

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



Re: mod_python calls an older script?

2008-10-30 Thread bruno desthuilliers

On 30 oct, 13:14, Alessandro <[EMAIL PROTECTED]> wrote:
> I'm getting weird errors about a script that I've changed recently (a
> template_tag).
> It's strange because it refers to a line that I've deleted, so I think
> it comes from some cache, but I cannot find nothing.

Did you restart Apache ?


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



Re: inspect a model's field's option's values

2008-10-30 Thread bruno desthuilliers



On 30 oct, 14:26, Mark Wolgemuth <[EMAIL PROTECTED]> wrote:
> It seems like I'm missing something, but here's what I'm trying to do:
>
> In creating a Form object, I'm setting size limit validation
> (max_length). I'd like to recover the value for that from the
> corresponding Model's Field's max_length. So basically I want a symbol
> lookup that will inspect in the options of a field I have defined for
> a model, without having an instance of the model, just it's type.
>
> This is to avoid the 2 having to share a common separately defined
> constant, or just using an integer that I have to coordinate in both
> places, or in place of always using auto forms.
>
> eg
>
> class MyModel(Model):
>  myfield = CharField(max_length=128)
>
> --
>
> class MyForm(Form):
>  myfield = CharField(max_length=**GET.FROM.MODEL**)
>

def get_model_field_option(model, field, option, default=None):
field = model._meta.get_field_by_name(field)[0]
return getattr(field, option, default)

class MyForm(Form):
 myfield = CharField(
 max_length=get_model_field_option(MyModel, 'myfield',
'max_length', 100)
 )

Caveat : Not sure it works on all possible options for all possible
fields - testing left as an exercise to to OP !-)

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



Re: How to get site's root path in Django

2008-10-30 Thread bruno desthuilliers



On 28 oct, 07:38, "yuanyun.ken" <[EMAIL PROTECTED]> wrote:
> Steve, Thanks for your expeditious reply.
> because our apache server includes other apps, I can not deploy my app
> to the root of the server.

This won't fix http://code.djangoproject.com/ticket/8906, but there's
at least one possible workaround in the meantime : use a sub domain
(ie subdomain.yourdomain.tld).



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



Re: Multiple types of output (HTML, JS), same view.

2008-10-30 Thread bruno desthuilliers



On 30 oct, 20:22, Joe Murphy <[EMAIL PROTECTED]> wrote:
> Hi,
>
> So I've got a bunch of views that I need to output in three forms:
> HTML with the site wrapper (header, footer etc.), HTML without the
> site wrapper, and JS. The templates are really, really similar.
>
> I'm thinking of using a url pattern like:
> r'^blog/blah(?P[-\.\/\w]+)$'
> so that blog/blah/ would return the HTML with site wrapper, blog/
> blah.html would return the HTML without wrapper, and blog/blah.js
> would return the javascript.
>
> Doing this means I'm putting logic in all the views that need this
> functionality -- and, then, building slightly-different templates for
> each of the three outputs.
>
> There's something about this that seems wrong, but I can't imagine a
> cleaner solution. Any thoughts?

I've been thinking about this recently (going to have a working
solution for the same problem pretty soon...). The cleanest solution
I've came with so far is to make the view function only return a
context, then wrap the view function in a decorator that takes care of
rendering, based on request informations. The points I'm yet really
happy with are:
- how to tell the rendering decorator what we want to render
- how to avoid template duplication for 'full' rendering and 'partial'
rendering

wrt/ first point, the simplest solution IMHO is to pass a render=json
or render=partial argument in the query string (default being
rendering the 'full' page). My main problem is with second point. I
have a working scheme using two templates, the 'full' one doing an
include of the 'partial' one. This should work, but I still don't like
having two distinct templates.

I don't have the (prototype) code at hand here, but from memory it's
something like:

class render_with(object):
def __init__(self, partial, full):
self.partial_template_path=fragment
self.full_template_path = full

def __call__(self, view):
self.view = view
return self.render

def render_json(self, request, context):
# this is in djangosnippets IIRC
return JsonResponse(context)

def render_partial(self, request, context):
return render_to_response(
self.partial_template_path,
context,
context_instance=RequestContext(request)
)

def render_full(self, request, context):
context['partial_include'] = self.partial_template_path
return render_to_response(
self.full_template_path,
context,
context_instance=RequestContext(request)
)

def render(self, request, *args, **kw)
context = self.view(request, *args, **kw)
#  the view can still return a response object
if isinstance(context, HttpResponse):
return context
# ok, it's really a context
render_mode = request.REQUEST.get('render', 'full')
render_method = getattr(self, 'render_%s' % render_mode)
return render_method(request, context)


Then you use it that way:

# myview.py
@render_with(partial='mypartial.html', full='myfull.html')
def myview(request, somearg):
   return dict(yadda='yadda')

# mypartial.html

Yadda : {{ yadda }}


# myfull.html
{% extends 'base.html' %}

{% block stuff %}
{{ yadday }} stuff here
{% endblock %}

{% block main %}
{% include partial_include %}
{% endblock %}

{% block other %}
other {{ yadda }} stuff here
{% endblock %}

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



Re: Django's decoupling apps but template should couple them together, right?

2008-11-03 Thread bruno desthuilliers



On 3 nov, 03:56, Steve Holden <[EMAIL PROTECTED]> wrote:
(snip)
> You might also want to look into ContextManager objects, which are a way
> of providing information to all pages.

I assume you meant 'Context processors' ?-)


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



Re: Beginner on Django and web developing

2008-11-03 Thread bruno desthuilliers

On 3 nov, 17:38, "Airton Arantes" <[EMAIL PROTECTED]> wrote:
> Hello folks, I have aready used python only in desktop. About 1 a week
> ago I installed the Django 1.0 on Fedora 9. I wonder about the
> djangobook, its version is 0.96 or 1.0?
>
> I don't know nothing about web programming but I'm studying a lot.
> Can I read this link[1] to learn better about django?
>
> [1]http://www.djangobook.com/en/1.0/

Hi.

If you installed django 1.0, yes, indeed, you want djangobook 1.0 too.
But note that this won't be enough to understand web programming in
general - for this, you need at least some understanding of the HTTP
protocol.


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



Re: access request.user in class Meta

2008-11-03 Thread bruno desthuilliers

On 1 nov, 23:57, Merrick <[EMAIL PROTECTED]> wrote:
> I am trying to dynamically generate a form, the fields will vary if
> the user is logged in. Here is where I am so far
>
> forms.py
> ==
> class LinkForm(ModelForm):
>
> def __init__(self, *args, **kw):
> self.request = kw.pop('request')
> super(LinkForm, self).__init__(*args, **kw)
>
> class Meta:
> model = Link
> if self.request.user:
> exclude = ['ip_address', 'timestamp', 'user', 'method', ]
> else:
> exclude = ['ip_address', 'timestamp', 'user', 'method',
> 'notes', 'private_stats',]

This is a Python problem, not a Django problem. I strongly suggest you
take time to learn Python.


When the 'class Meta:' statement is eval'd, the LinkForm class doesn't
even yet exists - so there's no hope an instance of LinkForm could
exists.

FWIW, there's nothing special with name 'self' in Python. Instance
methods receive the current instance as first argument, and by
convention, this argument is named 'self', but you could name it
'ekky_ekky_ekky_ekky_zBang' just the same.

To make a long story short, what you're trying to do just cannot work
- or at least, not that way.


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



Re: Beginner on Django and web developing

2008-11-04 Thread bruno desthuilliers



On 4 nov, 03:02, "DULMANDAKH Sukhbaatar" <[EMAIL PROTECTED]> wrote:
> > Hello folks, I have aready used python only in desktop. About 1 a week
> > ago I installed the Django 1.0 on Fedora 9. I wonder about the
> > djangobook, its version is 0.96 or 1.0?
>
> book's version is 1.0, but written for 0.96.

oops, my bad :(


Sorry, I should have doubled-checked this before answering


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



Re: Design question : best way to show 1 .. N different categoried items

2008-11-05 Thread bruno desthuilliers

On 4 nov, 23:54, John M <[EMAIL PROTECTED]> wrote:
> i have a model for status reports:http://dpaste.com/88760/
>
> The report has 1-N bullet Points, each bullet Point has a category.
>
> What I want to figure out, whats my best way to display this in a
> template, given that the category list is flexible.  I mean, a report
> might have 1 or more categories.
>
> I'd like to then group the bullet points for each category on the
> site.

Not tested, but this should work AFAICT:

# myview.py
def myview(resquest, report_id):
   report = get_object_or_404(Report, pk=report_id)
   context = dict(
  report = report,
  bullets =
report.bulletpoint_set.all().select_related('category')
   }
   return render_to_response('mytemplate.html', context)

# mytemplate.html
{% regroup bullets by category as grouped_bullets %}

  {% for group in grouped_bullets %}
  
{{ group.grouper }}

{% for bullet in group.list %}
  {{ bullet }}
{% endfor %}
  
  {% endfor %}


cf http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

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



Re: setting value of a ModelForm field through Javascript

2008-11-06 Thread bruno desthuilliers


On 6 nov, 13:38, limas <[EMAIL PROTECTED]> wrote:
> hello
>
> please help me...
> can i set the value of a ModelForm field ,ie a text box, using
> javascript.

This is totally unrelated to Django and ModelForms. javascript runs on
the browser, *after* the whole page containing the form has been sent
by the server. IOW, at this stage, all you have is a plain old HTML
form. For questions related to client-side HTML form (or whatever)
scripting, please post on comp.lang.javascript (and possibly, learns a
bit of javascript before...).

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



Re: setting value of a ModelForm field through Javascript

2008-11-08 Thread Bruno Desthuilliers

limas a écrit :


Limas, please answer on the group, not privately


>> This is totally unrelated to Django and ModelForms. javascript runs on
>> the browser, *after* the whole page containing the form has been sent
>> by the server. IOW, at this stage, all you have is a plain old HTML
>> form.
> 
> Bruno,
> First of all thank you for your comment.
> But i have some doubts.

You should not !-)


> 1) The browser is receiving the form as a single bulk with fieldname
> and control, i think it is as an array.

What the browser receive is an HTTP response. IOW : text. You'll find a 
very exhaustive description of what's an HTTP response in the HTTP rfc:

http://www.w3.org/Protocols/rfc2616/rfc2616.html

> Then how can i set the value of a single textbox placed in between a
> big form?

for which definition of "setting the value" ?

If what you mean is : "how do I change the "value" attribute of an HTML 
form on the browser using Javascript", then you're definitively on the 
wrong newsgroup.

> If i use a loop like below
> {% for field in form %}
> {{ field.name }}  {{ field }}
> {% endfor %}

You'd getter better results using form.as_p IMHO.

> The row field name is displaying rather than the verbose name.

Of course, that's what you asked for.

> 2) Handling form with javascript is through there name attribute of
> each controlls.

Not necessarily, but that's indeed the most common case.

> When we using ModelForm, how can we get the "name" value for each
> controll?

How would this information help you setting the value using javascript ?

> Hop you understand what i meant.
> Sorry for my poor English...

Well, hope you'll pardon me, but I don't know for sure if you are 
confused wrt/ how HTTP work or if it's just a language problem. If you 
really feel your English is too limited to clearly explain your problem, 
  you should perhaps find someone around you that may help you rewriting 
your question.



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



Re: Recursive function

2008-11-12 Thread bruno desthuilliers

On 12 nov, 14:25, gontran <[EMAIL PROTECTED]> wrote:
> On 12 nov, 13:22, Steve Holden <[EMAIL PROTECTED]> wrote:
>
> > gontran wrote:
(snip - about using templates instead of building html in python code)

> > > -> I'm using this function in a custom tag to build a menu
>
> > And is there a rule that says you can't do that using templates?
> > Hello Steve,
>
> Maybe I'm wrong but I want to display this menu in all pages of my
> site, so by using a custom tag, I can display my menu without having
> to import my model in my different views.

This doesn't prevent you from using a template to do the html
rendering:

class MyNode(Node):
def render(self, context):
template = get_template('path/to/mytemplate.html')
context.push()
try:
context['foo'] = 'bar'
return template.render(context)
finally:
context.pop()

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



Re: Recursive function

2008-11-12 Thread bruno desthuilliers

On 12 nov, 14:56, gontran <[EMAIL PROTECTED]> wrote:
> Could you be more explicite because I don't understand everything and

I thought it was explicit enough. A custom tag is usually made of a
parser function and a rendering node (cf relevant part of django's
documentation), so I gave you a snippet showing how to use a template
_from within a custom tag's node_.

> why not using my custom tag?

Who said you shouldn't use it ???




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



Re: Recursive function

2008-11-12 Thread bruno desthuilliers

On 12 nov, 09:22, gontran <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I've got a problem with a recursive function:
> in my model, I have a class named myClass: each object in my class has
> an id, a parentId, and a name.
> I want to make a list of all my objects that looks like this:
> 
> object1
> object2
> object3
> 
> object4
> object6
> 
> object5
> ...
> 
>
> So I wrote a function displayListObject():
> def displayListObject(parentId, displayString):
> displayString += ''
> elements = myClass.objects.filter(parentId=parentId)
> for element in elements:
> if  myClass.objects.filter(parentId=page.id):
> displayString += '' + page.id + ''
> displayListObject(page.id, displayString)


(snip)

> Any idea to fix this?

Yes : don't pass displayString as an argument, just use the return
value of the function, ie:


def displayListObject(parentId):
displayString = ''
elements = myClass.objects.filter(parentId=parentId)
for element in elements:
if  myClass.objects.filter(parentId=page.id):
displayString += '' + page.id + ''
displayString += displayListObject(page.id, displayString)
else:
displayString += '' + page.id + ''
displayString += ''
return displayString


The root of your problem is that python strings are immutable. So the
augmented assignment ('+=') rebind the name displayString to a new
string object. And since parameters names are local to the function,
this rebinding (hopefully) only affect the local namespace.

Now, and while this is none of my problems, I'd seriously question the
decision of building html that way. This would be better done using
templates IMVHO.

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



Re: Categorisation

2008-11-12 Thread bruno desthuilliers

On 11 nov, 21:41, coderb <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I'm having trouble getting my head around how to set up my data entry
> and queries, so that a listing/detail entry is categorised properly.
>
> firstly, my models look like this:
>
> class Category(models.Model):
> name  = models.CharField(max_length=100, unique=True)
> slug  = models.SlugField(max_length=100, unique=True)
> parent= models.ForeignKey('self',blank=True,null=True)
> ...etc..
>
> class Entry(models.Model):
> categories= models.ManyToManyField(Category)
> title = models.CharField(max_length=200)
> description  = models.TextField()
> etc..
>
> I'm trying to achieve this:
> Each entry can be linked to one or more categories
> When browsing/searching categories, I want all child entries (from
> next level down to lowest level) to be listed in one result.

I assume that what you want is to display all entries for a given
category *and* its children ?


> The manually selected categories from the list-box are obviously the
> only ones linked to the Entry, so when I someone browses/searches
> listings by category, they will not automatically get the all child
> Entries.
>
> my view filter to get Entries looks like this:
> entry_list=Entry.objects.filter(categories__slug=this_cat,
>
> theoretically I can think of two options:
> 1. At the time an Entry is added/edited - I need to have a routine
> that rebuilds the many-many link table so that  the Entry is linked
> directly to each parent, of all selected categories.  Although this
> would cause other issues, like duplicated results on the search, how
> to display all linked categories on the detail page, changing the
> model to have a separate many-to-many link table  etc..

Wrong solution IMHO

> 2. The other option, sounds better to me, is the way the browse/search
> query is built, when a user is browsing a top level category, I need
> to somehow create a left/outer join or union so that all child
> categories are linked with their Entries.

Which is indeed the way to go.

> But since I do not know the
> depth of cateogories,  this sounds like quite a complex bit of code to
> dynamically build the sql, although it might be quite simple using
> some kind of custom method in the model or something.. (but would this
> query cause a performance issue.)

The "adjacency list" pattern you used for the Category model, while
the most obvious one, can indeed become somewhat costly when you want
to retrieve ancestors or childrens. Now there are other ways to handle
hierarchies in SQL. You may want to have a look here for other
options:

http://code.google.com/p/django-treebeard/

Anyway, a simple Q&D solution is to
1/ get a list of categories ids for the current category and it's
children (this should be a method of your Category model)
2/ filter your entries on this list, using the 'in' operator

This will at least reduce the number of queries on the Entry 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-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Turning key=value1&key=value2&key=value3 into a list

2008-11-12 Thread bruno desthuilliers



On 12 nov, 21:44, Peter Bengtsson <[EMAIL PROTECTED]> wrote:
> If I publishhttp://someurl/myview?foo=1&foo=2&foo=3
>
> How do I turn this into foo = ['1','2','3']?

foo = request.GET.getlist('foo')

http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Trouble extending User

2008-11-12 Thread bruno desthuilliers



On 12 nov, 22:05, joshuajenkins <[EMAIL PROTECTED]> wrote:
> So I'm doing basically what Chapter 12 references in the djangobook on
> how to add a profile to Users.
>
> All is well in terms of adding users and pulling out the profile with
> get_profile() on single users, but when I'm trying to pull out all
> Users in my view and append the profile data, I'm lost.
>
> Before I had profiles I did this:
> all_users = User.objects.all()
>
> Now I need the extra fields and I'm not sure if there's a graceful way
> to do it like that or if I'm going to have to cycle through each user
> and append the data, which is definitely not how I would like to do
> this.
>
> Any thoughts?

User.get_profile doesn't take any arg, so you can call it from the
template. IOW : you just don't need to "append the data" (err...) from
within the view.


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



Re: Dynamic Paths for File Uploads

2008-11-13 Thread bruno desthuilliers



On 13 nov, 01:52, Tim <[EMAIL PROTECTED]> wrote:
> Just to add some more information - I have been messing around with
> making the upload_to a callable, but I still have the same problem in
> that I need to build the path based on information that only exists
> during runtime (that is, a call to a view). Basically, I don't know
> the value of upload_to until I'm in the view. Ideally I'd like to do
> the following actions in views.py:
>
> - import the model
> - set the upload_to value
> - save the file
>

Don't know if this can apply to your problem, but here's what we did:

# models.py

def get_upload_path(instance, filename):
# store images under MEDIA_ROOT/myimages//filename
return os.path.join("myimages", instance.owner.username, filename)

class Image(Model):
"""
Media-Image
"""
owner = models.ForeignKey(User)
image_file = ImageField(
upload_to=get_upload_path
)
# etc...


Then it's just a matter of passing the request.user to the model (or
to the form) within the view.

HTH




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



Re: Basic concept for templatetag using node and parser

2008-11-13 Thread bruno desthuilliers

On 13 nov, 11:13, sugi <[EMAIL PROTECTED]> wrote:
> Hi
>
> Can any one explain template tag with sample example.

No problem :
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

To make a long story short: the parser function is called at
"compilation" time, and must return a Node object. The result of the
"compilation" phase is an in-memory tree of Node objects. Then this
tree is traversed, each Node being called with the current context,
and the return value being concat to build the final HTML (or
whatever) content.


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



Re: Basic concept for templatetag using node and parser

2008-11-13 Thread bruno desthuilliers

On 13 nov, 12:33, "suganthi saravanan" <[EMAIL PROTECTED]>
wrote:
> Thanks bruno...but i have already read the documentation for the Custom
> template tag.
>
> I need simple example for  more clarification

There's already one, and you can find quite a few others in third-part
dhango apps, or even in Django's source code ('builtin' templatetags
are written the exact same way).

> can you help me.

Not unless you get more specific about what you have trouble with.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Improvement: documentation example for extra Manager methods

2008-11-13 Thread bruno desthuilliers

On 13 nov, 14:53, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am building a custom Manager for adding extra methods that return
> filtered querysets.
> I believe this is a common case for custom Managers.

Yes, indeed.

> Digging into the documentation [1], the only example emphasises on the
> ability to return anything from a Manager method. However, I miss a
> standard example for methods that DO return a filtered queryset.



> I am still struggling with my custom Manager method, which raises an
> error in my project ('NoneType' object has no attribute '_meta'). Any
> hint?

Not without the relevant source code and the full traceback. Sorry, my
crystall ball is out for repair.

> My custom Manager method is like this:
>   def active(self):
> return self.get_query_set().filter(status=STATUS_ACTIVE)

or more simply:

  return self.filter(status=STATUS_ACTIVE)

But this won't solve your problem anyway.

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



Re: Basic concept for templatetag using node and parser

2008-11-14 Thread bruno desthuilliers



On 14 nov, 12:29, "suganthi saravanan" <[EMAIL PROTECTED]>
wrote:
> Here i have customized the class

???

> in the templatetags folder and i have
> render too.

???

> Using the function also i have called the parser function and
> return the node object...
>
> I have created the template also
>
> How to call in the urls.py

Err... template tags are used *within* templates. They have nothing to
do with urls.py. What are you trying to do, exactly ???



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



Re: Beginner desperately seeking Django experts.

2008-11-16 Thread bruno desthuilliers



On 15 nov, 07:54, Innergy <[EMAIL PROTECTED]> wrote:
> Thanks for reading my question.  I may not be asking all the right
> questions.
>
> I am looking for a fast way to build a ecommerce site with many of the
> qualities of threadless.com.  I was told Django is an excellent
> language

Django is not a language, it's a framework. The language is named
Python. (NB : just like Rails is a framework built on the Ruby
language).

> and allows for rapid fast implementation.
>
> My back ground is not in development. So I am agnostic. I am currently
> leaning towards Ruby for my project.  How does Django compare to
> Ruby?  Is Django faster to develop in? Is it as stable as Ruby?

I assume you mean Rails. But anyway : wrt/ frameworks (Rails vs
Django), both are of equal quality and stability - even if  Django has
IMHO a big plus : the automatic (yet fully customizable) admin
interface. wrt/ languages (Ruby vs Python), both are pretty good
languages, but Python has a somewhat better implementation, and a way
bigger community (mostly because it's older FWIW).




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



Re: How to access the request object in a decorator

2008-11-17 Thread bruno desthuilliers

On 17 nov, 10:02, TH <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I wanted to redirect a logged in user if he access certain page. For
> example i do not want the user to access registration page if he is
> logged in.
>
> A simple way to do this is:
>
> def register(request):
> if request.user.is_authenticated():
> return HttpResponseRedirect('/
> some_nice_page_for_logged_in_user')
> ...
>
> The problem is i have lot of pages that only anonymous user can
> access. So i wanted to write a decorator so that i can do something
> like that
>
> @anonymous_only
> def register(request):

A "decorator" is just a function (or any other callable) that takes a
function as argument and returns a function (or any other callable).
The @decorator syntax is only syntactic sugar.

In most cases, the returned function is just a wrapper around the
decorated one, and this is obviously what you want:

def anonymous_only(view):
  # 'view' is the view function to decorate
  # since we decorate views, we know the first parameter
  # is always going to be the current request
  #
  # '_wrapper' is the function that will be used instead
  # of 'view'.
  def _wrapper(request, *args, **kw):
# here we can access the request object and
# either redirect or call 'view'
if request.user.is_authenticated():
  return HttpResponseRedirect('/page_for_logged_in_user')
return view(request, *args, **kw)

  # this part is not mandatory, but it may help debugging
  _wrapper.__name__ = view.__name___
  _wrapper.__doc__ = view.__doc__

  # and of course we need to return our _wrapper so
  # it replaces 'view'
  return _wrapper


Note that this example assume you always want to redirect to the same
page if the user is logged in, which might not be the case. Things get
a bit more complicated if you want your decorator to takes the
redirection url as param, since we'll then need one more indirection,
IOW : a function that takes an url and returns a function that takes a
function and returns a 'wrapper':

def anonymous_only(redirect_to):
   def deco(view):
 def _wrapper(request, *args, **kw):
   if request.user.is_authenticated():
 return HttpResponseRedirect(redirect_to)
   return view(request, *args, **kw)

 _wrapper.__name__ = view.__name___
 _wrapper.__doc__ = view.__doc__
 return _wrapper

   return deco


Then you use it that way:

@anonymous_only('/page_for_logged_in_user')
def register(request):
# code here

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



Re: Items tree in Django

2008-11-17 Thread bruno desthuilliers

On 17 nov, 11:46, Fabio Natali <[EMAIL PROTECTED]> wrote:
> Hi everybody out there! :-)
>
> I have to cope with a few hundreds item tree/hierarchy in my Django
> project. Specifically, I'll have 500 hundreds leaves in a 3-levels
> tree with a dozen branches.
>
> I won't need much writing over this tree, I'll just need to read it
> and show data in a drop down menu.
>
> I've been told to use django-treebeard

That's what I was about to suggest !-)

> or django-mptt to speed up
> things, but I wrote down a first draft on my own:
>
> class Node(models.Model):
> name = models.CharField(max_length=50)
> parent = models.ForeignKey('self')
>
> class Product(models.Model):
> name = models.CharField(max_length=50)
> parent = models.ForeignKey(Node)
> [some more info here]
>
> The point is, how can I create the root of my tree? Should I add some
> "blank=True, null=True" properties to my Node model? So to have:
>
> class Node(models.Model):
> name = models.CharField(max_length=50)
> parent = models.ForeignKey('self', blank=True, null=True)
>
> And then consider the "null-parented" node as the root one?

That's the canonical solution when using the adjacency list pattern,
yes.

> Does my code make any sense? Do you think it will turn out as too slow
> for my hierarchy?

If you are really confident that your hierarchy will never grow deeper
than three levels, the above solution might be good enough. But it's
still less efficient than the materialized path or the nested sets
patterns when it comes to reading a whole branch.

> Should I better rely on django-treebeard or
> django-mptt?

Well... I'm not sure there's any clearcut answer here. If you have
enough time, you may want to do a couple benchmarks on representative
data and use cases.

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



Re: Python and/or django book

2008-11-17 Thread bruno desthuilliers

On 17 nov, 20:53, prem1er <[EMAIL PROTECTED]> wrote:
> Just trying to figure out what the best book to purchase for a
> newcomer to Django and python.

Depends on your background...  But if you have prior experience with
1/ another (preferably but not necessarily object oriented) language
and 2/ server-side web programming, the 'official' tutorials and docs
might be enough.


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



Re: Passing values to template

2008-11-17 Thread bruno desthuilliers



On 17 nov, 16:45, Alex Jonsson <[EMAIL PROTECTED]> wrote:
> Hey guys,
>
> I have a news application that I would like some help with.
>
> My view generates a list with objects mixed with dictionaries with two
> objects.
(snip)
> Or is there a better way of doing this other
> than mixing objects and dictionaries in the list?

Others already gave you practical answers, so this will be mostly a
more general ('conceptual' ?) advice: don't mix heterogenous data
(objects, whatever) in a list. If you have a compelling reason (ie :
ordering) to have heterogenous data, wrap them all in a same 'meta'
data structure.

David's answer is one possible solution, but it still requires 'type'
testing on each item of the collection. The (potential) problem with
this solution is that each new 'type' will require a modification of
the template. A more OO solution is to use another level of
indirection, ie: make your view return a list of {data:whatever,
template:'path/to/specifictemplate'} dict, so the template's loop
doesn't have to make any test:

{% for stuff in mylist %}
  {% with stuff.data as object %}
 {% include stuff.template %}
  {% endwith %}
{% endfor %}

This might be overkill for your concrete use case, and (like any
solution based on indirection FWIW) has some impact on performances,
but it's often worth the price when it comes to maintainance.

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



Re: Can't access the development server

2008-11-17 Thread bruno desthuilliers

On 17 nov, 14:14, Ben <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm completely new to python and Django, although fairly familiar with
> programming and web servers in general.
>
> I'm struggling to get Django up and running, at the moment, and I'd be
> really grateful if someone could help.
>
> I'm following this tutorial, after having successfully installed
> Django:
>
> http://docs.djangoproject.com/en/dev/intro/tutorial01
>
> I start the development server using:
>
> python manage.py runserver
>
> which seems to work ok:
>
> Validating models...
> 0 errors found
>
> Django version 1.1 pre-alpha SVN-9479, using settings
> 'prototype.settings'
> Development server is running athttp://127.0.0.1:8000/
> Quit the server with CONTROL-C.
>
> In fact, on that server, I can telnet to the development server fine.
> However, if I try to access it in my browser, nothing happens.
(snip)
> As far as I know there are
> no firewalls between me and the server (it's a shared hosting server
> with Site5).

Err... If I get you right, you're not running the dev server process
on your own machine ? If so, it looks like your familiarity with web
servers is lacking one important point: 127.0.0.1 is the loopback IP
address - IOW, it's an  IP address that connect one machine *to
itself* !-).

Try starting the dev server with the real IP address for your server,
and you should be fine, ie if your server machine IP is
AAA.BBB.CCC.DDD, start the dev server with

python manage.py AAA.BBB.CCC.DDD:8000

> I'm assuming that when I try to connect to port 8000 this will go
> directly to the development server and apache settings etc should be
> irrelevant?

To make a long story short: yes. (To make it a bit longer : apache
could be configured to  listen to port 8000, but then you couldn't run
any other process listening on this same port...)


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



Re: Default custom settings

2008-11-18 Thread bruno desthuilliers

On 18 nov, 03:29, mdnesvold <[EMAIL PROTECTED]> wrote:
> I'm writing an application that adds several app-specific settings. As
> I'm developing, I'm just adding them to the end of my settings.py
> file:
>
> MY_APP_FOO = 'foo'
> MY_APP_BAR = (
>'bar',
>'bam',
>'baz',
> )
> # and so on
>
> So far, I have eleven such settings over 21 lines and expect to add
> several more. I don't want to make any new users of this app cut-and-
> paste a block of code into their settings.py just to get the app
> working, especially since some are "advanced settings" and will rarely
> be changed. Is there any way to specify default values for these
> settings? That way, my app requires less work to set up and still
> allows flexibility.

What I usually do is to provide default values in the relevant app's
module(s), ie:

# myapp.models.py
from django.conf import settings
MYAPP_FOO = getattr(settings, "MYAPP_FOO", "default_foo")

# etc...


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



Re: Multiple types of output (HTML, JS), same view.

2008-11-18 Thread bruno desthuilliers

On 18 nov, 21:29, "David Zhou" <[EMAIL PROTECTED]> wrote:
> On Thu, Oct 30, 2008 at 4:08 PM, bruno desthuilliers
>
> <[EMAIL PROTECTED]> wrote:
> > rendering, based on request informations. The points I'm yet really
> > happy with are:
> > - how to tell the rendering decorator what we want to render
> > - how to avoid template duplication for 'full' rendering and 'partial'
> > rendering
>
> > wrt/ first point, the simplest solution IMHO is to pass a render=json
> > or render=partial argument in the query string (default being
> > rendering the 'full' page). My main problem is with second point. I
> > have a working scheme using two templates, the 'full' one doing an
> > include of the 'partial' one. This should work, but I still don't like
> > having two distinct templates.
>
> I'd need to check Django's template code to see if this is possible,
> but one possibility is to give the decoration a "block" parameter, to
> render a specific block from a template.  So you could have something
> like:
>
> @render_view('js', 'template.html', block='js_block')
> def view:
>pass

I've been investigating and doing a bit more work on this point since
then, and indeed there are ways to only render a given block from a
template. I have nothing worth being posted so far (too much to do on
other, more fundamental features for our current project), but we
should soon come to the point where we'll have to make this work. I'll
post back then with possibly improved solutions.


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



Re: Default custom settings

2008-11-18 Thread bruno desthuilliers

On 18 nov, 16:43, mdnesvold <[EMAIL PROTECTED]> wrote:
> On Nov 18, 2:15 am, bruno desthuilliers
>
> <[EMAIL PROTECTED]> wrote:
> > What I usually do is to provide default values in the relevant app's
> > module(s), ie:
>
> > # myapp.models.py
> > from django.conf import settings
> > MYAPP_FOO = getattr(settings, "MYAPP_FOO", "default_foo")
>
> > # etc...
>
> The problem with using getattr(settings, 'MY_SETTING', default) is
> that I'd have to specify the default value every time I access the
> value;

Nope. You just do this once at the top of the module using these
settings, and then only use the module-level (pseudo)constant. And if
you have more than one module  depending on this setting, you just put
all these (pseudo)constants definitions in a separate package-wide
setting file that you import where needed.


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



Re: Custom template tag problem: "No module named models"

2008-11-18 Thread bruno desthuilliers



On 15 oct, 09:19, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
> On Wed, 2008-10-15 at 01:08 -0700, bruno desthuilliers wrote:
>
> [...]
>
> > FWIW, I just don't understand why each an every example in the
> > Django's manual insists on using this projectname.appname scheme.
>
> "Insists" is a rather strong word, since nowhere does it say "do this or
> else".

(just reading this post now - a bit late, but...)

Malcom, I'm not a native English speaker, so I sometimes  fail to
convey the exact nuance. Please bear with me !-)


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



Re: Passing values to template

2008-11-18 Thread bruno desthuilliers



On 18 nov, 19:54, Ross Dakin <[EMAIL PROTECTED]> wrote:
> > Others already gave you practical answers, so this will be mostly a
> > more general ('conceptual' ?) advice: don't mix heterogenous data
> > (objects, whatever) in a list. If you have a compelling reason (ie :
> > ordering) to have heterogenous data, wrap them all in a same 'meta'
> > data structure.
>
> Agreed. The simplest solution might be to just wrap your single
> objects in dictionaries:
>
> my_list = [
> {single_object},
> {'one', 'two'},
> {single_object},
> {'one', 'two'},
> ]

Err... Actually, this is not correct Python code and will raise a
SyntaxError. Also, just wrapping objects in dicts wouldn't solve the
problem of having to test and branch in the template - which is
exactly the problem polymorphic dispatch is trying to avoid.



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



Re: dynamic method calling

2008-11-24 Thread bruno desthuilliers

On 22 nov, 14:05, Ivan Sagalaev <[EMAIL PROTECTED]> wrote:
> Chris wrote:
> > try:
> > push = getattr(self, 'get_%s_content' % self.name)
> > except AttributeError:
> > raise "Method does not exist"
> > if callable(push):
> > push(**argv)
>
> There are a couple of problems with this code.
>
> 1. It's more readable to call hasattr than to catch an exception from
> getattr:

Actually, most python programmer will favor the getattr solution, at
least if they expect the given attribute to exists as "the normal
case".

> if hasattr(self, 'get_%s_content' % self.name):
>  raise Exception('Method does not exists')

logical bug above.

> if callable(push):

NameError here.

>  push(**argv)


> 2. Raising another exception instead of the standard AttributeError
> looks suspicious. Why are you doing it?
>
> 3. Exceptions should be instances of class Exception, not strings.
>
> 4. The code silently does nothing when attribute is here but is not
> callable.

Agree on these 3 points.


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



Re: dynamic method calling

2008-11-24 Thread bruno desthuilliers

On 22 nov, 13:07, "Steve McConville" <[EMAIL PROTECTED]>
wrote:
> > On Sat, Nov 22, 2008 at 2:38 AM, Chris <[EMAIL PROTECTED]> wrote:
> >> Hello everyone,
> >> I have a quick python question. Is they a better way of calling a
> >> method dynamically then what I have below? Is there a more elegant
> >> approach? Thanks in advance.
>
> try:
> self.__class__.__dict__[method_name](self, argument)
> except KeyError:
> #handle missing method
> pass
>
> is pretty much equivalent to
>
> try:
> getattr(self, method_name)(argument)
> except AttributeError:
> # handle missing method
> pass

It isn't. In the first case, you only lookup the class dict, while the
second takes inheritence, per-object methods, __getattr__ hooks etc
into account.

> Don't know if anyone would consider it more elegant

Definitively not.


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



Re: dynamic method calling

2008-11-24 Thread bruno desthuilliers


On 22 nov, 02:38, Chris <[EMAIL PROTECTED]> wrote:
> Hello everyone,
> I have a quick python question. Is they a better way of calling a
> method dynamically then what I have below? Is there a more elegant
> approach? Thanks in advance.

> try:
> push = getattr(self, 'get_%s_content' % self.name)
> except AttributeError:
> raise "Method does not exist"


If that's how you handle the AttributeError, you'd be better doing
nothing - at least you'd get a meaningfull (at least for éa
developper) error message, and an helpful traceback.



> if callable(push):
> push(**argv)

There's no one-size-fits-all answer here. It depends on what you
consider to be 'normal' and 'exceptional' cases, on how you plan to
handle exceptional cases etc. But at least one thing is clear: your
solution is not consistant. Either
1/ you expect the attribute to exist *and* be callable - and then any
other case should raise the appropriate exception - or
2/ you consider that the attribute may exists *and* be callable if it
exists - in which case you should silently ignore a failure of getattr
() but raise if callable(obj) evals to False - or
3/ you just ignore both failure conditions.

Anyway, crashing on a gettattr() failure and ignoring a callable()
failure is really a WTF.

FWIW:

case 1/ is the simplest to code : just rely on Python's default error
handling:

push = getattr(obj, name) # will raise if no attribute 'name'
push(args) # will raise if 'push' is not callable


case 2/ is not that hard:

push = gettattr(obj, name, None)
if push and not callable(push):
raise TypeError("%s.%s is not callable" % (obj, name))
push(args)

case 3/ is even simpler:

push = gettattr(obj, name, None)
if push and callable(push):
push(args)


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



Re: Injecting stuff to an existing list?

2008-11-25 Thread bruno desthuilliers

On 25 nov, 10:04, "David Zhou" <[EMAIL PROTECTED]> wrote:
> On Tue, Nov 25, 2008 at 3:55 AM, sajal <[EMAIL PROTECTED]> wrote:
> > Now Id like to show age of the people along with their names.
>
> > I have a function which can calculate age callable via calculateAge
> > (p.date_of_birth)  but how do I make pass this along with the person
> > object?
>
> There's several ways you could approach this:
>
> 1. Create a new template tag
(snip)
> 2. Add a current_age method to the Person model,
(snip)
>
> 3. Return a list of tuples in your context processor:
>
(snip)

You forgot one: write a custom filter:

@register.filter
def calculate_age(date):
   return some_calculation(date)


{% load myfilters %}
{% for person in borntoday %}
{{ person }} - {{ person.date_of_birth|calculate_age }}
{% endfor %}


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



Re: Injecting stuff to an existing list?

2008-11-25 Thread bruno desthuilliers



On 25 nov, 10:17, sajal <[EMAIL PROTECTED]> wrote:
> David/Daniel,
>
> Thanks a lot for the prompt responses, ill use the method as specified
> by Daniel.
>
> I had use methods earlier for get_absolute_url and stuff, but didnt
> realize i could use methods to do anything I wanted...

Well... This is the whole point of a model layer : centralizing model-
related stuff where it belongs. Also note that Python being highly
dynamic, you can add new methods at runtime to an existing class,
which is very handy when using third-part applications:

# mymodel.py
from thirdpart.model import Person

def get_age(self):
return calculate_age(self.birth_date)

Person.get_age = get_age


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



Re: Copy data from 1 model to another

2008-11-26 Thread bruno desthuilliers

On 26 nov, 06:24, issya <[EMAIL PROTECTED]> wrote:
> It looks like I partly answered my own question. I just do something
> like the below to get the field names of the empty model B and I will
> iterate through the fields until 1 matches and then assign the
> information.
>
> This only prints out the field names.
>
> property_field = FeaturedProperties()._meta.fields
> for field_name in property_field:
> print field_name.name


objA = ModelA.objects.all()[0]
fieldnames = ModelB._meta.get_all_field_names()
data = {}
for fieldname in fieldnames:
val = getattr(objA, fieldname, None)
if val:
data[fieldname] = val
objB = ModelB.objects.create(**data)


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



Re: can't pass a parameter to my named url using {% url %} tag in template

2008-11-27 Thread bruno desthuilliers

On 27 nov, 14:19, dash86no <[EMAIL PROTECTED]> wrote:
(snip)
> However, when I do :
>
> delete
>
> I get the error:
>
> Caught an exception while rendering: Reverse for 'sam_project.delete-
> quote-page,' with arguments '('',)' and keyword arguments '{}' not
> found.
>
> If anyone has any hints they would be most appreciated.

The two things I'd try:
1/ double-check that object.id is not empty
2/ try this syntax:

delete


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



Re: Overriding contrib.auth User save()

2008-11-27 Thread bruno desthuilliers



On 27 nov, 17:11, Paddy Joy <[EMAIL PROTECTED]> wrote:
> Thanks for the tips, signals would work except I need access to the
> raw password when users are created.
>
> On further inspection it seems I would need to override the
> UserManager,

On even further inspection, you may in fact want to override
User.set_password !-)

> I know I can extend it with more methods but I don't
> think I can override it.

As Alex said, you can always - I mean, as a _last_ resort -
monkeypatch it:

# mymodel.py
from auth.models import UserManager
_create_user = UserManager.create_user
def my_create_user(self, username, email, password=None):
# do whatever here
# and eventually remember to call the original method
return _create_user(self, username, email, password)

UserManager.create_user = my_create_user

# et voilà.



> Paddy
>
> On Nov 27, 12:39 am, sergioh <[EMAIL PROTECTED]> wrote:
>
> > Signals are the better way to achieve. You usually override the save
> > method when you need to define something related with the model
> > itself, but in many cases signals are the better way to notify some
> > function to do something if a model change (after save)
>
> > def your_function(sender, instance, created=False, **kwargs):
> >   # your tasks
>
> > models.signals.post_save.connect(your_function, sender=User)  #this
> > relate your User model with the signal
>
> > regards,
>
> > Sergio Hinojosa
>
> > On Nov 26, 7:01 am, "Alex Koshelev" <[EMAIL PROTECTED]> wrote:
>
> > > Of course you can monkey-patch the User model but the better way is to use
> > > signals pre_ or post_save
>
> > > On Wed, Nov 26, 2008 at 13:54, Paddy Joy <[EMAIL PROTECTED]> wrote:
>
> > > > I would like to override the save() method on the contrib.auth User
> > > > model so that I can run a routine when a user is created/modified.
>
> > > > Is this possible or do I need to use a signal? I have tried overriding
> > > > the User model like this but it never seems to call my code:
>
> > > > from django.contrib.auth.models import User
>
> > > > # Override User model
> > > > class User(models.Model):
>
> > > >def save(self):
>
> > > ># Do something here
> > > >myroutine()
> > > >super(User, self).save()
>
> > > > Can anyone help?
>
> > > > Paddy
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Ordering bookeditions by their rating

2008-11-28 Thread bruno desthuilliers

On 28 nov, 11:07, coan <[EMAIL PROTECTED]> wrote:
> I have book editions in my database. Users can rate editions. If they
> want, they can also add them to their book collection.
> Here is a simplified overview of the models:
>
> class Edition(models.Model):
>  title   = models.models.CharField(max_length=255)
>  binding= models.models.CharField(max_length=30)
>
> class Bookcollection(models.Model):
>  user= models.ForeignKey(User)
>  edition = models.ForeignKey(Edition)
>
> class Rating(models.Model):
>  user= models.ForeignKey(User)
>  edition = models.ForeignKey(Edition)
>  rating = models.PositiveIntegerField()
>
> I can fetch all the books in a users bookcollection with editions =
> user.edition_set.all()
> What do I do if I want to order a users bookcollection by the rating
> he or she gave it?

What's the point of having two distinct models for Bookcollection and
Rating ??? Looks like mostly redundant to me.

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



Re: Overriding contrib.auth User save()

2008-11-28 Thread bruno desthuilliers

On 28 nov, 09:45, Paddy Joy <[EMAIL PROTECTED]> wrote:
> Thanks however I'm guessing:
>
>
>
> > admin.site.unregister(User)
> > admin.site.register(User, NewModelForm)
>
> will only work in the admin site?

Yes.

> Not actually using the admin site at
> the moment but would nice to have something that would work globally.
>
> I nearly have the monkey patch working however I'm getting the
> following error, any idea?
>
> >>> from django.contrib.auth.models import UserManager
> >>> a=UserManager()
> >>> a.create_user(username='sdf', email='[EMAIL PROTECTED]', password='222')
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/var/django/mysite/../mysite/hosting/models.py", line 166, in
> my_create_user
> return _create_user(self, username, email, password)
>   File "/usr/lib/python2.5/site-packages/django/contrib/auth/
> models.py", line 100, in create_user
> user = self.model(None, username, '', '', email.strip().lower(),
> 'placeholder', False, True, False, now, now)
> TypeError: 'NoneType' object is not callable

Your UserManager instance is not connected to any model, so it's model
attribute is None. Manager classes are meant to be used thru model
classes, not directly.

IOW, you want:

from django.contrib.auth.models import User
user = User.objects.create_user(username='sdf', email='[EMAIL PROTECTED]',
password='222')

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



Re: Displaying items of a linked object in a template

2008-12-01 Thread bruno desthuilliers

On 1 déc, 14:20, Daniel Roseman <[EMAIL PROTECTED]> wrote:
> On Dec 1, 12:15 pm, Marco <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
>
> > I have this in my models.py :
>
> > class Device(models.Model):
> > name = models.CharField(max_length=30)
>
> > class DeviceProperty(models.Model):
> > key = models.CharField(max_length=30)
> > value = models.CharField(max_length=80)
> > device = models.ForeignKey(Device)
>
> > In my views.py, I'm doing :
> > deviceList = Device.objects.all() and put this list to the response
>
> > In my template, I'm currently displaying the items like this :
> > {% for device in deviceList %}
> >   {{ device.name }}
> >   ...
> > {% endfor %}
>
> > My question is : how can I also display items from my DeviceProperty
> > class ? Like it is described in the model, I have a list of
> > DeviceProperty for each Device. So inside of my "for" loop, I'd like
> > to display the associated DeviceProperty items.
>
> > Any idea ?
>
> > Thanks.
>
> Just carry on with the same logic.
>
> {% for device in deviceList %}
>   {{ device.name }}
>   {% for property in device.deviceproperty_set.all %}
>   {{ property.key }}: {{ property.value }}
>   {% endfor %}
> {% endfor %}

And eventually change your view to:

 deviceList = Device.objects.all().select_related()

(this should avoid one extra db query per property)


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



Re: Model similar to a spreadsheet

2008-12-02 Thread bruno desthuilliers

On 1 déc, 20:10, Stefan <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm new to Django and have some problems on how to create the models.
>
> What I want to do is something similar to a spreadsheet, but with more
> than one data field per intersection.
>
> Basically like this: (http://dpaste.com/hold/95128/)
>
> Items/Members: Person_A | Person_B | Person_C
> Item_1: x=1,y=3 | x=4,y=2 | x=7,y=5
> Item_2: x=8,y=2 | x=2,y=0 | x=8,y=4
> Item_3: x=4,y=9 | x=5,y=9 | x=3,y=1
> .
> .
> (and so on)
>

class CostSheet(models.Model):
title=models.CharField(max_length=200)

class Person(models.Model):
name=models.CharField(max_length=200)

class Item(models.Model):
name=models.CharField(max_length=200)
sheet=models.ForeignKey(CostSheet)

class PersonItem(models.Model):
person = models.ForeignKey(Person)
item = models.ForeignKey(Item)
x = models.IntegerField()
y = models.IntegerField()


Your specs are not enough detailed to make sure this is what you want,
but this should at least get you started.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Configuring Paths for FileField ?

2008-12-02 Thread bruno desthuilliers



On 2 déc, 08:58, Eric <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I'm new at Django, but I've been having relatively good luck.  I've
> recently hit a big of a wall using FileField.  I have set up the paths
> correctly enough that I can upload files to  /my_site/uploads/photos,
> but when I view the model containing the FileField in the admin
> interface, it shows the URL of the photo 
> as:http://localhost:8000/uploads/photos/flier.jpg
>
> Clicking on this link, of course, produces a 404 error.
>
> Is there an accepted way to set up the routes to make this /uploads/
> directory publicly accessible?

A couple links to the FineManual:
http://docs.djangoproject.com/en/dev/howto/static-files/
http://docs.djangoproject.com/en/dev/ref/settings/#media-root
http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-media

HTH
> Thanks for your time.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Why run two web-servers on the same host?

2008-12-02 Thread bruno desthuilliers

On 2 déc, 17:46, walterbyrd <[EMAIL PROTECTED]> wrote:
> All the python frameworks seem to do this: one web-server for
> development, another for production. There may be a good reason for
> this, but I don't see it.

Err... Not breaking whatever on the production server, perhaps ? FWIW,
this is nothing specific to Django nor Python - no one in his own mind
would work directly on a production server.

> For example, this is what I do with php: I mirror my web-site on my
> development box. When the files on my development box work the way I
> want, I just ftp those files to the web-site.

So you have your development server on your own box ? Fine. That's
what most of us do, FWIW. Having an intermediate 'pre-production'
server is still usefull, for integration tests (team work), and to
give the customer access to work-in-progress.

> I find this method much
> more simple, fast, and robust, than trying to juggle two web-servers
> on the same box.

??? two web servers on the same box ???

> Also, why is it that with Django I have to restart the web-server, or
> touch all files, any time I make any change?

Because django runs as a long-running process, and does not rebuild
the whole world on each and any request (which is what PHP do).

As a side note : Django also comes with a builtin dev server that
doesn't even require setting up apache or anything else, and that
knows how to auto-restart when necessary.

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



Re: about tutorial

2008-12-03 Thread bruno desthuilliers

On 3 déc, 13:22, Alan <[EMAIL PROTECTED]> wrote:
> Hi, so I did the tutorial and did a simple modification in order to
> get 'polls' views and 'admin' view too but I am failing.
>
> It's that:
>
> for mysite/urls.py:
> from django.conf.urls.defaults import *
> from django.contrib import admin
> admin.autodiscover()
> urlpatterns = patterns('',
> (r'^admin/(.*)', admin.site.root),
> (r'^polls/', include('mysite.polls.urls')),
> )
>
> But, if so, then admin pages failed (http://localhost:8000/admin/):
> TemplateSyntaxError at /admin/
> Caught an exception while rendering: Tried vote in module
> mysite.polls.views. Error was: 'module' object has no attribute 'vote'
> ...
>
> If I want 'admin' view, then I have to comment out line "(r'^polls/',
> include('mysite.polls.urls')),"

I strongly suspect an error in either your polls.urls module or your
polls.views module. It seems you're trying to access some unexisting
symbol of the polls.views module (a view function perhaps ?) named
'vote'.

> Well, I must confess that my knowledge on regexp is limited. So, in
> the end, what should I do about mysite/urls.py in order to get both
> admin and polls pages working?

first make sure the whole thing works correctly without the admin
part.


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



Re: unable to open database file

2008-12-04 Thread bruno desthuilliers

On 4 déc, 09:49, gaz <[EMAIL PROTECTED]> wrote:
> Hi I am trying to run Django Questionaire (http://djangoquest.aperte-
> it.com/) on Apache with mod_python using SQlite on Windows 2003.
>
> When I try to log in I get the unable to open database file error. I
> saw a number of posts mention that the parent
> directory should be writable and it is.
>
(snip)
> Here is my settings file and error output, any ideas ?
>
> # Django settings for django-questionnaire project.
(snip)
> WORKING_DIRECTORY = 'C:\djangoprojects\djangoquest'
(snip)
> DATABASE_NAME = 'C:\questionairedb\test_quest.sqlite' # Or

Remember that the settings.py file is python source code, and that in
Python (like in C and most other languages), '\t' is the escape
sequence for the tab character. For file path on Windows, you want to
either:
- escape the antislashes (ie : "C:\\questionairedb\
\test_quest.sqlite")
- use raw strings (ie : r"C:\questionairedb\test_quest.sqlite")
- or just use a slash as path separator (ie :  "C:/questionairedb/
test_quest.sqlite")


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



Re: Using managers for related object access

2008-12-04 Thread bruno desthuilliers



On 4 déc, 21:39, "Luke Graybill" <[EMAIL PROTECTED]> wrote:
> I am attempting to use a custom manager for related object access, as
> documented 
> here,
> but it does not appear to be working properly. Upon accessing the reverse
> relationship, I am getting an unfiltered queryset result. Using this trimmed
> down code ,

invert lines 17 and 18, ie make 'referenced' the first declared object
manager and 'objects' the second.

And yes, the result you get is not what one would expect reading the
mentioned doc.

The fact is that is that use_for_related_fields only impacts the other
side of the relationship, ie Shift.worked_by (but since you didn't
define a  Custom manager for Employee...). In this side of a OneToMany
relationship, it's the default manager that is used, and the default
manager is the first declared one.

HTH

PS : As a side note: the pattern I personnally use is :

class ShiftManager(models.Manager):
use_for_related_fields = True
def referenced(self):
return self.filter(is_dereferenced=False)

e = Employee.objects.get(id=1)
e.shifts.referenced()

This avoid having to write too many managers


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



Re: Ruby on Rails vs Django

2008-12-05 Thread bruno desthuilliers

On 5 déc, 13:06, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I'm new to the django world and I was just wondering how Django
> compears with  Ruby on Rails ?

Mostly just like Python compares with (with ??? to ???) Ruby IMHO.
Quite close overall, and yet very different philosophies.


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



Re: Ruby on Rails vs Django

2008-12-05 Thread bruno desthuilliers



On 5 déc, 15:31, Masklinn <[EMAIL PROTECTED]> wrote:
> On 5 Dec 2008, at 14:30 , bruno desthuilliers wrote:> On 5 déc, 13:06, 
> "[EMAIL PROTECTED]"
> > <[EMAIL PROTECTED]> wrote:
> >> Hi All,
>
> >> I'm new to the django world and I was just wondering how Django
> >> compears with  Ruby on Rails ?
>
> > Mostly just like Python compares with (with ??? to ???) Ruby IMHO.
> > Quite close overall, and yet very different philosophies.
>
> I'd say that Rails and Django differ much more than Python and Ruby.
> There are "small" differences between Python and Ruby,

for which definition of "small" ? Granted, Python and Ruby are both hi-
level object-oriented highly dynamic languages, and there are a couple
superficial similarties in their respective syntaxes. But the object
model and the general philosophy are _totally_ different.

> but the core
> philosophies and structures of Rails and Django on the other hand are
> completely unrelated and pretty much incompatible.

As far as I'm concerned, this is just as true (or false) of Python vs
Ruby. And this mostly reflects the "architectural" and philosophical
differences between both languages.


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



Re: Ruby on Rails vs Django

2008-12-05 Thread bruno desthuilliers

On 5 déc, 16:16, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Metaphorically that Python/Djangois for a conservative engineer
> mindset,

??? care to elaborate on this ???


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



Re: Ruby on Rails vs Django

2008-12-06 Thread bruno desthuilliers

On 5 déc, 23:57, yejun <[EMAIL PROTECTED]> wrote:
> On Dec 5, 2:43 pm, bruno desthuilliers <[EMAIL PROTECTED]>
> wrote:
>
> > On 5 déc, 16:16, "[EMAIL PROTECTED]"
>
> > <[EMAIL PROTECTED]> wrote:
> > > Metaphorically that Python/Djangois for a conservative engineer
> > > mindset,
>
> > ??? care to elaborate on this ???

> I think he means python is a more traditional procedure like language
> than ruby is.

"Code-blocks" set aside, I fail to see how Python is "more
traditional" or "more procedural" than Ruby.

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



Re: Ruby on Rails vs Django

2008-12-06 Thread bruno desthuilliers



On 6 déc, 10:55, "Guillermo C." <[EMAIL PROTECTED]> wrote:
> Hi.
>
> - Scaffolding: I prefer it over django admin in many situations. I
> mean, when you're doing something complex you'll need to drop out the
> django admin and write your own code, so it's cool to have the basic
> CRUD code and develop from that.

While you surely have to write some code for custom stuff, you don't
necessarily have to "drop out of admin" - you can just customize the
relevant part of the admin.
(snip)

> - RoR controllers versus Django views: Django does not enclose in
> classes the controllers neither have Routes, the mapping between urls
> and views (plain functions taking a ``request`` object as first param).

s/plain functions/callable objects/

Remember that classes are callable too, and that Python let you define
your own callable types.

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



Re: fields in object.values()

2008-12-08 Thread bruno desthuilliers



On 8 déc, 08:53, Sotiris Kazakis <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Thank you for your answer.
>
> I try : tbData = tableName.objects.values(*strFld.split(","))
>
> but that error appears :
>
>   File "/var/lib/python-support/python2.4/django/db/models/sql/query.py", 
> line 1503, in add_fields
> field, target, u2, joins, u3, u4 = self.setup_joins(
> AttributeError: 'list' object has no attribute 'split'
> because strFld.split(",") --> produce a list

>>> fnames=['target_user', 'source_user']
>>> Friendship.objects.values(*fnames)
[{'source_user': 1L, 'target_user': 2L}]
>>> fields = "target_user,source_user"
>>> Friendship.objects.values(*fields.split(','))
[{'source_user': 1L, 'target_user': 2L}]
>>>

str.split() indeed returns a list, but that's obviously not the cause
of your problem 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-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: fields in object.values()

2008-12-08 Thread bruno desthuilliers

On 7 déc, 21:48, "sotiris.kazakis" <[EMAIL PROTECTED]> wrote:
> hello,
>
> I search a lot about the use of object.values() but don't get what I
> want.
>
> I want to put dynamically (with a string ?)

Better to use a sequence of strings IMHO.

> the fields that I want to
> get from a model. i.e.:
>
> #model
> Class Test(model.Model)
>Id = models.AutoField(primary_key=True, verbose_name="a/a")
>Name = models.CharField(max_length=90, unique=True,
> verbose_name="Name")
>Description = models.CharField(max_length=24,
> verbose_name="Description")
>
> #function to view the data of my table with strFld
> def tbView(tbName,strFld=None):
>  tableName=eval(tbName)   # class instance

eval() is the wrong solution for 99.9% use cases. If you want a
generic solution, better to use "app_label" "model_name" as argument
and db.models.loading.get_model (cf below).

>  tbFields=tableName._meta.fields# load table fields

you actually don't use this in the rest of the code...

> tbData=tableName.objects.values(strFld)  #load only field in
> strFld
>
> return render_to_response('myView.html',
> {'tbData':tbData,'name':tbName})
>
> I would like to get the data from selected fields with this :
>
> strFld="Name,Description"
> tbView('Test',strFld)
>
> When I use that get this error :
>
> raise FieldError("Cannot resolve keyword %r into field. "
> FieldError: Cannot resolve keyword 'Name,Description' into field.
> Choices are: Id, Name, Description.
>
> What is wrong ?

You need to pass a sequence of field names. Which you can build from
strFld:

# assuming ',' is the delimiter:
  fieldnames = filter(None, [n.strip() for n in strFld.split(',')])


Now note that the HTTP protocol allow multiple values for a same key
in a GET or POST request, which is of course supported by Django's
request.GET, request.POST and request.REQUEST QueryDict objects.

here's a possible fix (untested, and without error handling).

I allowed myself to use a more pythonic naming scheme (cf Python's
naming conventions: http://www.python.org/dev/peps/pep-0008/)



from django.db.models.loading import get_model

def table_view(request, app_label, model_name):
# example url with querystring:
# /myproject/table_view/app_label/model_name/?field=foo&field=bar

model = get_model(app_label, model_name)
fields = request.REQUEST.getlist('field')
data = model.objects.all().values(*fields)
context = dict(data=data, app_label=app_label,
model_name=model_name)
return render_to_response('my_view.html', context)

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



Re: Help needed debugging a weird MySQL error!

2008-12-08 Thread bruno desthuilliers



On 8 déc, 14:28, taleinat <[EMAIL PROTECTED]> wrote:
> I have a Django application, and I wrote an external script which
> reads and writes to the Django database. I've started getting the
> following exception consistently:
>
> Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of
> sync; you can't run this command now") in  of > ignored

Most probably something to do with transaction handling, I'd say.

> Has anyone had similar problems?
>
> Otherwise, I need some help debugging this. Where do I start?

As usual : extract the minimum code required to reproduce the error,
and run it with pdb.


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



Re: unique_together question

2008-12-09 Thread bruno desthuilliers

On 9 déc, 13:20, Alex Jonsson <[EMAIL PROTECTED]> wrote:
> Hey everyone,
>
> My model looks like the following:
>
> http://dpaste.com/97293/
>
> An album has a release date for every format, and one format can only
> have one release date per album. Hopefully you get what I'm trying to
> achieve here ;)

Then your model seems broken to me. If you set album as a unique key,
you can only have one single ReleaseDate instance per album. Idem for
format: if a unique key, you can only have one single ReleaseDate
instance per format. You want them to be unique _together_, not unique
in the whole table.


> The thing is though, that in my Album model I specify a ManyToMany
> relationship with the Format in order to specify what Formats an Album
> would be released in.
>
> Now when I create this model, it will allow me to set a release date
> for any Format - I would like to allow it to only specify a release
> date for the formats that are specified in the Album ManyToMany
> column.
>
> How would be the easiest way to do this?

overload the ReleaseDate save() method ?

class ReleaseDate(models.Model):
album = models.ForeignKey(Album) #, unique=True)
format = models.ForeignKey(Format) #, unique=True)
date = models.DateField()

class Meta:
verbose_name = _('release date')
verbose_name_plural = _('release dates')
unique_together = ('album', 'format')

def save(self, **kw):
if self.format not in album.format_set.all():
raise Whatever(
"%s is not an allowed format for alubm %s" \
% (self.format, self.album)
)
super(ReleaseDate, self).save(**kw)

Note that this might cause problem if you:
- allow a format for an album
- create a ReleaseDate for this album and format
- disallow the format for this album

You'll have to handle this correctly (most probably by overloading
Album.save too...)

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



Re: Using random.random() while running on server

2008-12-09 Thread bruno desthuilliers

On 9 déc, 11:32, Chris <[EMAIL PROTECTED]> wrote:
> Hello,
> when django is running on a server, I want to make a call to:
> random.random().  When I make a call to this again, I can't. I think
> this related to a similar issue datetime.datetime.now() where you
> leave off the () to get a current date each time each time you call
> it.

I _very_ strongly suggest you take some time learning Python. In this
case, the parens are actually the call operator. Not applying this
operator results in getting a reference to the function (or whatever
callable).


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



Re: Using random.random() while running on server

2008-12-10 Thread bruno desthuilliers



On 9 déc, 23:56, Chris <[EMAIL PROTECTED]> wrote:
> Thanks Daniel Roseman That did the trick. I did not think to do a
> lambda
>
> > I _very_ strongly suggest you take some time learning Python. In this
> > case, the parens are actually the call operator. Not applying this
> > operator results in getting a reference to the function (or whatever
> > callable).
>
> bruno desthuilliers - Yes I understand that!

Ok, this was not obvious (to me at least) from reading your post.
Sorry.

> I _very_ strongly suggest

!-)

> that you read up on the issue with datetime
> as to why you pass it in
> that way when passing it through something like so:
>
> date = models.DateTimeField(default=datetime.datetime.now)

It's not a issue with datetime, it's a consequence of Python's
evaluation rules wrt/ the class statement - which is in this case
'solved' by the fact that 'default' can take a callable as value (cf
fields.get_default() in db/models/__init__.py). Which FWIW was what I
was about to add to my answer, but Daniel already did so in the
meantime !-)



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



Re: referencing the current instance inside limit_choices_to

2008-12-10 Thread bruno desthuilliers

On 10 déc, 19:25, fiedzia <[EMAIL PROTECTED]> wrote:
> On Dec 10, 1:56 am, GuyBowden <[EMAIL PROTECTED]> wrote:
>
> > I'd like to set the limit_choices_to value of a ForeignKey field based
> > on another selection in the current instance.
>
(snip)
>
> other thing to look at is that what is passed to limit_choices_to
> might be a callable,
> but it doesn't receive instance as parameter (and i would like it
> did).

I had a quick look, and it seems that limit_choices_to doesn't accept
a callable (at least in the svn version I use at work, rev 9100 iirc).
It can be a queryset or any object having a add_to_query(sqlquery)
method, but I failed to find any object implementing this protocol in
django itself, nor any documentation.


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



Re: get_profile() and save()

2008-12-10 Thread bruno desthuilliers

On 10 déc, 11:18, [EMAIL PROTECTED] wrote:
> Hi,
>
> I've got a ManyToMany-Field in my user-get_profile model. Now I've got these 
> lines of code:
>
> 1. up = user.get_profile()
> 2. up.groups.add(bla)
> 3. up.groups.save()
> 4. up.save()
>
> Is it necessary to call up.groups.save() (line 3)

No.

> and it is necessary to call up.save() (line 4) ?

No - unless you modified 'up' itself of course !-)

> Afaik there is no need to call the save() method when adding a instance to a 
> Many-To-Many Field, but I'm not sure :)

You could easily tried out by yourself using ./manage.py shell.

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



Re: A custom field that populates other models

2008-12-10 Thread bruno desthuilliers

On 10 déc, 10:50, pielgrzym <[EMAIL PROTECTED]> wrote:
> Hi there,
>
> I followed some examples in the documentation regarding contenttype
> and I wanted to write my own simple, generig tagging app. I know there
> is tagging application but it's troublesome when you try to pass tag
> names in GET (language specific chars).

http://docs.python.org/library/urllib.html#utility-functions

> Here is my code - it doesn't
> work

"doesn't work" is one of the most useless possible description of a
problem. What happens exactly ?

> - could anyone point me to the right direction?

I'd say urllib.quote and unicode.encode...

(snip)

> tags/fields.py:
>
> # -*- coding: utf-8 -*-
> from django.db import models
> from tags.models import *
>
> def _tag_split(string):
>   list = string.split(",")

this will shadow the list builtin type. 

>   i = 0
>   for val in list:
> list[i] = val.strip()
> i = i + 1

Use enumerate(seq) if you want to iterate over a sequence and have
indices too:

for i, val in enumerate(thelist):
   thelist[i] = val.strip()

>   clear_list = [x for x in list if x]
>   return clear_list

Somehow complexificated way to do a simple thing:

def _split_tags(tags):
   return  filter(None, [tag.strip() for tag in tags.split(',')])


> _transliteration_pl = (
> (u"Ä ", r'a'),
> (u"\xc4\x85", r'a'),
> (u"Ä ", r'c'),
> (u"\xc4\x87", r'c'),
> (u"Ä ", r'e'),
> (u"\xc4\x99", r'e'),
> (u"Ĺ ", r'l'),
> (u"\xc5\x82", r'l'),
> (u"Ĺ ", r'n'),
> (u"\xc5\x84", r'n'),
> (u"Ăł", r'o'),
> (u"\xc3\xb3", r'o'),
> (u"Ĺ ", r's'),
> (u"\xc5\x9b", r's'),
> (u"Ĺź", r'z'),
> (u"\xc5\xbc", r'z'),
> (u"Ĺş", r'z'),
> (u"\xc5\xba", r'z')
> )
>
> def _transliterate(value):
> """Replaces language specific chars with theis non-specific
> equivalents"""

What about hebrew characters ?-)

> for bad, good in _transliteration_pl:
> value = value.replace(bad, good)
> return value
>

(snip)

Ok, you may have perfectly valid reasons to roll your own tag
application, but if it's just a problem with encoding, using
unicode.encode and urllib.quote should be enough to solve it IMHO.

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



Re: A custom field that populates other models

2008-12-11 Thread bruno desthuilliers



On 11 déc, 01:11, pielgrzym <[EMAIL PROTECTED]> wrote:
(snip)
> The problem with saving is that when I try to save a post instance I
> recieve:
>
> AttributeError: 'TagField' object has no attribute '_meta'
> (link to full error report:http://wklej.org/hash/098a9cbd7a/)
>
> I'm not sure if passing 'self' as content object isn't the reason,

It is, clearly. You're passing a Field object ('self') where a Model
object is expected. It's not the TagField you want to pass but the
Model instance it's bound to. Which should probably be done in pre_save
() - which gets the instance as parm -, not in get_db_prep_value().

For the record and if I may ask : did you investigate solving your
initial problem with the existing tagging app and urllib.quote
instead ?

Also and FWIW : the existing tagging app (just like Django and Python)
is free software. This means that you have the right to read, modify
and redistribute the source code. If tagging is quite close but not
exactly what you want, why don't you start with the existing source
code and improve / taylor to your needs ?


> yet
> I have no idea how to achieve this :(

You could have a look at how tagging implemented TagField, and/or at
django/db/models/fields/__init__.py. Reading the source is most of the
time the best way to understand how something works !-)
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: A custom field that populates other models

2008-12-11 Thread bruno desthuilliers



On 11 déc, 16:30, pielgrzym  wrote:
> Thanks for your suggestions! Now I made the tagging work without any
> inside changes due to proper url escaping :)

Fine !-)

> Unfortunately tagging
> crashes multilingual app on postgresql database (I posted an issue
> here:http://code.google.com/p/django-multilingual/issues/detail?id=79
> ). I think I should write some simple content translation app, since
> this error I get seems to be just to complex for me :(

Too bad. Well... shit happens :(



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



Re: django template script variable usage and declaration

2008-12-12 Thread bruno desthuilliers

On 12 déc, 11:57, Daniel Roseman 
wrote:
> On Dec 12, 7:04 am, "Haroon idrees"  wrote:
>
>
>
> > Hello
> >  I am new to python world . any one can help to guide how we
> > declare variables in python template script and use in if else block
> > and vary it
>
> > for example
> > //need to declare variable here
> > //for example x=0
> > {% for message in message %}
> > //need to put if condition here
> > //ifequal x 0
> > 
> > //x=1
> > //need to put else condition here
> > 
> > x=0
> >   > href="/restmessage/mzubair.ahmed?format=xml">mzubair.ahmed 
>
> > 
> > test
> > 
> >  2008-12-12 05:13:45.788901
> > 
>
> >  {%endfor%}
>
> No, you can't do that, by design.
>
> But a quick reading of the documentation for the for tag would show
> you how it should be done: use forloop.counter0.
> Seehttp://groups.google.com/group/django-users/browse_thread/thread/3edf...


Or if it's just to alternate between odd and even rows, use the
builtin {% cycle %} tag:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#cycle



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



Re: Multiple sites - same code, different templates

2008-12-12 Thread bruno desthuilliers



On 12 déc, 13:33, "Ramdas S"  wrote:
> just a suggestion
>
> if it is just the templates you can write a loop inside in settings.py
> based on site_id
>
(snip)
> Pardon me if I didn't understand your question.

Nope. The OP is talking of using different templates for the same 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-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Multiple sites - same code, different templates

2008-12-12 Thread bruno desthuilliers

On 12 déc, 13:14, will0  wrote:
> Hi all
>
> I can't figure out how to change TEMPLATE_DIRS according to the URL
> used.
>
> My purpose is to view two versions of the same site, e.g. mysite/v1/
> and mysite/v2/, but keep the same codebase. This is just for
> development so people in several countries can view the site and put
> in their opinion.

The simplest solution would be to use 2 different settings files -
IIRC, you can specify the setting file to use in the apache config.

(snip)

> Perhaps there's a way to pick up the HTTP request parameters in
> settings?

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



Re: Multiple sites - same code, different templates

2008-12-13 Thread bruno desthuilliers

On 13 déc, 14:41, barbara shaurette  wrote:
> This might be overkill, but you could use middleware and parse for the
> version number in request.path:
>
> from django.conf import settings
> from django.http import HttpResponseRedirect
>
> from mysite import settings as local_settings
>
> class DetectSiteVersion(object):
> def __init__(self):
> self.v2_templates = local_settings.VERSION_TWO_TEMPLATE_DIRS
>
> def process_request(self, request):
> if str(request.path).find('v2') == -1:

request.path is already a string. Also, 'v2' could be part of
request.path without being the relevant part (ie : /v1/foo/barv2/
yadda').

> settings.TEMPLATE_DIRS = self.v2_templates +
> local_settings.TEMPLATE_DIRS

Modifying settings at runtime may not be such  a good idea...

> return HttpResponseRedirect(request.path)

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



Re: django template script variable usage and declaration

2008-12-14 Thread bruno desthuilliers

On 14 déc, 10:53, "Haroon idrees"  wrote:
> I try cycle tage but it also give some error can please tell me what
> is write Syntax  of cycle tag


It's in the documentation. Just follow the link I gave in my previous
post.

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



Re: django query database

2008-12-14 Thread bruno desthuilliers

On 14 déc, 00:46, "Alfredo Alessandrini"  wrote:
> Hi,
>
> It's possible call a query with max or min value?:
>
> like this:
>
> game_list = game.objects.filter(Q(max_rating > player.rating) &
> Q(min_rating < player.rating))

Sorry but your question is not clear. Are 'min_rating' and
'max_rating' fields of the game object ? If yes:

game_list = game.objects.filter(
Q(max_rating__gt = player.rating)
&
Q(min_rating__lt = player.rating)
   )

Else, cf Malcolm's answer.



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



Re: django template script variable usage and declaration

2008-12-14 Thread bruno desthuilliers

On 14 déc, 18:06, "Haroon idrees"  wrote:
> after follow the documentation i face the following error
>  File "C:\Program
> Files\Google\google_appengine\lib\django\django\template\__init__.py",
> line 273, in parse
> compiled_result = compile_func(self, token)
>   File "C:\Program
> Files\Google\google_appengine\lib\django\django\template\defaulttags.py",
> line 434, in cycle
> raise TemplateSyntaxError("Invalid arguments to 'cycle': %s" % args)
> TemplateSyntaxError: Invalid arguments to 'cycle': ['cycle', "'row1'", 
> "'row2'"]

And where's your code ? Are we supposed to use crystal ball ?-)


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



Re: Reusing a python model

2008-12-14 Thread bruno desthuilliers

On 14 déc, 17:58, "JULIO Cayo"  wrote:
> Thanks Alex for your fast reply! Maybe I don't understand you, but if
> i have a model (70 classes) in "base python" i don't want to re-write
> entire model in django style.

You don't have use Django's models.Model class to use Django. But
obviously you need to subclass models.Model to use Django's ORM.
There's nothing magical with Django you know, it's just a Python
framework.

> For example, I have a class "User" with age, name, lastname , etc...
> In my model is:
> class User:
>   name = " "


Err... I assume you don't have much experience with Python itself. If
that's how your "model" classes looks like, I strongly suggest you
(and your coworkers) ask for guidance on comp.lang.python, because
chances are you'll have to rewrite the whole damn thing anyway.


> And django need something like:
> name =  models.CharField(max_length=200)

*Django* doesn't "need" it. It's just if you want to use Django's
*ORM*.

> But I don't want to "touch" the model, because are 70 classes, and can
> be more: a group is working on the model, another is working on
> "desktop view" and another is in "web view", one model many views.

This is unrelated. If you have your own ORM (or whatever persistence
system), then use it. You won't be able to use any Django Model-
related feature - obviously - but there's more (much more) than this
in the framework.


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



Re: django query database

2008-12-14 Thread bruno desthuilliers

On 14 déc, 19:03, "Alfredo Alessandrini"  wrote:
> > Sorry but your question is not clear. Are 'min_rating' and
> > 'max_rating' fields of the game object ? If yes:
>
> Yes
>
> It's better:
>
> game_list = game.objects.filter(Q(max_rating__gt = player.rating) &
> Q(min_rating__lt = player.rating))
>
> or
>
> game_list = 
> game.objects.exclude(min_rating__gt=player.rating).exclude(max_rating__lt=player.rating)
>

As far as I'm concerned, I find the first solution more readable. wrt/
perfs, you'd have to benchmark it.


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



Re: Custom ACL

2008-12-14 Thread bruno desthuilliers

On 14 déc, 15:26, Yanik  wrote:
> Hello,
>
> I need to build a custom ACL for the app I'm working on, Django's
> isn't specific enough (I need to give permissions based on IDs,
> statuses, etc.).
>
> I'd also like to attach it to the user, so that I could lookup in a
> way something like User.acl.has_permission(post_id, "can_edit). How
> can I attach my ACL to the User model "dynamically", without actually
> touching Django's base code?

if 'ACL' is a model (I mean, a django.db.models.Model subclass), then
just add a foreign key to the User model:

from django.db import models
from django.contrib.auth import User

class ACL(models.Model):
user = models.ForeignKey(User, related_name='acl')
...

Else, you can always monkeypatch the User model. You may then want to
use the descriptor protocol (http://docs.python.org/reference/
datamodel.html#descriptors)

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



Re: Custom ACL

2008-12-14 Thread bruno desthuilliers

On 14 déc, 22:49, bruno desthuilliers 
wrote:
(snip)
> Else, you can always monkeypatch the User model. You may then want to
> use the descriptor protocol (http://docs.python.org/reference/
> datamodel.html#descriptors)

More here on descriptors:
http://users.rcn.com/python/download/Descriptor.htm


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



Re: Sort Table Headers after data has been rendered via a POST request

2008-12-16 Thread bruno desthuilliers

On 16 déc, 01:15, SnappyDjangoUser  wrote:
> I wanted to run this by the group one more time does anyone know
> how to handle sorting results by table header URL after a POST
> request?
>
> I have used the SortHeaders class for GET requests and it works
> great.  I am hoping to find a way to extend this for POST requests.

Short answer : don't !-)

Longer answer below:

> On Nov 25, 2:29 pm, SnappyDjangoUser  wrote:
(snip)

> > In my case I am submitting a form to search for items

Submit this form as a GET request (iow : set the html form's method
attribute to 'get'). POST is for when you want to alter the server's
state (ie : add or modify some record etc).

And of course don't forget to add the relevant querystring part to the
urls of your table headers...
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: List a model fields

2008-12-16 Thread bruno desthuilliers



On 16 déc, 10:26, JF Simon  wrote:
> thanks dude.
>
> any idea to split the dict on the _ char ?
> recursive function ?

Probably not the most elegant solution, but it should do the trick:

def add_to_context(self, context, field):
current = context
parts = field.name.split('_')
last_part = len(parts) - 1
for part_num, part in enumerate(parts):
if part_num == last_part:
current[part] = getattr(self, field.name)
return
current = current.setdefault(part, dict())

def get_context(self):
context = {}
for field in self._meta.fields:
self.add_to_context(context, field)
return context

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



Re: List a model fields

2008-12-16 Thread bruno desthuilliers

On 16 déc, 07:53, JF Simon  wrote:
> Hello, i'm new with python (and french so my english may seem very
> poor, sorry about that).
> I would like to list a model's fields and return a dict, here is the
> example :
>
> I have a model class with :
>
> meta_title : CharField(...)
> meta_description : CharField(...)
> body_header_title : CharField(...)
> body_header_text : CharField(...)
> foot : CharField(...)
>
> This class represents context for a page. This class will have a
> function get_context() who will return :
>
> {
>meta :
>{
>   title : 'value of meta_title' ,
>   text : 'value of meta_text' ,
>} ,
>body :
>{
>   header :
>   {
>  title : 'value of body_header_title ,
>  text : 'value of body_header_text ,
>   }
>} ,
>foot : 'value of foot'
>
> }

If I may ask and just out of curiousity: I assume this 'context' is
intended to be passed to a template. if so, why not just  pass the
Page object itself ?


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



Re: Model Inheritance with external apps

2008-12-16 Thread bruno desthuilliers

On 16 déc, 19:07, Lyubomir Petrov  wrote:
> I'm just starting a project that is using django-profile. There are
> some fields like "country" that i want to remove.
> As in django-profiles I use my own class that extends the base class
> (BaseProfile), so i can add some common information fields.
> What is the best way that i can remove those field from the ORM ?

Don't know if it's the "best" way, but it's surely a very simple one:
make a local copy of the app and edit the code !-)
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Using authenticated users id in models

2008-12-17 Thread bruno desthuilliers

On 17 déc, 17:08, abidibo  wrote:
> Hi all,
> I'm a beginenr with Django and Python

And possibly with web programming AFAICT - but we won't hold it
against you !-)

> and I'e have a problem I didn't
> reached to solved myself, here is the question:
> I'd like to have a DB table like POST, that contains a title, a text
> and an author. I'd like the field author to be filled with the id of
> the user which is writing the form, so i tried to set it as a default
> value in the models.py

You can't. Period. The "user which is writing the form" is only known
when there's an incoming HTTP request (from a logged in user, of
course), which is not the case by the time the models are loaded.

IOW, you have to wait until there's an available logged-in user (that
is : in the view handling your form), and explicitely pass it to the
model (eventually thru the form).

> this way:
>
>   from django.db import models
>   from django.contrib.sessions.models import Session
>   from django.http import HttpRequest
>
>   request = HttpRequest()

The HttpRequest class is used by Django to present the incoming HTTP
request (a chunk of bits sent thru the wires) as a Python object.
You're not supposed to instanciate it yourself (except eventually for
unittesting), but to get it as first param of a view function.

Since you obviously don't get it, here's how things work (8-miles
heigh view, skipping quite a lot of steps):

1/ you start your Django server process (either the builtin dev
server, as a wsgi or fcgi server or when starting Apache if you're
using mod_python)

2/ this process loads all your models

3/ then he waits for incoming HTTP requests

4/ when a request come in, django
41. build an HttpRequest object from it
4.2 uses the urls.py to find out which view function should handle it
4.3 call the function with the HttpRequest instance as first param

5. the view function do whatever it has to do - usually using some
model instance and
5.1 returns an HttpResponse object

6. django builds a 'real' HTTP response (ie : a chunk of bits that
will be sent thru the wires) from the (python) HttpResponse object

(snip)

> but the problem, i think, is that the array cookies has no elements,

indeed.

> even if with my browser tool i may see the cookie with key 'sessionid'
> setted.

indeed. There's absolutely _no_ (none, zilch, nada) relationship
between the HTTP request sent by your browser and the HttpRequest
object you instanciate in your models.py file.

If your form is handled thru a view function (and assuming you have
the appropriate middleware installed, cf documentation), you'll get
access to the currently logged-in user as request.user. Then proceed
as you would with any other model attribute. If you want to handle
this for admin forms, just follow this link:
http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser

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



Re: nested template problem

2008-12-18 Thread bruno desthuilliers

On 18 déc, 18:31, marco ghidinelli  wrote:
> hello.
>
> Does django template engine supports nested dictionary?

Yes, indeed.

> i'm trying to display a nested array with no luck.
>
> that's my tries:
>
> --- python manage.py shell ---
> from django.template import Template, Context
> list_parts = {
> 'root': {'value': [{'tag': 'a'},{'tag':'b'}]},
> 'wheel': {'value': [{'tag': 'c'}, ]}
>
> }

Why do you name it "list_" when it's a dict ?

> t = Template("""
> {% for part in list_parts %}

This will iterate over the keys. If you want key:values pairs, you
have to spell it:

{% for partname, partvalue in list_parts.items %}

Also, remember that Python dicts are _not_ ordered. If order matters,
use a list of (name, value) tuples instead.

> 
> {{part}}
>   
>   {% for subpart in part %}

Here, "part" is the key (a string).

> {{ subpart }}
>   {% endfor %}
>   
> 
> {% endfor %}
> """)
>
> c=Context({'list_parts':list_parts})
> print t.render(c)
> --
>
> i tried every possible combination of
>
> {% for subpart in part %}
> {% for subpart in part.part %}
> {% for subpart in list_parts.part %}
>
> but i'm not able to show the information.
>
> where i am wrong?

google for "programming by accident" (a well known antipattern FWIW).

> /me hopeless.

Here's a working version, with a simpler data structure:

from django.template import Template, Context
list_parts = [
('root',  [{'tag': 'a'},{'tag':'b'}]),
('wheel',  [{'tag': 'c'}, ]),
]


t = Template("""
{% for partname, tags in list_parts %}

{{partname}}
  
  {% for tag in tags %}
{{ tag.tag }}
  {% endfor %}
  

{% endfor %}
""")

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



Re: Security in AJAX POSTing

2008-12-18 Thread bruno desthuilliers

On 18 déc, 23:20, Taylor  wrote:
> I'm working on a game in Django where the majority of the interaction
> comes through clicks that run JavaScript methods that use jQuery's
> $.post() to post data to a url.  To protect against cheaters and bots,
> I must ensure that every post is made by a logged-in user and protect
> against cross-site scripting, and I certainly don't want any injection
> attacks. I know Django has many protections against these built in,
> but since most of my requests come through AJAX posts rather than URL
> requests or form submissions, I was wondering what steps I need to
> take to fully protect myself.

Nothing more. From the server's POV, this makes absolutely no
difference - all it sees are HTTP requests, period.


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



Re: output of XML serializer

2008-12-19 Thread bruno desthuilliers



On 19 déc, 00:13, "Mr. T"  wrote:
> response = serializers.serialize('xml', MySet.objects.all())
> return HttpResponse(response , mimetype='text/xml;')
>
> The output has each member of "MySet" with an  tag, and then
> within the object, a bunch of  tags with each field.

Looks like a sensible schema


   1
   1
   1967-01-05
   33640
   Castres-Gironde
   mugshots/bigb.jpeg


> It seems
> sort of hard to parse this on the client side.

If the "client-side" is javascript code in a browser, use json instead
- you'll save quite a lot on both bandwidth and processing.

Else, I assume the client code is written in a language with decent
XML parsing support, and then I just don't see what's your problem
parsing such a simple and obvious schema.

> Can anyone help how to parse out a field,

Err... type and name are attributes, content is content ? What's your
problem exactly ???

> or to have the XML
> serializer just output something simpler?

Sorry but I fail to see what could be simpler.

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



Re: template inheritance miff

2008-12-20 Thread bruno desthuilliers



On 20 déc, 18:48, "Milan Andric"  wrote:
> Hello,
>
> I have two templates in this example, 
> page_base.htmlhttp://dpaste.com/101058/and intro.html  
> http://dpaste.com/101059/.
> intro.html inherits from page_base.html,  but the content_head block
> does not get inherited.  what am i doing wrong or mis-understanding?

Remove the first {% endblock %} (the one just after the call to
{{block.super}}

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



Re: Complete layout (template) switching.

2008-12-22 Thread bruno desthuilliers

On 22 déc, 13:34, Kura  wrote:
> Hey guys, I'm currently working on a content management system built
> on the Django framework, currently the whole cms works on a section->page(s) 
> basis which is working well, we've run in to some issues with
>
> our designs in that the blocks for content on some pages are in
> different locations and the overall layout is different, to combat
> this we've added a field to the page table that tells Django which
> layout template it should use, the issue is I'm not sure how to
> actually make Django read that column and actually switch the whole
> layouts template for that page on a project level as a replacement to
> base.html while keeping base.html as default for other pages.
>
> Any ideas?

if it's a field of the Page model object and you have a Page model
instance in your context, then {% extends page.template|
default:"base.html" %} should do.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#extends



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



Re: Django models

2008-12-22 Thread bruno desthuilliers



On 22 déc, 17:10, kev  wrote:
> Hello,
> Im reading a django book and it adds friends to user authentication
> system by making:
>
> (was .96)
>
> class Friendship(models.Model):
>   from_friend = models.ForeignKey(
> User, related_name='friend_set'
>   )
>   to_friend = models.ForeignKey(
> User, related_name='to_friend_set'
>   )
>   def __str__(self):
> return '%s, %s' % (
>   self.from_friend.username,
>   self.to_friend.username
> )
>   class Admin:
> pass
>   class Meta:
> unique_together = (('to_friend', 'from_friend'), )
>
> But for this to work, you have to add friendship both ways.

Nope. You have to *query* it both ways.


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



  1   2   3   4   5   6   7   8   9   10   >