Re: announcement: SHPAML (alternative to haml)

2010-01-26 Thread Steve Howell
On Dec 29 2009, 1:44 pm, Durbin  wrote:
> very cool! any plans to integrate it fully into the django templating
> system?

Glad you like it.

Amit Upadhyay has written a loader here:

http://github.com/amitu/dutils/blob/master/dutils/shpaml_loader.py

I've used shpaml mostly with django, but for my own use cases, I
prefer light integration, so I publish from shpaml to django outside
of django itself.

This is the script I use; it should be fairly straightforward to
modify it for more complicated template directory structure schemes:

from shpaml import convert_text
import os
import glob

def publish():
os.system('rm -f templates/*.html')
for fn in glob.glob('templates/*.shpaml'):
out_fn = fn.replace('.shpaml', '.html')
open(out_fn, 'w').write(convert_text(open(fn).read()))

if __name__ == '__main__':
publish()

If you are interested in shpaml, please join the mailing list here:

http://groups.google.com/group/shpaml

Since this announcement, there has been a port of shpaml to
Javascript.  Thanks to the Javascript implementation, you can see a
WYSIWYG demo of shpaml here:

http://kp.hcoop.net/kp/doc/tip/shpaml/js/demo.html

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



announcement: SHPAML (alternative to haml)

2009-12-19 Thread Steve Howell
Hi, I have ported some haml concepts to Python in my implementation of
SHPAML.  Details here:

http://shpaml.webfactional.com/

For those of you not aware of haml, haml is a markup language
implemented in Ruby that allows you to eliminate end tags in HTML.
Like Python itself, haml and SHPAML use indentation to eliminate the
need for block-ending syntax.  Whereas Python eliminates the end-
squiggly in scripting code, haml/SHPAML eliminates the need for end
tags in HTML.  If you hate Python, you will undoubtedly hate haml and
SHPAML.  If you like Python, you might like haml/SHPAML.

When I originally wrote SHPAML, I attempted to eliminate end tags in
my Django templates, such as endfor, endblock, endwith, and friends.
I decided to back off that strategy and just DRY up the HTML.  So
SHPAML has no explicit support for Django now, other than letting
Django template constructs gently pass through the preprocessor.

But the whole SHPAML website is still written in Django.  You can see
the markup here:

http://shpaml.webfactional.com/long_example

The Django markup for my website is now back to being lexically
repetitive, but that's okay.  Removing all the crufty syntax of HTML
lets the Django syntax stand out more clearly.

If you are passionate about DRY markup, please join the mailing list
on the site above and help me evolve this product!

One thing you might like about SHPAML is that you can try before you
buy.  Try it here:

http://shpaml.webfactional.com/try_it

Thanks,

Steve

--

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




Re: style guide/autoformatter/linter for Django templates?

2009-12-01 Thread Steve Howell

On Dec 1, 3:33 am, Tom Evans  wrote:
> On Tue, Dec 1, 2009 at 7:33 AM, Steve Howell  wrote:
> > Just following up on this a few days later, in case it got lost in the
> > shuffle due to the weekend and U.S. holiday.
>
> > On Nov 27, 2:18 pm, Steve Howell  wrote:
> >> I am wondering if there is a style guide anywhere for writing Django
> >> templates.  Also, are there programs to automatically format your
> >> templates...to indent block tags, for example?  I know there are
> >> autoformatters for HTML, but I am not aware of any tools that handle
> >> Django tags.  Also, it would be nice to have a command line tool that
> >> detected unbalanced tags before rendering occurs, knowing, of course,
> >> that that task is a little complicated due to conditionals.
>
> >> [...]
>
> vim 7.2 comes with two syntax, highlighting and indentation modes for django.
>
> "set ft=django" for just django template syntax highlighting/indentation
> "set ft=htmldjango" for mixed HTML/django template syntax highlighting
>

That's a start, but is there anything that runs from the command
line?  Am I correct that vim does not indent blocks for django tags,
only HTML tags?

--

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




Re: style guide/autoformatter/linter for Django templates?

2009-11-30 Thread Steve Howell
Just following up on this a few days later, in case it got lost in the
shuffle due to the weekend and U.S. holiday.

On Nov 27, 2:18 pm, Steve Howell  wrote:
> I am wondering if there is a style guide anywhere for writing Django
> templates.  Also, are there programs to automatically format your
> templates...to indent block tags, for example?  I know there are
> autoformatters for HTML, but I am not aware of any tools that handle
> Django tags.  Also, it would be nice to have a command line tool that
> detected unbalanced tags before rendering occurs, knowing, of course,
> that that task is a little complicated due to conditionals.
>
> [...]

--

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




Re: Stuck with simple query

2009-11-28 Thread Steve Howell

On Nov 28, 8:36 am, Benjamin Wolf  wrote:
> Hi,
>
> I'm trying to create a query like this with django:
> SELECT count(*) As total FROM `disposal` group by(salesman_id)
>
> This gives me the number of total sales for every salesman.
> In django I tried this:
> data = Disposal.objects.annotate(total=Count('salesman'))
> print str(x[0].total)
>
> But total is always 1.
>

What happens when you run the query outside of Django?

You can see the SQL that Django is generating for you by looking at
something like db.connection.queries[-1]['sql'], or for more debugging
goodness, you can install the Django debug toolbar.

--

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




style guide/autoformatter/linter for Django templates?

2009-11-27 Thread Steve Howell
I am wondering if there is a style guide anywhere for writing Django
templates.  Also, are there programs to automatically format your
templates...to indent block tags, for example?  I know there are
autoformatters for HTML, but I am not aware of any tools that handle
Django tags.  Also, it would be nice to have a command line tool that
detected unbalanced tags before rendering occurs, knowing, of course,
that that task is a little complicated due to conditionals.

Here is example code that I would wish to reformat:

{% load i18n %}

{% if show_save %}{% endif %}
{% if show_delete_link %}{% trans "Delete" %}{% endif
%}
{% if show_save_as_new %}{%endif%}
{% if show_save_and_add_another %}{% endif %}
{% if show_save_and_continue %}{% endif %}


It seems like this would be more readable.  The if statements get
indented, except where they are inside an HTML tag.  Also the
statements inside the div get indented.

{% load i18n %}

{% if show_save %}

{% endif %}
{% if show_delete_link %}
{% trans "Delete" %}
{% endif %}
{% if show_save_as_new %}

{%endif%}
{% if show_save_and_add_another %}

{% endif %}
{% if show_save_and_continue %}

{% endif %}


--

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




Re: Issue when saving a model form

2009-11-27 Thread Steve Howell
I am not fully tracking to the problem here, but when it comes to
overriding save() behavior on forms, I find the following helper to be
handy:

def build_instance_from_form(model_form):
instance = model_form.save(commit=False)
return instance

Then in your view code do something like this:

   restaurant = build_instance_from_form(form)
   # fix up data like city
   restaurant.save()

This can help you avoid all the complexity of overriding save() on the
form object and delegating to super(), etc., at least in some cases.

--

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




Re: replicating database changes from one postgres DB to another

2009-07-23 Thread Steve Howell


On Jul 21, 3:18 pm, Wayne Koorts  wrote:
> Hi Steve,
>
> > We have an application where we periodically import data from an
> > external vendor, and the process is mostly automated, but we need to
> > review the data before having it go live.
>
> > We were considering an option where we would run processes on another
> > database, do the manual validation, and then replicate the DB changes
> > to our production database (which would have the same schema).
>
> I do exactly this with one of my sites.  This is my scenario:
>
> 1.  Main database table gets updated automatically every night (this
> is a kind of data that can be automatically refreshed, but that should
> be beside the point for this discussion).  The data first goes into a
> pending table on my dev server, which is exactly the same as the main
> table, with "_pending" appended to the name.
> 2.  The data is then dumped to a file using "psql" and sent via FTP up
> to an equivalent pending table on the production server (via Python
> script in my dev environment).  There is a Python script set up on the
> server to monitor a specific folder for a specific dump file name at
> regular intervals, and if it finds it, imports it into the table also
> with "psql", then deletes the dump file.
> 3.  The data sits in the pending table on the production server until
> I approve it via an admin interface which I have set up Django.
> Basically there is a "DB Admin" area on the site which I have set up
> which shows me four chunks of the data at various points in the table,
> 100 at the start, 100 at 1/4 through, 100 at 3/4 through and then 100
> at the end.  It also shows me the total number of records so that I
> can do a quick visual integrity check.
> 4.  There are "approve" and "reject" buttons at the bottom of the
> approval page.  If I click "approve" it moves the current live table
> data into a backup table (the db admin area also has a restore
> function) and moves the pending data into the live table using a raw
> nested SQL SELECT statement via Django and then empties the pending
> table.  If I click "reject" it just empties the pending table.
>
> These same general steps can be adjusted to accomodate more tables
> etc. as per your requirements.
>

Wayne,

Thanks for your response.

The way that you are doing it was definitely an option we were
considering, but we have just enough tables that I think scaling up
the "pending_" methodology that you describe below would not
really be practical.

The overall process will be very similar, though.  We'll do the import
on some sort of staging database and have an application with approve/
reject buttons to validate the new data is quality for production.


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



replicating database changes from one postgres DB to another

2009-07-21 Thread Steve Howell

We have an application where we periodically import data from an
external vendor, and the process is mostly automated, but we need to
review the data before having it go live.

We were considering an option where we would run processes on another
database, do the manual validation, and then replicate the DB changes
to our production database (which would have the same schema).

One option is to do it all through postgres, but I am thinking there
may be advantages in doing it through django, just in the sense that
it might be easier to script and/or add intelligence to the
replication as needed.

Is there anything in django that would facilitate this?  If not, my
slightly off-topic question would be how best to do this in postgres.
Essentially, we want some process to generate a log of DB inserts/
updates/deletes on the one side and replay it on the other.

Thanks,

Steve

--~--~-~--~~~---~--~~
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: get_or_create() returns "no such savepoint" error

2009-07-08 Thread Steve Howell

See below.

On Jul 8, 10:49 am, Karen Tracey  wrote:
> On Tue, Jul 7, 2009 at 9:05 PM, Steve Howell  wrote:
>
> > On Jul 7, 3:07 pm, Karen Tracey  wrote:
>
> > > > On Jun 29, 10:53 am, Steve Howell  wrote:
> > > > > Hi, I have created a management command that populates some tables in
> > > > > a Postgres database, and I use the handy get_or_create() method in
> > db/
> > > > > models/query.py.  I tried running a command recently where I had
> > > > > inadvertently left some foreign key references dangling around,
>
> > > Could you be a little more specific about what the error was in your
> > code?
>
> > Sorry I never reported the error, but, of course, part of my problem
> > was that the error was caught by the try/except in Django code.
>
> > I did the following sequence, conceptually:
>
> >  1) I had a database with books and authors.
> >  2) I received a new feed of books.
> >  3) I cleaned the books table without cleaning the authors table.
> >  4) When I tried to import the first book, there was still a stale
> > author.
> >  5) Instead of getting the normal integrity error, I got the red
> > herring savepoint error.
> >  6) When I went back and cleaned BOTH tables, everything worked fine.
>
> > > From looking at the full get_or_create routine you include below it isn't
> > > immediately obvious to me where it might be raising an IntegrityError
> > before
> > > the savepoint is created, yet it sounds like that is what is happening.
> >  We
> > > need to understand how that is happening before figuring out what the
> > right
> > > fix is.
>
> > If memory serves correctly, it was this line that raised the original
> > error:
>
> >                obj.save(force_insert=True)
>
> > Here's the code in more context:
>
> >            try:
> >                params = dict([(k, v) for k, v in kwargs.items() if
> > '__' not in k])
> >                params.update(defaults)
> >                obj = self.model(**params)
> >                sid = transaction.savepoint()
> >                obj.save(force_insert=True)
> >                transaction.savepoint_commit(sid)
> >                return obj, True
> >            except IntegrityError, e:
> >                transaction.savepoint_rollback(sid)
> >                try:
> >                    return self.get(**kwargs), False
> >                except self.model.DoesNotExist:
> >                    raise e
>
> But if it's the obj.save(force_insert=True) that is causing the
> IntegrityError, then the savepoint should have been created by the
> immediately preceding line: 'sid = transaction.savepoint()'.  

There's no code there that prevents sid from being None, FWIW.

> Thus
> attempting to rollback that savepoint should not fail.  I was thinking you
> were hitting the IntegrityError earlier, before the savepoint had been
> created (though I couldn't see where that could possibly be happening), but
> if that were the case I think you'd be getting a Python error about sid
> being referenced before being set.  So, the savepoint has been created but
> the DB doesn't seem to know about it, which is a bit of a mystery.
>

Yep, I think it's definitely a strange DB anomaly, and I've seen long
threads about how there have been some disconnects between Postgres
transaction model and how Django works, but they've been a bit above
my head.

I'm pretty confident the savepoint gets created, but just can't roll
back correctly for whatever reason.


> If you look at that code you see it tries to not swallow any IntegrityErrors
> that aren't in fact due to collisions on insert.  

I agree with you there.  I think it's perfectly valid for the code to
reach the except clause and try to do the savepoint_rollback, but it
does not seem to be working.

FWIW I am launching these commands as a management command, so it's
possible that I need to do something in the management command to put
Django into a "normal" transaction mode, although I agree it's strange
that the code wouldn't fail earlier when it's trying to create the
savepoint.

> If the save fails, it
> tries the get again, and if that again returns DoesNotExist then the
> original IntegrityError e is raised.  You have hit an unexpected case where
> the savepoint rollback is failing.  As the code is written I don't see how
> that could be failing, and I don't have time to try to recreate myself right
> now.
>
> What version of PostgreSQL are you running?
>

8.3
--~--~-~--~~~---~--~~
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: get_or_create() returns "no such savepoint" error

2009-07-07 Thread Steve Howell

On Jul 7, 3:07 pm, Karen Tracey  wrote:
>
>
> > On Jun 29, 10:53 am, Steve Howell  wrote:
> > > Hi, I have created a management command that populates some tables in
> > > a Postgres database, and I use the handy get_or_create() method in db/
> > > models/query.py.  I tried running a command recently where I had
> > > inadvertently left some foreign key references dangling around,
>
> Could you be a little more specific about what the error was in your code?

Sorry I never reported the error, but, of course, part of my problem
was that the error was caught by the try/except in Django code.

I did the following sequence, conceptually:

  1) I had a database with books and authors.
  2) I received a new feed of books.
  3) I cleaned the books table without cleaning the authors table.
  4) When I tried to import the first book, there was still a stale
author.
  5) Instead of getting the normal integrity error, I got the red
herring savepoint error.
  6) When I went back and cleaned BOTH tables, everything worked fine.


> From looking at the full get_or_create routine you include below it isn't
> immediately obvious to me where it might be raising an IntegrityError before
> the savepoint is created, yet it sounds like that is what is happening.  We
> need to understand how that is happening before figuring out what the right
> fix is.
>

If memory serves correctly, it was this line that raised the original
error:

obj.save(force_insert=True)


Here's the code in more context:

try:
params = dict([(k, v) for k, v in kwargs.items() if
'__' not in k])
params.update(defaults)
obj = self.model(**params)
sid = transaction.savepoint()
obj.save(force_insert=True)
transaction.savepoint_commit(sid)
return obj, True
except IntegrityError, e:
transaction.savepoint_rollback(sid)
try:
return self.get(**kwargs), False
except self.model.DoesNotExist:
raise e



--~--~-~--~~~---~--~~
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: get_or_create() returns "no such savepoint" error

2009-07-07 Thread Steve Howell

Hi everybody, I posted the following about a week ago and did not get
a response.

I'm hoping it was simply lost in the shuffle the first time, so maybe
it will get an answer now.

If my questions didn't get a response due to some missing information
in my original post, maybe I can provide it now.

On Jun 29, 10:53 am, Steve Howell  wrote:
> Hi, I have created a management command that populates some tables in
> a Postgres database, and I use the handy get_or_create() method in db/
> models/query.py.  I tried running a command recently where I had
> inadvertently left some foreign key references dangling around, but
> instead of a useful error, I instead got the obscure error "no such
> savepoint."  The code catches the original exception that would have
> helped me realize my own error, and instead raises a new exception
> about "no such savepoint."
>
> Here is the code with get_or_create() that obscures the error:
>
>             except IntegrityError, e:
>                 transaction.savepoint_rollback(sid)
>
> In order to see actual errors, I think I need to something with
> management commands that allows the savepoint to be rolled back.  Has
> anybody encountered this before?  I've skimmed some long threads
> pertaining to Django/psycopg/Postgres interactions with respect to
> setting up transaction management, but I have to admit that most of
> the discussion has been over my head.
>
> Thanks,
>
> Steve
>
> P.S.  Here is the entire method for get_or_create(), for more context:
>
>     def get_or_create(self, **kwargs):
>         """
>         Looks up an object with the given kwargs, creating one if
> necessary.
>         Returns a tuple of (object, created), where created is a
> boolean
>         specifying whether an object was created.
>         """
>         assert kwargs, \
>                 'get_or_create() must be passed at least one keyword
> argument'
>         defaults = kwargs.pop('defaults', {})
>         try:
>             return self.get(**kwargs), False
>         except self.model.DoesNotExist:
>             try:
>                 params = dict([(k, v) for k, v in kwargs.items() if
> '__' not in k])
>                 params.update(defaults)
>                 obj = self.model(**params)
>                 sid = transaction.savepoint()
>                 obj.save(force_insert=True)
>                 transaction.savepoint_commit(sid)
>                 return obj, True
>             except IntegrityError, e:
>                 transaction.savepoint_rollback(sid)
>                 try:
>                     return self.get(**kwargs), False
>                 except self.model.DoesNotExist:
>                     raise e
--~--~-~--~~~---~--~~
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: PyDev users: how do you manage tabs?

2009-07-01 Thread Steve Howell


On Jun 30, 10:42 pm, Rex  wrote:
> Kind of a petty question:
>
> I've been using PyDev to do my Django work and find it to be great.
> However, my only gripe is that it's hard to keep track of tabs, since
> they display only the (non-qualified) file name, which is a problem
> given Django's very regular naming scheme. So for example I'll often
> have 4+ tabs that are all named "views.py", and I have to mouse over
> each to find which one is the one I'm looking for.
>

I definitely feel your pain.

One thing that you can do is put view code into files that are not
called "views.py."  It's always a little risky to break the convention
here, but I have done it in on nontrivial projects without major
hangups.

On the other hand I don't think you want to mess with conventions on
models.py and certain other files, but I tend to spend less time
editing those.



--~--~-~--~~~---~--~~
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: no module name xxxx error

2009-06-29 Thread Steve Howell


On Jun 29, 11:05 am, nixon66  wrote:
> I'm getting an error no module name x. I've create all the
> directories and I can see them, but I keep getting this error and
> can't understand why. Any ideas. Not sure why this is happening since
> it did not happen when I've created other apps.

There are many reasons why modules cannot be found, but the most
likely gotcha is that you forgot to create __init__.py.

If __init__.py is already there, then you can help others help you by
listing the things you've verified already (PYTHONPATH, 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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



get_or_create() returns "no such savepoint" error

2009-06-29 Thread Steve Howell

Hi, I have created a management command that populates some tables in
a Postgres database, and I use the handy get_or_create() method in db/
models/query.py.  I tried running a command recently where I had
inadvertently left some foreign key references dangling around, but
instead of a useful error, I instead got the obscure error "no such
savepoint."  The code catches the original exception that would have
helped me realize my own error, and instead raises a new exception
about "no such savepoint."

Here is the code with get_or_create() that obscures the error:

except IntegrityError, e:
transaction.savepoint_rollback(sid)

In order to see actual errors, I think I need to something with
management commands that allows the savepoint to be rolled back.  Has
anybody encountered this before?  I've skimmed some long threads
pertaining to Django/psycopg/Postgres interactions with respect to
setting up transaction management, but I have to admit that most of
the discussion has been over my head.

Thanks,

Steve

P.S.  Here is the entire method for get_or_create(), for more context:

def get_or_create(self, **kwargs):
"""
Looks up an object with the given kwargs, creating one if
necessary.
Returns a tuple of (object, created), where created is a
boolean
specifying whether an object was created.
"""
assert kwargs, \
'get_or_create() must be passed at least one keyword
argument'
defaults = kwargs.pop('defaults', {})
try:
return self.get(**kwargs), False
except self.model.DoesNotExist:
try:
params = dict([(k, v) for k, v in kwargs.items() if
'__' not in k])
params.update(defaults)
obj = self.model(**params)
sid = transaction.savepoint()
obj.save(force_insert=True)
transaction.savepoint_commit(sid)
return obj, True
except IntegrityError, e:
transaction.savepoint_rollback(sid)
try:
return self.get(**kwargs), False
except self.model.DoesNotExist:
raise e

--~--~-~--~~~---~--~~
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: no module name xxxx error

2009-06-29 Thread Steve Howell


On Jun 29, 11:13 am, nixon66  wrote:
> Steve,
>
> The is a __init__.py
>

Ok, you need to provide a little more detail then.  Can you tell us
what your subdirectory structure looks like, and have you put
__init__.py's in enclosing folders?

Sometimes modules fail to import due to syntax errors in the modules
themselves.

Do you have a more specific error message?  Have you verified no typos
in the import statement itself?  Can you import the module from a
manage.py shell?


--~--~-~--~~~---~--~~
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: why doesn't the "with" template tag transverse blocks?

2009-06-24 Thread Steve Howell



On Jun 23, 9:16 pm, Karen Tracey  wrote:
>
> Raising some sort of error for child template content found outside of a {%
> block %} seems like a more reasonable idea.  I have no idea if it's been
> asked for/considered/rejected/etc., nor how hard it would be to do.  If you
> are really interested in pursuing that idea I'd first search the tracker and
> archives of this list to see if it hasn't already been discussed.
>

A similar ticket regarding enclosing child blocks with "if" statements
was closed with the statement that "this is by design."

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

I don't really agree with the design in either case.  I think tags
that are truly outside of derived blocks should create syntax errors,
and tags that surround derived blocks should somehow satisfy the
principle of least astonishment--either apply the conditional or
variable assignment when rendering or raise a syntax error, but don't
just ignore the tags silently.



--~--~-~--~~~---~--~~
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: why doesn't the "with" template tag transverse blocks?

2009-06-23 Thread Steve Howell

The child should either win semantically or fail syntactically.  You
seem to have some sympathy for the latter position.  I think the
current behavior is less than ideal but I have no passion to fix it.
It might be something worth documenting more clearly.  Without
researching tracker I suspect that most folks who encounter this
gotcha either work around it or go to a different templating system.
The OP is using generics so will probably be wise to stick with django
templates and slightly repetitive code.

On Jun 23, 9:16 pm, Karen Tracey  wrote:
> On Tue, Jun 23, 2009 at 11:05 PM, Steve Howell  wrote:
> > > {% extends "base_form.html" %}
> > > {% with form.instance as object %}
>
> > I understand why tags outside the block would not render anything
> > within the parent but it is not as clear to me why the with statement
> > would not change the context for template code that it lexically
> > encloses.  It seems like this code should either dwim or raise an
> > exception.
>
> It doesn't lexically enclose anything if it is inside a child template and
> not inside a {% block %}.
>
> Consider:
>
> parent.html:
>
> {% with something as x %}
> {% block b1 %} {{ x }} in parent b1{% endblock %}
> {% block b2 %} {{ x }} in parent b2{% endblock %}
> {% endwith %}
> {% with something_else as x %}
> {% block b3 %}{{ x }} in parent b3{% endblock %}
> {% endwith %}
>
> child.html:
>
> {% extends "parent.html" %}
> {% with something_else_again as x %}
> {% block b3 %}{{ x }} in child b3{% endblock %}
> {% block b2 %}{{ x }} in child b2{% endblock %}
> {% endwith %}
> {% with yet_even_something_else as x %}
> {% block b1 %}{{ x }} in child b1{% endblock %}
> {% endwith %}
>
> If those with/endwiths in child.html were to have some effect, what would it
> be?  Where would you place them in the fully-block-substituted parent
> template?  something_else_again being x encloses blocks b3 and b2 in
> child.html, yet in the parent template these blocks are found in a different
> order and have different with's enclosing them...which withs win?  I just
> don't see any sensible way to make this "work".
>
> Raising some sort of error for child template content found outside of a {%
> block %} seems like a more reasonable idea.  I have no idea if it's been
> asked for/considered/rejected/etc., nor how hard it would be to do.  If you
> are really interested in pursuing that idea I'd first search the tracker and
> archives of this list to see if it hasn't already been discussed.
>
> Karen
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: why doesn't the "with" template tag transverse blocks?

2009-06-23 Thread Steve Howell



On Jun 23, 7:29 pm, Karen Tracey  wrote:
> On Tue, Jun 23, 2009 at 10:16 PM, Steve Howell  wrote:
>
> > Nothing posted is outside a block but it could be that the parent has
> > no title block?
>
> I can't parse this sentence.  The part of the original post where things
> didn't work is here:
>
> {% extends "base_form.html" %}
> {% with form.instance as object %}
>

I understand why tags outside the block would not render anything
within the parent but it is not as clear to me why the with statement
would not change the context for template code that it lexically
encloses.  It seems like this code should either dwim or raise an
exception.
> {% block title%}
>    {{object.title}} <- not displayed :(
> {% endblock %}
>
> {% with %} is not inside a block, so there is no place for it to go in the
> parent template.  That's why {{ object.titlte }} won't work inside the
> over-ridden title block -- without the {% with %}, object hasn't been
> assigned a value.
>
> Karen
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: why doesn't the "with" template tag transverse blocks?

2009-06-23 Thread Steve Howell

Nothing posted is outside a block but it could be that the parent has
no title block?

On Jun 23, 6:47 pm, Karen Tracey  wrote:
> On Tue, Jun 23, 2009 at 8:34 PM, nbv4  wrote:
>
> > I'm trying to set up a template for all my forms, but I'm having
> > trouble using the {% with %} block:
>
> > {% extends "base_form.html" %}
> > {% with form.instance as object %}
>
> > {% block title%}
> >    {{object.title}} <- not displayed :(
> > {% endblock %}
>
> > {% block body %}
> > {% with form.instance as object %}
> >    {{object.title}} <- now it is displayed
> > {% endwith%}
> > {% endblock %}
>
> > {% endwith %}
>
> > The 'with' tag works, but only within other blocks. Is there any way
> > to get around this without wrapping a hundred 'with' blocks around
> > each block in my template?
>
> I don't think what you're describing has anything to do with the {% with %}
> tag specifically.  You're dealing with a child template here -- one that
> starts with an {% extends %} tag.  Nothing placed outside of {% block %}
> tags in a child template has any effect on the rendered template.  A child
> template simply supplies block contents to override what has been specified
> in the parent template, so everything in a child template must be included
> inside {% block %} tags. (If it is not specified inside a {% block %}, where
> should it go in the parent template?)  See:
>
> http://docs.djangoproject.com/en/dev/topics/templates/#id1
>
> Karen
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



currying variables into ModelForm subclasses

2009-06-23 Thread Steve Howell

I have an application with a single method called member_create that
presents a form to collect membership information and save it to the
database.  Depending on the project configuration and user I have
different membership forms, so I have a line of code like this in
member_create():

member_edit_form_class = get_member_edit_form_class
(membership_type)

Up until recently, get_member_edit_form would return either
GenericMemberEditForm or SpecialMemberEditForm, where the latter
inherited from the former.  All of that was relatively
straightforward.  Just to be clear, get_member_edit_form_class was
returning a class, not an instance, since member_create would
instantiate the class later as needed:

if request.method == 'POST':
form = member_edit_form_class(request.POST, request.FILES)
...
else:
form = member_edit_form_class()


Things got a little more interesting, though, when our "Special"
customer wanted further refinements in the form's behavior based on
membership type.  Trying to keep member_create() generic, I put logic
like this in the SpecialMemberEditForm class:

def __init__(self, *args, **kwargs):
membership_type = kwargs.pop('membership_type', None)
super(SpecialMemberEditForm, self).__init__(*args, **kwargs)
if membership_type.name == 'whatever':
 self.fields['options'].queryset = ...
else:
 self.fields['options'].queryset = ...

I wanted the member_create() method not to have any knowledge of this
extra parameter, for a few reasons:

  1) I wanted to keep member_create() as generic as possible.
  2) I already had a factory method called get_member_edit_form_class
(), so I wanted the factory method to configure the classes as
needed.  (I am using "factory" in the loose sense--I don't know the
exact terminology for a method that returns a class, not an instance.)
  3) I didn't want member_create() to pass in the extra parameter to
any class other than SpecialMemberEditForm, since
GenericMemberEditForm had no use for that parameter, and it would be
brittle to have all member edit forms follow the contract of popping
off unused parameters.
  4) To elaborate on the prior point, the forms all have BaseModelForm
as an ancestor, and BaseModelForm's __init__ method cannot deal
gracefully with extraneous keyword arguments, perhaps for good reason.

In order to allow get_member_edit_form_class to configure
SpecialMemberEditForm as needed, I wrote code like this:

def special_get_member_edit_form_class(membership_type):
# we curry membership_type here so that other code never needs
to
# deal with extra parms
def curry(*args, **kwargs):
kwargs['membership_type'] = membership_type
return SpecialMemberEditForm(*args, **kwargs)
return curry

Essentially, the method above is not returning a class--instead it's
returning a method, but that method generally provides the illusion of
being a class in a pythonic sort of way, since it has the same
behavior when used as a callable (it returns an instance).

This worked exactly as expected in member_create(), but then I got
around to updating member_update(), which works like this:

member_edit_form_class = get_member_edit_form_class
(membership_type)

return create_update.update_object(request,
   post_save_redirect=...,
 
form_class=member_edit_form_class,
 
template_name='member_form.html',
   **kwargs)

Here is where the illusion broke down.  The update_object method
really wants member_edit_form_class to be a subclass of Form, not just
a callable that produces a Form subclass instance.

In particular, this line of code fails inside get_model_and_form_class
(), which gets called by update_object():

return form_class._meta.model, form_class

Basically what is happening at this point is that form_class is the
same as curry above, and curry does not have an attribute called
_meta, since curry is not exactly a subclass of Form; instead, it is a
method that returns an instance of Form.  So I added one line of code
to solve the problem:

curry._meta = SpecialMemberEditForm._meta

So now everything works, but it still feels a little dirty and
brittle, and I'm wondering if others have solved similar problems
using different design patterns.  The situation is not as esoteric as
perhaps it looks--really, it's just a scenario where we are trying to
keep one method DRY with a couple different forms that can be plugged
in, and one form class needs to be configured before instantiation.

I know that django has some helpers related to partial functions, but
I haven't had luck tracking down documentation, so any pointers there
are welcome, even if they don't exactly solve my problem.  I think I
am doing something a little different from the normal partial/currying
use case, but I also bet somebody has solved my problem before.


ANN: elif added to smart_if tag

2009-06-17 Thread Steve Howell

For those of you who, like me, have enjoyed SmileyChris's excellent
smart if tag, you may find the following extension useful:

http://www.djangosnippets.org/snippets/1572/

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

2009-06-17 Thread Steve Howell

Another option is to install the snippet below, which supports "in":

http://www.djangosnippets.org/snippets/1350/

On Jun 17, 1:53 pm, Ben Davis  wrote:
> Nope, you'll need to set a variable in your view.  You can also try creating
> your own filter such that {% if friend|is_in_group %}  would work (it's
> pretty easy to do, just check out the docs for custom template filters)
>
> On Tue, Jun 16, 2009 at 2:40 PM, CrabbyPete  wrote:
>
> > Is there a way do something like this with the template system
> > {% if friend in group.members.all %} or simply {% friend in
> > group.members.all %}
>
>

--~--~-~--~~~---~--~~
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: Problem with performance on a django site

2009-05-28 Thread Steve Howell

On May 28, 8:19 am, jrs_66  wrote:
> 250 queries on one page seems to me to be dangerously high.  I would
> have to guess you could reduce that significantly.  Turn on query
> output to see if the Django ORM isn't creating sloppy queries in
> loops.  My guess is that with some code alterations you could help
>

This seems like a good place to start to me.

As far as debugging, there might be some tools on djangosnippets that
might help the original poster:

http://www.djangosnippets.org/snippets/461/

As somebody else suggested on the thread, I'm not entirely sure about
the diagnosis that the template rendering is really the bottleneck,
since queries are lazily executed.

For debugging purposes, you can force queries to be executed earlier
with little impact on the template by turning them into lists, which
helps you to more easily identify bottlenecks (but not good for prod,
it uses more memory).

objs = list(objs)

To reduce the sheer number of queries, I recommend experimenting the
select_related() feature.  I haven't used it in Django, but I've used
equivalent features in Rails, and it can lead to pretty drastic
speedups, but I'll give the caveat that I was usually trying to reduce
delays from latency.  Here are docs on select_related():

http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4

Also, as always, it might make good sense to simply divide and
conquer, refactor as you go, 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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Mutiple template inheritance

2009-05-28 Thread Steve Howell


On May 28, 7:26 am, "Daniele Procida" 
wrote:
> On Thu, May 28, 2009, Masklinn  wrote:
> >> I need to create some templates that will cover a number of cases:
>
> >>    display navigation menu: yes or no
> >>    display additional info box: yes or no
>
> >> In other words, there are a total of four cases that need to be  
> >> provided for.
>
> >> I understand how to use template inheritance so that a derived  
> >> template
> >> will contain a block that overrides the default presence of the
> >> navigation menu.
>
> >> I could create a total of four derived templates, one for each case;
> >> that would be OK too.
>
> >> However, the number of derived templates rises exponentially. If I
> >> needed to cover a couple of additional options, say:
>
> >>    use low-bandwidth styling: yes or no
> >>    display secret information: yes or no
>
> >> then I'd need 16 templates to extend the base.
>
> >> There must be a better way to do this - what is it?
>
> >Template inclusion instead of template inheritance?
>
> You mean, by using a series of tags like:
>
> {% if [condition] %}
>     {% include "navigationmenu.html" %}
> {% endif %}
>
> {% if [condition2] %}
>     {% include "additionalinfo.html" %}
> {% endif %}
>
> and so on?
>

Yes, that could work.

Also, if you evaluate the conditions in the view, instead of the
template, you can pass in the file to be included as a parameter.

if condition1:
context['extra_includes'] = 'navigationmenu.html'
elif condition2:
context['extra_includes'] = 'additionalinfo.html'

This keeps your template nice and clean:

{% include extra_includes %}

Of course, the tradeoff is that you might view the conditions as
having more context in the template.

Here are the docs for include:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include
--~--~-~--~~~---~--~~
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: Weird problem in url resolving after restarting django dev. server

2009-05-27 Thread Steve Howell


On May 27, 8:23 am, Konstantin S  wrote:
> On May 26, 9:28 pm, Steve Howell  wrote:
>
> [...]
> > Perhaps you can try to step through the code in the debugger.  The top-
> > level method involved in reversing URLs are not super complicated.
> > You can set a breakpoint in django/core/urlresolver.py to see what's
> > happening.
>
> Steve, thanks for your suggestion to trace django code, I've finally
> found what was the problem. Don't know how to fix it yet so I disabled
> some fancy ajax-based functionality. But at least I am no getting this
> mysterious 500 errors any more.

You're welcome, glad you're making progress.

Here is a snippet I found related to debugging URL problems, just in
case others are watching this thread or it comes up in Google.

http://www.djangosnippets.org/snippets/1434/


--~--~-~--~~~---~--~~
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: Weird problem in url resolving after restarting django dev. server

2009-05-26 Thread Steve Howell


On May 26, 6:43 am, Konstantin S  wrote:
> On May 20, 2:02 pm, Konstantin S  wrote:
>
> > Hello!
>
> > I have a very strange problem and really don't know where to start in
> > hunting it down. My app uses django-registration, all works fine but
> > if I been logged in restart django dev. server I immediately get
> > TemplateSyntaxError:
>
> > Caught an exception while rendering: Reverse for
> > 'myapp.add_media_action' with arguments '()' and keyword arguments
> > '{}' not found.
>
> > It seems like after restarting django couldn't resolve url's names. I
> > know this is a very vague and incomplete description but may be it is
> > a very well known problem that you can identify on the spot ?
>
> Continue my story...
>
> I've changed a bit template code:
>
> was: Add new
> now: Add new
>
> Error message also changed, now it is:
>
> Caught an exception while rendering: Reverse for
> ''
> with arguments '()' and keyword arguments '{}' not found.
>
> I have no idea how to fix this problem, please help if you can.

>From the docs you might want to take advantage of the name= parameter
in your URLS setup and do something like {% url 'add_media_action'
%}.  Not sure about the quoting, as the docs are vague about quoting
literals.

'''
New in Django 1.0: Please, see the release notes

If you're using named URL patterns, you can refer to the name of the
pattern in the url tag instead of using the path to the view.
'''

It seems like the login_required method may be confusing you:

url(r'^add/$', login_required(views.add_media),
name = 'add_media_action'),

I am guessing the login_required method returns another method that
gets set up into the url data structure, so the reverse code has no
way of knowing about views.add_media anymore.   Does that make sense
to you?

Perhaps you can try to step through the code in the debugger.  The top-
level method involved in reversing URLs are not super complicated.
You can set a breakpoint in django/core/urlresolver.py to see what's
happening.

Look for this snippet of code (which may be slightly different for
your version of django, but I doubt it's changed too much):

def reverse(self, lookup_view, *args, **kwargs):
if args and kwargs:
raise ValueError("Don't mix *args and **kwargs in call to
reverse()!")
try:
lookup_view = get_callable(lookup_view, True)
except (ImportError, AttributeError), e:
raise NoReverseMatch("Error importing '%s': %s." %
(lookup_view, e))
possibilities = self.reverse_dict.getlist(lookup_view)
for possibility, pattern in possibilities:
for result, params in possibility:
if args:
if len(args) != len(params):
continue
unicode_args = [force_unicode(val) for val in
args]
candidate =  result % dict(zip(params,
unicode_args))
else:
if set(kwargs.keys()) != set(params):
continue
unicode_kwargs = dict([(k, force_unicode(v)) for
(k, v) in kwargs.items()])
candidate = result % unicode_kwargs
if re.search(u'^%s' % pattern, candidate, re.UNICODE):
return candidate
raise NoReverseMatch("Reverse for '%s' with arguments '%s' and
keyword "
"arguments '%s' not found." % (lookup_view, args,
kwargs))

--~--~-~--~~~---~--~~
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: Weird problem in url resolving after restarting django dev. server

2009-05-20 Thread Steve Howell

On May 20, 10:49 am, Konstantin S  wrote:
> On 20 май, 19:43, Steve Howell  wrote:
>
>
>
> > To elaborate on Karen's suggestion, one way to see which URLs are
> > among the candidates for resolving the reverse match is to
> > deliberately hit a bad URL like the following:
>
> >http://localhost:8000/something_that_does_not_match_urls
>
> > If you have appropriate debug settings, you should then get back a
> > list of all the patterns that django knows about in your browser.  If
> > you don't see the URL for add_media_action, then you probably have
> > some issue with the environment, as Karen suggests.
>
> Yes, there is URL for 'add_media_action'. As I said before all works
> as expected till I restart dev. server.
>

Just to be clear, I'm suggesting that you try the technique above
after you restart the dev server.

--~--~-~--~~~---~--~~
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: Callable objects instead of functions in views.py

2009-05-20 Thread Steve Howell


On May 20, 6:33 am, Filip Gruszczyński  wrote:
>
> I have recently created a class:
>
> class RequestService:
>
>         def __call__(self, request, *args, **kwargs):
>                 self.prepare(request, *args, **kwargs)
>                 if request.method == 'POST':
>                         value = self.servePost(request, *args, **kwargs)
>                         if value is not None:
>                                 return value
>                 else:
>                         value = self.serveGet(request, *args, **kwargs)
>                         if value is not None:
>                                 return value
>                 return self.serveBoth(request, *args, **kwargs)
>
> When I need another view, I inherit from it and create an instance,
> that is used instead of a function. I decided to use it, because my
> views functions began to grow big and I wanted to divide them into
> smaller chunks, and yet keep them logically connected.
>

I don't have major beefs with your solution, but I'll offer a few
alternatives that might accomplish the same thing, without creating
inheritance.  Inheritance feels a little heavy for what you're trying
to provide, which is basically just a common method to tie together
three other methods.  Seems like it might be more pythonic to do
simple duck typing, but that's just my two cents of course.

1) Just pass in the three functions--this gives you the ultimate
flexibility to reuse methods between views.

def request_service(request, serve_post, serve_get, serve_both, *args,
**kwargs)

def blog_view(request,...):
return request_service(request, serve_blog_post, serve_blog_get,
serve_blog_both, ..)

OR

2) Replace inheritance with delegation.

def request_service(request, service_provider, *args, **kwargs)

class BlogServiceProvider:
def serve_post(..)
def serve_get(...)
def serve_post(..)

def blog_view(request,...):
return request_service(request, BlogServiceProvider(), ..)


--~--~-~--~~~---~--~~
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: Weird problem in url resolving after restarting django dev. server

2009-05-20 Thread Steve Howell

On May 20, 6:41 am, Karen Tracey  wrote:
> On Wed, May 20, 2009 at 7:28 AM, Konstantin S  wrote:
>
> > On 20 май, 14:02, Konstantin S  wrote:
> > > Hello!
>
> > > I have a very strange problem and really don't know where to start in
> > > hunting it down. My app uses django-registration, all works fine but
> > > if I been logged in restart django dev. server I immediately get
> > > TemplateSyntaxError:
>
> > > Caught an exception while rendering: Reverse for
> > > 'myapp.add_media_action' with arguments '()' and keyword arguments
> > > '{}' not found.
>
> > > It seems like after restarting django couldn't resolve url's names. I
> > > know this is a very vague and incomplete description but may be it is
> > > a very well known problem that you can identify on the spot ?
>
> > I've tried it in a django shell.  'myapp.add_media_action' really does
> > not resolve, but 'add_media_action' resolves fine. That makes it even
> > more puzzling. Why am I getting 'myapp.add_media_action' instead of
> > 'add_media_action' ?
>
> That's a misleading message. The code tries to reverse the requested name
> with the project  name prepended only after attempting to reverse the
> requested name on its own has failed.  See:
>
> http://code.djangoproject.com/browser/django/trunk/django/template/de...
>
> That code was recently (r10350, on April 1st) fixed so that the original
> NoReverseMatch is raised instead of the one resulting from the last-ditch
> attempt to find a reversal.
>
> So, ignore the 'myapp' part of the message.  The real issue is that your
> server can't reverse 'add_media_action', even though you can reverse it from
> the shell.  There's got to be some difference between your server
> environment and the shell environment you are using that is causing that.
>

Konstantin,

To elaborate on Karen's suggestion, one way to see which URLs are
among the candidates for resolving the reverse match is to
deliberately hit a bad URL like the following:

http://localhost:8000/something_that_does_not_match_urls

If you have appropriate debug settings, you should then get back a
list of all the patterns that django knows about in your browser.  If
you don't see the URL for add_media_action, then you probably have
some issue with the environment, as Karen suggests.

If you do see the URL for add_media_action, then you probably want to
focus on other theories, such as the wrong number of arguments or
something similar.

Obviously, more information would help people help you figure this
out.  At the very least you should provide the line of code from
urls.py that establishes the mapping for add_media_action.

--~--~-~--~~~---~--~~
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 tags and variables overlapping

2009-05-03 Thread Steve Howell


On May 3, 1:15 pm, Julián C. Pérez  wrote:
>
> example:
> {% createLink "a link to something" src "class attr" "id attr" "title
> attri" %}
> would output something like:
> a
> link to something
>
> how can i make the 'src' input to be the result of url tag calling a
> valid view??

I recommend the captureas snippet below:

http://www.djangosnippets.org/snippets/545/

You will see in the author's writeup that they are solving essentially
the same problem as you are trying to solve.

(I found it by googling "django snippet assign variable.")

> i mean, something like:
> {% createLink "a link to something" "{% url aValidView %}" "class
> attr" "id attr" "title attri" %} # obviously that is wrong... just to
> make my point
>  url/="src">a link to something
>

As others have mentioned in this thread, I don't recommend actually
trying to call the url tag that far "inline," i.e. in another tag call
(createLink).

Hopefully the captureas tag gets you a lot closer to where you want to
be.  Do something like this:

{% captureas valid_view_url %}}{% url aValidView %} {% endcaptureas %}
{% createLink "a link to something" valid_view_url "class attr" "id
attr" "title attri" %}

I would stop reading this now. :)

But I can sympathize with the gist of your dilemma...sometimes you
want to inject a little power into the template language, live on the
edge a bit.  The code below might provide some inspiration for you,
although it doesn't really solve your problem, just suggests some
techniques at your disposal.

'''
  A node that gets re-rendered as needed.
'''
class RenderNode(Node):
def __init__(self, var):
self.var = var

def render(self, context):
val = resolve_variable(self.var, context)
try:
return val.render(context)
except:
return val

@register.tag
def render(parser, token):
"""
if a variable resolves to a template object, expands the object...
allows you to do something like this
context['name'] = 'Steve'
context['greeting'] = template.Template('Hi {{ name }}, nice to
meet you!')
template.html:
{{ render greeting}}
"""
bits = token.split_contents()
tag = bits.pop(0)
try:
var = bits.pop(0)
except IndexError:
raise TemplateSyntaxError, "%r tag requires at least one
param" % tag
return RenderNode(var)

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