from future url -- argh

2012-06-14 Thread JeffH
django 1.4

topapp
  urls.py
...
url(r'^shows/', include('shows.urls')),
  template
base.html
... {% url shows.views.customers %}

shows
  urls.py
..
url(r'^customers/$', 'shows.views.customers')

The above works just fine -- everything is happy except for the deprecation 
warning in debug mode.

So I modify base.html  and add {% load url from future %}  to the top, and 
then put single quotes around the argument {% url 'shows.views.customers' 
%} and django goes Boom!  
"django.core.urlresolvers.NoReverseMatch -- NoReverseMatch: Reverse for '' 
with arguments '()' and keyword arguments '{}' not found."

I've become dizzy trying the different methods specified in the docs 
including setting a name= attr in the shows/urls.py 
url(r'^customers/$', 'shows.views.customers', name='fido')
{% url 'fido' %}

and I get the same message.  Other variations tried:
{% url 'shows_views.customers' %}  - same error

If someone can help me out,I'd appreciate it.

Best,

Jeff

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/x4uqjgipT9YJ.
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: can't add via admin, get django template error

2010-12-09 Thread JeffH
I had defined a custom admin class for that model. I commented it out
and went with the default admin class, and got the same error trying
to create a new record. So didn't think it was the admin.

Then I looked at the date fields on that model. Turned out that
specifying a default date as a string was the problem:
  publish_date = models.DateTimeField(default='2039-12-31') # don't!

Even though it works with a standard ModelForm form, ie gets displayed
in the UI properly, is accepted as a valid date by the Form
validation, and gets inserted into the db properly.

I think that the admin should accept such a (properly formed) date
string. Or else the model shouldn't validate.

On Dec 8, 2:20 pm, Wayne Smith  wrote:
> On Wed, Dec 8, 2010 at 10:49 AM, JeffH  wrote:
> > So I'm working along, everything's humming fine. Then I try to add a
> > record via the admin, and get the following:
>
> > TemplateSyntaxError at /admin/expert/expertresponse/add/
> > Caught AttributeError while rendering: 'unicode' object has no
> > attribute 'date'
>
> > [snip]
>
> > Template error
>
> > In template c:\python26\lib\site-packages\django\contrib\admin
> > \templates\admin\includes\fieldset.html, error at line 12
> > Caught AttributeError while rendering: 'unicode' object has no
> > attribute 'date'
> > 2       {% if fieldset.name %}{{ fieldset.name }}{% endif %}
> > 3       {% if fieldset.description %} > class="description">{{ fieldset.description|safe }}{% endif %}
> > 4       {% for line in fieldset %}
> > 5       
> > 6       {{ line.errors }}
> > 7       {% for field in line %}
> > 8        > endif %}>
> > 9       {% if field.is_checkbox %}
> > 10      {{ field.field }}{{ field.label_tag }}
> > 11      {% else %}
> > 12      {{ field.label_tag }}{{ field.field }}
>
> > I can add records via a ModelForm without problem, it just doesn't
> > work in the admin.
>
> > As you probably surmised from the error, the admin is expecting a field
>
> attribute of type date on your  model object (line?).  Anyway, what is
> getting passed is an Unicode object, which obviously does not have the
> attribute (field) it is looking for.
>
> I would guess that the problem lies somewhere in your admin file
> (admin.py).  What are the contents of 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-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.



can't add via admin, get django template error

2010-12-08 Thread JeffH
So I'm working along, everything's humming fine. Then I try to add a
record via the admin, and get the following:

TemplateSyntaxError at /admin/expert/expertresponse/add/
Caught AttributeError while rendering: 'unicode' object has no
attribute 'date'

[snip]

Template error

In template c:\python26\lib\site-packages\django\contrib\admin
\templates\admin\includes\fieldset.html, error at line 12
Caught AttributeError while rendering: 'unicode' object has no
attribute 'date'
2   {% if fieldset.name %}{{ fieldset.name }}{% endif %}
3   {% if fieldset.description %}{{ fieldset.description|safe }}{% endif %}
4   {% for line in fieldset %}
5   
6   {{ line.errors }}
7   {% for field in line %}
8   
9   {% if field.is_checkbox %}
10  {{ field.field }}{{ field.label_tag }}
11  {% else %}
12  {{ field.label_tag }}{{ field.field }}

I can add records via a ModelForm without problem, it just doesn't
work in the admin.

-- 
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: HttpResponseRedirect

2010-08-07 Thread JeffH
Another approach that I used recently:

# urls.py
   (r'^ThankYou/(?P\d{4})/$', views.ThankYou),

# message defs in views.py
# messages for ThankYou page
ty_messages = {
'' : 'Invalid message specified.',
'0001' : 'Pending dealer record has been re-saved, awaiting
approval.',
'0002' : 'Pending dealer record has been saved, awaiting
approval.',
...
}

# function in views.py
def ThankYou(request, ty_msg_id):
c = Context({
'request' : request,
'show_admin' : request.user.is_authenticated(),
'ty_message' : ty_messages.get(ty_msg_id,
ty_messages['']),
})
t = get_template('ThankYou.html')
html = t.render(c)
return HttpResponse(html)

# usage example

return HttpResponseRedirect('/ThankYou/0089')

--Jeff


On Aug 6, 8:33 am, bagheera  wrote:
> I have two pages with two different forms. Each, if validated, redirects  
> to "thanks" page. I want to customize this behavior, so "thanks" page  
> should display different message, regarding witch form was invoked, or  
> redirects to "/' if no redirection took place (like user typed in browser  
> "test.com/thanks")
> Unfortunately,  HttpResponseRedirect takes only one argument. How can i  
> pass right message anyway? Or mb there is some workaround, like i could  
> check in "thanks" view, from what page it was redirected?
>
> --
> Linux user

-- 
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: outer join in orm

2010-06-21 Thread JeffH
Doing a nested list comp has to be less efficient than an outer join
done at the db level. For my issue, it's a relatively small data set,
so I'd rather be more pythonic than eg running raw sql. Nonetheless, I
view this as a weakness in Django's ORM, and would plead with TPTB to
provide a solution, not that it would affect my current problem.

On Jun 21, 11:46 am, "euan.godd...@googlemail.com"
 wrote:
> AFAIK there is no direct way to do this sort of thing in a single
> query. select_related will only get foreign key relations into the
> query so the ORM will always do an SQL query for each row in your many
> to many. In these types of situations I tend to select everything I
> need and then run some sort of pre-processing to put the two sets
> together, thus ensuring only 2 queries rather than n+1 (where n is the
> number of items in your original queryset).
>
> Scott Gould's answer is about as good as you'll get I reckon.
>
> On Jun 21, 3:37 pm, JeffH  wrote:
>
> > That looks reasonable... but I wonder if the ORM can do it directly
> > somehow. Anyone?
>
> > On Jun 21, 10:14 am, Scott Gould  wrote:
>
> > > There may well be a better way to do this, especially since it's been
> > > a good year since I was struggling with this myself. (Very similar
> > > case to yours, different subject matter of course.)
>
> > > The way I ended up doing it was to use a template tag and some list
> > > comprehensions to whittle things down. E.g.:
>
> > > questions = Questions.objects.all()
> > > answers = Answers.objects.filter(candidate=my_candidate)
>
> > > questions_and_answers = [(q, [a for a in answers if a.question = q])
> > > for q in questions]
>
> > > ...which should give you a list of (question, )
> > > tuples.
>
> > > On Jun 21, 10:00 am, JeffH  wrote:
>
> > > > To clarify: Each race has a set of questions. The candidate may have
> > > > responded to none, some, or all. The answers are linked to the
> > > > candidate (and to the question). For each candidate, I want to display
> > > > all the questions, with or without answer. The way it works currently,
> > > > only the questions with answers get displayed.
>
> > > > On Jun 21, 8:41 am, Daniel Roseman  wrote:
>
> > > > > On Jun 21, 12:51 pm, JeffH  wrote:
>
> > > > > > I have some models that (simplified) look like the following.
>
> > > > > > class Answer(models.Model):
> > > > > >     id = models.CharField(max_length=32, primary_key=True)
> > > > > >     text = models.TextField(blank=False)
> > > > > >     question = models.ForeignKey(Question)
> > > > > >     candidate = models.ForeignKey(Candidate)
>
> > > > > > class Question(models.Model):
> > > > > >     id = models.CharField(max_length=32, primary_key=True)
> > > > > >     text = models.TextField(blank=False)
>
> > > > > > class Candidate(models.Model):
> > > > > >     id = models.CharField(max_length=32, primary_key=True)
> > > > > >     name = models.CharField(max_length=32, blank=False)
>
> > > > > > class Race(models.Model):
> > > > > >     id = models.CharField(max_length=32, primary_key=True)
> > > > > >     name = models.CharField(max_length=128, blank=False)
> > > > > >     questions = models.ManyToManyField(Question)
> > > > > >     candidates = models.ManyToManyField(Candidate)
>
> > > > > > So, a Race has Candidates and Questions, and a Candidate has 
> > > > > > Answers.
> > > > > > Each answer is associated with a Question and a Candidate. 
> > > > > > Displaying
> > > > > > the question associated with an answer is easy:
>
> > > > > > # context variable in view
> > > > > >     answers = Answer.objects.filter(candidate=candidate)
>
> > > > > > # template code
> > > > > >     
> > > > > >     {% for answer in answers %}
> > > > > >     
> > > > > >         {{answer.question.text}}
> > > > > >         {{answer.text}}
> > > > > >     
> > > > > >     {% endfor %}
> > > > > >     
>
> > > > > > From the point of view of the Candidate, I need to display all the
> > > > > > questions, including the ones without Answers. I know how to to do
> > > > > > this using raw sql and an outer join. How to do it in the orm?
>
> > > > > > Thanks in advance for any ideas.
>
> > > > > > --Jeff
>
> > > > > Not quite enough information here to answer. What are you wanting to
> > > > > join? If you just want to display all the questions, why do you need a
> > > > > join at all?
> > > > > --
> > > > > DR.
>
>

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



Re: outer join in orm

2010-06-21 Thread JeffH
That looks reasonable... but I wonder if the ORM can do it directly
somehow. Anyone?

On Jun 21, 10:14 am, Scott Gould  wrote:
> There may well be a better way to do this, especially since it's been
> a good year since I was struggling with this myself. (Very similar
> case to yours, different subject matter of course.)
>
> The way I ended up doing it was to use a template tag and some list
> comprehensions to whittle things down. E.g.:
>
> questions = Questions.objects.all()
> answers = Answers.objects.filter(candidate=my_candidate)
>
> questions_and_answers = [(q, [a for a in answers if a.question = q])
> for q in questions]
>
> ...which should give you a list of (question, )
> tuples.
>
> On Jun 21, 10:00 am, JeffH  wrote:
>
> > To clarify: Each race has a set of questions. The candidate may have
> > responded to none, some, or all. The answers are linked to the
> > candidate (and to the question). For each candidate, I want to display
> > all the questions, with or without answer. The way it works currently,
> > only the questions with answers get displayed.
>
> > On Jun 21, 8:41 am, Daniel Roseman  wrote:
>
> > > On Jun 21, 12:51 pm, JeffH  wrote:
>
> > > > I have some models that (simplified) look like the following.
>
> > > > class Answer(models.Model):
> > > >     id = models.CharField(max_length=32, primary_key=True)
> > > >     text = models.TextField(blank=False)
> > > >     question = models.ForeignKey(Question)
> > > >     candidate = models.ForeignKey(Candidate)
>
> > > > class Question(models.Model):
> > > >     id = models.CharField(max_length=32, primary_key=True)
> > > >     text = models.TextField(blank=False)
>
> > > > class Candidate(models.Model):
> > > >     id = models.CharField(max_length=32, primary_key=True)
> > > >     name = models.CharField(max_length=32, blank=False)
>
> > > > class Race(models.Model):
> > > >     id = models.CharField(max_length=32, primary_key=True)
> > > >     name = models.CharField(max_length=128, blank=False)
> > > >     questions = models.ManyToManyField(Question)
> > > >     candidates = models.ManyToManyField(Candidate)
>
> > > > So, a Race has Candidates and Questions, and a Candidate has Answers.
> > > > Each answer is associated with a Question and a Candidate. Displaying
> > > > the question associated with an answer is easy:
>
> > > > # context variable in view
> > > >     answers = Answer.objects.filter(candidate=candidate)
>
> > > > # template code
> > > >     
> > > >     {% for answer in answers %}
> > > >     
> > > >         {{answer.question.text}}
> > > >         {{answer.text}}
> > > >     
> > > >     {% endfor %}
> > > >     
>
> > > > From the point of view of the Candidate, I need to display all the
> > > > questions, including the ones without Answers. I know how to to do
> > > > this using raw sql and an outer join. How to do it in the orm?
>
> > > > Thanks in advance for any ideas.
>
> > > > --Jeff
>
> > > Not quite enough information here to answer. What are you wanting to
> > > join? If you just want to display all the questions, why do you need a
> > > join at all?
> > > --
> > > DR.
>
>

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



Re: outer join in orm

2010-06-21 Thread JeffH
To clarify: Each race has a set of questions. The candidate may have
responded to none, some, or all. The answers are linked to the
candidate (and to the question). For each candidate, I want to display
all the questions, with or without answer. The way it works currently,
only the questions with answers get displayed.

On Jun 21, 8:41 am, Daniel Roseman  wrote:
> On Jun 21, 12:51 pm, JeffH  wrote:
>
>
>
> > I have some models that (simplified) look like the following.
>
> > class Answer(models.Model):
> >     id = models.CharField(max_length=32, primary_key=True)
> >     text = models.TextField(blank=False)
> >     question = models.ForeignKey(Question)
> >     candidate = models.ForeignKey(Candidate)
>
> > class Question(models.Model):
> >     id = models.CharField(max_length=32, primary_key=True)
> >     text = models.TextField(blank=False)
>
> > class Candidate(models.Model):
> >     id = models.CharField(max_length=32, primary_key=True)
> >     name = models.CharField(max_length=32, blank=False)
>
> > class Race(models.Model):
> >     id = models.CharField(max_length=32, primary_key=True)
> >     name = models.CharField(max_length=128, blank=False)
> >     questions = models.ManyToManyField(Question)
> >     candidates = models.ManyToManyField(Candidate)
>
> > So, a Race has Candidates and Questions, and a Candidate has Answers.
> > Each answer is associated with a Question and a Candidate. Displaying
> > the question associated with an answer is easy:
>
> > # context variable in view
> >     answers = Answer.objects.filter(candidate=candidate)
>
> > # template code
> >     
> >     {% for answer in answers %}
> >     
> >         {{answer.question.text}}
> >         {{answer.text}}
> >     
> >     {% endfor %}
> >     
>
> > From the point of view of the Candidate, I need to display all the
> > questions, including the ones without Answers. I know how to to do
> > this using raw sql and an outer join. How to do it in the orm?
>
> > Thanks in advance for any ideas.
>
> > --Jeff
>
> Not quite enough information here to answer. What are you wanting to
> join? If you just want to display all the questions, why do you need a
> join at all?
> --
> DR.

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



outer join in orm

2010-06-21 Thread JeffH
I have some models that (simplified) look like the following.

class Answer(models.Model):
id = models.CharField(max_length=32, primary_key=True)
text = models.TextField(blank=False)
question = models.ForeignKey(Question)
candidate = models.ForeignKey(Candidate)

class Question(models.Model):
id = models.CharField(max_length=32, primary_key=True)
text = models.TextField(blank=False)

class Candidate(models.Model):
id = models.CharField(max_length=32, primary_key=True)
name = models.CharField(max_length=32, blank=False)

class Race(models.Model):
id = models.CharField(max_length=32, primary_key=True)
name = models.CharField(max_length=128, blank=False)
questions = models.ManyToManyField(Question)
candidates = models.ManyToManyField(Candidate)

So, a Race has Candidates and Questions, and a Candidate has Answers.
Each answer is associated with a Question and a Candidate. Displaying
the question associated with an answer is easy:

# context variable in view
answers = Answer.objects.filter(candidate=candidate)

# template code

{% for answer in answers %}

{{answer.question.text}}
{{answer.text}}

{% endfor %}


>From the point of view of the Candidate, I need to display all the
questions, including the ones without Answers. I know how to to do
this using raw sql and an outer join. How to do it in the orm?

Thanks in advance for any ideas.

--Jeff

-- 
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: Hosting for Django sites

2010-04-05 Thread JeffH
Valcato.com offers shared and dedicated hosting, including good Django
support. I've got two Django sites with them now. Home office is in
UK. --Jeff

On Apr 4, 8:33 pm, Nick Lacey  wrote:
> Matt wrote:
> >  plus im uk based so  phone wouldn't really help.
>
> Speaking of being UK based .. for the project all I'm working on,
> *all* the users will be in the UK, so I'm not sure about performance
> issues caused by servers in the US.
>
> Do I need to worry about the host not being based in Europe? If so,
> could anyone recommend a Europe based host?
>
> Many thanks,
>
> Nick

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



django admin instance needs to have a primary key value before a many-to-many relationship can be used

2010-03-11 Thread JeffH
Hello,

I'm a relative newcomer to Django and love it. I'm having a problem
with a m:m relationship in the admin. Stripped down, I have two
models, Fact and FactSet

class Fact(models.Model):
Name = models.CharField(max_length=64, unique=False, blank=False,
db_index=True)

class FactSet(models.Model):
Name = models.CharField(max_length=64, unique=False, blank=False,
db_index=True)
Factors = models.ManyToManyField(Fact, null=True, blank=True)

The models verify, syncdb runs without error. In the admin, I populate
in a bunch of Facts, all is well. Still in the admin, I try to create
a FactSet and get "FactSet instance needs to have a primary key value
before a many-to-many relationship can be used" As if it's trying to
save items in the join table before saving the FactSet item itself.
I'm running Django 1.1.1.

I'm probably overlooking something obvious. TIA for any clues.

--Jeff

-- 
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: Hosting for django?

2009-12-24 Thread JeffH
Tried DreamHost, which is OK for shared static sites; fuggetaboutit
vis a vis Django. I've been using http://www.valcatohosting.com/. They
have some good getting started docs and excellent support. Good for
low volume shared hosting. For a large upcoming project, I'm looking
at either Linode or SliceHost, unless a dark horse shows up.

On Dec 22, 1:59 pm, yummy_droid  wrote:
> Hi,
>
> Has anyone had good experiences with hosting companies that I can use
> for production django apps, with backups, etc.?
>
> I would also want to add some extensions etc. as well (e.g.
> matplotlib, reportlab, etc.).
>
> Anyone use godaddy?
>
> Thanks.

--

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




Re: newb URL mapping problem

2008-07-09 Thread JeffH

Thanks. I can live with it. The main thing is knowing I'm not
crazy. ;-)

On Jul 9, 8:00 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Wed, 2008-07-09 at 04:51 -0700, JeffH wrote:
> > I have a URL mapping problem, running 0.96.2 on Windows.
>
> > The problem: I have to specify the site name in the urls.py or else I
> > get 404s.
>
> > For example:
> > urlpatterns = patterns('',
> > (r'^/$', home),
> > (r'^/home/$', theview),
> > (r'^SouthHavenReservations/home1/$', theview1),
> > (r'^SouthHavenReservations/home2/$', theview2),
> > (r'^SouthHavenReservations/admin/',
> > include('django.contrib.admin.urls')),
> > )
>
> > The first two REs (without the site prefix) give 404s. The last three
> > work fine. I can 'fix' the first two by including the site prefix.
>
> That's right. It's a limitation in Django and something we're going to
> fix before 1.0. In fact, it's something we're going to fix before
> 1.0-alpha1, since it's going to be a bit backwards-incomaptible
> (once-off pain and very easy to fix, but still).
>
> Ticket #285 is probably the one to track if you care about exactly when
> this lands, but it will probably be fixed this weekend (or sooner, when
> I next get some time to sit down and cause major damage ... er... fix
> stuff in the tree). This one's my responsibility.
>
> For now, just live with it. Include the site prefix in the URLs (put it
> in a variable and include the variable in the front of each prefix if
> you think it might change).
>
> > In settings.py I have:
> >   ROOT_URLCONF = 'SouthHavenReservations.urls'
>
> This has nothing to do with it. It determines the Python import path and
> has nothing to do with the URL as seen by Python.
>
> Regards,
> Malcolm
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



newb URL mapping problem

2008-07-09 Thread JeffH

I have a URL mapping problem, running 0.96.2 on Windows.

The problem: I have to specify the site name in the urls.py or else I
get 404s.

For example:
urlpatterns = patterns('',
(r'^/$', home),
(r'^/home/$', theview),
(r'^SouthHavenReservations/home1/$', theview1),
(r'^SouthHavenReservations/home2/$', theview2),
(r'^SouthHavenReservations/admin/',
include('django.contrib.admin.urls')),
)

The first two REs (without the site prefix) give 404s. The last three
work fine. I can 'fix' the first two by including the site prefix.

In settings.py I have:
  ROOT_URLCONF = 'SouthHavenReservations.urls'

I'm sure it's something simple, but I'm stuck.

TIA--Jeff

--~--~-~--~~~---~--~~
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: Validating dynamically generated fields (guess i'll need a metaclass)

2007-09-14 Thread JeffH

I agree with Doug B's advice - I've used that "list of forms with
different prefixes" technique and it works very well and the code
should be easy for others to follow down the road. You actually don't
need a prefix hidden field for each fieldset - one hidden field
containing the number of fieldsets is plenty if the prefixes follow a
sequence like 'room0','room1','room2' then loop as in the following
"notional code" (no validation, initialization, etc):

for i in range(int(request.POST['numberOfFieldSets'])):
roomshared.append(RoomShared(request.POST,prefix='room%d' % i))

If you are interested in generating the forms dynamically, one way
I've done it is to define the RoomShared class by building a
dictionary of fields and then creating the class using the built-in
type() rather than using a Class declaration:

RoomShared = type('RoomShared',(django.newforms.Form,),
{ 'field_name1':field_declaration1,'field_name2':...})

It's important to add the field declarations to the dictionary in the
order they will be displayed in the form if you want to use shortcuts
like as_p(). newforms assigns a creation counter to each field when
it's declaration is processed and orders fields by their creation
counters when displaying the form.

Using type() to create a class is discussed in the context of dynamic
model creation at http://code.djangoproject.com/wiki/DynamicModels

Cheers,
Jeff

On Sep 14, 9:16 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> On Sep 13, 11:06 pm, Doug B <[EMAIL PROTECTED]> wrote:
>
> > Could you just use a collection of forms with different prefixes...
>
> Hi Doug,
>
> that's a good idea... but i'm still following the meta-programming
> route... i tried with a form factory function which is conceptually
> closer to what i thought but still doesn't work.
>
> This is what i tried:
>
> def room_form_factory(new_data):
> room_type = IntegerField(widget=Select(choices=BEDROOM_TYPES))
> room_price = IntegerField()
> is_shared = BooleanField(required=False)
>
> class RoomShared(Form):
> pass
>
> for k in new_data:
> postfix = k[-3:]
>
> if k.startswith('room_type'):
> setattr(RoomShared, 'room_type_%s' % postfix, room_type)
> elif k.startswith('room_price'):
> setattr(RoomShared, 'room_price_%s' % postfix, room_price)
> elif k.startswith('is_shared'):
> setattr(RoomShared, 'is_shared_%s' % postfix, is_shared)
>
> return RoomShared(new_data)
>
> And this is my view code:
>
> def add_share_room_details(request, object_id):
>
> if request.method == 'POST':
> new_data = request.POST.copy()
> form = room_form_factory(new_data)
>
> d = vars(form)
> for kw in d:
> print "%s = %s" % (kw, d[kw])
>
> if form.is_valid():
> return HttpResponse("Form is valid")
> else:
> return HttpResponse("Form NOT valid")
> else:
> pass
>
> return render_to_response("house_share_room.html")
>
> Any other idea?
>
> Thanks,
> Lorenzo


--~--~-~--~~~---~--~~
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: Best Practices to Make your Apps Portable

2007-07-27 Thread JeffH

I use the following:
my pythonpath includes /usr/local/lib/django/
within which I have:
apps/
app1/(models,views,urls)
app2/(models,views,urls), etc.
vhosts/
vhost1/(settings,urls)
vhost2/(settings,urls), etc.

within the config for each apache virtual host I have a different
DJANGO_SETTINGS_MODULE like vhosts.vhost1.settings

this way apps and vhosts are completely separate in the hierarchy, but
it is all within the same python path entry. It works well with
subversion because I have one code structure to capture all my apps
and vhosts and I can test out different vhost settings on different
servers by changing DJANGO_SETTINGS_MODULE in the apache config. I
have all my settings.py files import local_secrets.local_secrets, a
function that returns the proper database password and secret key
depending on whether a "DEVELOPMENT_MODE" parameter is set and on the
calling vhost. local_secrets.py is elsewhere on my pythonpath on each
physical server. That keeps that stuff out of my subversion tree.

templates and media are stored elsewhere where the designers have
access, using the same hierarchy as apps, but with an additional
vhosts directory containing overrides specific to particular vhosts.
In subversion I have code, templates and media directories below
trunk. Initially I had templates and media as subdirectories in each
app (to maximize app portability), but I found the access issues for
designers too cumbersome (chmod won't follow symlinks so granting
permissions to template and media subdirectories within each app is
unwieldy, and it was much easier to have media actually in the media
server docroot since we could use existing share permissions and have
user-restore capability (the docroots are mounted from a snapvaulted
SAN), and the designers don't play nice with subversion so I could
give them their own branch, 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: SQL VIEWs as Django Models for aggregation --- delete() issues with django.db.models.query: delete_objects

2007-07-17 Thread JeffH

> > 3. That said, my delete_objects() hack was an attempt to solve the
> > more general problem of using an overridden delete() without any
> > special flags while allowing for the possibility of model subclassing
> > in the future, because it seemed that respecting an overridden
> > delete() was an important end in itself from an object integrity
> > perspective.
>
> To my mind, the better approach here would be to have proper support
> for a 'read-only' query set that disables (or doesn't have) the delete
> operation, rather than significantly changing the behaviour of bulk
> deletes. Read-only objects/querysets would be an essential part of any
> view support in Django.

Hmmm. I seem to have overgeneralized my problem and its solution. My
real problem with using views right now is that Django implements (and
therefore enforces) cascading deletes internally. I could easily
override database-level delete cascade without having to hack on
Django itself. I'm not concerned about intentional Manager-level bulk
deletes. My specific error occurred when I blanked out all the core
fields for an inline object in the Admin and saved the primary object.
The inline object also has a one-to-one related view object that is
caught up in the cascading delete code. I don't think the Manager-
level delete() for related objects is invoked in situations like this
--- though I'm speaking well beyond my knowledge level here.

Regardless of how it is implemented, offering the user the ability to
prevent cascading deletes of an object class either at the class
definition or the field definition level  would allow lots of powerful
stuff without having to hack the Django core.

In terms of the bigger picture, I think aggregation support should be
handled at the queryset level, but view support would be much more
powerful and easy to use if views are treated as model-like objects
themselves because of their flexibility (for instance an updatable
view onto a table in another database). Views are an advanced feature
that not everybody needs - why not keep the changes minimal and put
the onus on the user (let the DBA code the create view SQL file, and
the application developer code the python)? In the short term, I would
suggest the actual view creation be handled as raw user SQL in place
of the usual model table creation (and that view creation be optional
in case the view already exists on the database), and the user can
specify that the view object is updatable, otherwise it defaults to
[no saves/no deletes/no cascading deletes].

> Well, it is correct if you consider bulk-delete to be different to
> delete. There is no bulk-save analog. Bulk delete (delete on a
> queryset) is quite a different operation, that doesn't integrate with
> the individual object delete.
>
> However, the distinction obviously isn't obvious to newcomers.
> Suggestions on documentation improvements are always welcome. My
> initial reaction is that if there is a need for improvement, its here:
>
> http://www.djangoproject.com/documentation/db-api/#deleting-objects
>
Good point. I'd say it should be explained there, and specifically
mentioned in the model-api section on overriding. I'll put in a
ticket.

Cheers,
Jeff


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



Re: SQL VIEWs as Django Models for aggregation --- delete() issues with django.db.models.query: delete_objects

2007-07-16 Thread JeffH

Russ: Thanks for your reply!

1. I don't consider my views-as-models approach elegant at the
implementation level, but:
  * it is dead simple to use once set up (it's just the Django model
and database API)
  * it allows for limited aggregation support (views are created at
install time, so real ad hoc reporting would have to be done with
custom model methods)
  * it works with querysets since the aggregated columns are defined
as Django model fields, so presenting a table of aggregated data with
an arbitrary selection of rows only requires one actual database query
(versus many queries when iterating over instances invoking a model
method)
  * SQL code stays in SQL script files that are part of Django's
design (sqlinitialdata) and stays out of my python code
Ideally Django classes for the table and view functionality would
share a common ancestor so they share an API, and table-specific
behavior like delete_objects would be defined above the common (i.e.
SELECT) functionality. Realistically, such a refactoring is unlikely
before my next few projects are due (no sarcasm intended).

2. With hindsight, delete_objects() behavior of Django appears to be
specifically desired by the developers so I'll just change my working
copy to just check for a class attribute like "not_updatable", and
abort batch deletes for related object classes with that attribute.
Given the specific nature of my need (prevent cascading deletes of
views) it will be much more efficient than calling an empty delete()
method for each object.

3. That said, my delete_objects() hack was an attempt to solve the
more general problem of using an overridden delete() without any
special flags while allowing for the possibility of model subclassing
in the future, because it seemed that respecting an overridden
delete() was an important end in itself from an object integrity
perspective. I had hoped that the developers might be intrigued by the
concept behind the hack (checking once per related class whether a
user has overridden delete() and defaulting to the usual batch delete)
because of the inherent object-functionality-versus-database-
efficiency tension in an ORM. My hack offers options - the user can
choose to give up database speed for object-level functionality - and
options are always good as long as they are documented: "WARNING: Your
database may slow to a crawl if you override delete()!" Checking if
delete() was overridden is not a performance hit, so you don't lose
anything by offering the option. For my application, aggregate
reporting is far more common than deletion, so it needs to be
efficient and convenient to code.

4. Regarding documentation, I will put in a ticket for the
documentation on the relevant section
http://www.djangoproject.com/documentation/model-api/#overriding-default-model-methods
of the model-api page. That section invites people to override save()
and delete() but only discusses save() and the implication (by
omission) that overriding delete() is analogous is incorrect.

5. A big ongoing thanks to all of Django's contributors. You rock!

Thanks for reading this.

Cheers,
Jeff


On Jul 15, 1:24 am, "Russell Keith-Magee" <[EMAIL PROTECTED]>
wrote:
> On 7/13/07, JeffH <[EMAIL PROTECTED]> wrote:
>
>
>
> > This post relates to two separate Django issues that intertwined for
> > me:
> > 1. Lack of aggregation support in Django's ORM
> > (I am delighted to 
> > seehttp://groups.google.com/group/django-developers/browse_thread/thread...
> > )
>
> For the record, I'm still keen to get aggregates supported in Django.
> After a few distractions along the way (the unicode and oracle branch
> merges), I believe Malcolm is currently working on the Query rewrite
> that is the prerequisite for aggregates. Hopefully I will get a chance
> to get some aggregates happening in the near future (but I've said
> that before... :-)
>
> > I would like to hear from others how they are dealing with #1 and what
> > their thoughts are about #2.
>
> When I need aggregates at the moment, I'm generally falling back into
> raw SQL, or occasionally using the extra() clause on a queryset. Using
> the 'extra' clause can get you where you want (annotated rows in a
> database) by adding items to the select clause, which will appear as
> extra attributes on objects from the query set.
>
> The difficulty comes in getting GROUP BY and HAVING clauses into your
> query. This is because Django doesn't currently have support for these
> clauses inside Q objects. You can cheat a little by exploiting the
> fact that WHERE clauses are the last in the chain, but it's not
> particularly robust approach to the problem.
>
> > Here goes:
> > Experimenting with ways to add aggregated database information into my
> >

Re: little problem

2007-07-13 Thread JeffH

Jacob: Great! I have played it safe with the getattr construct,
figuring that the new object instance _might_ be constructed with an
id attribute set to None prior to save().

On Jul 13, 2:46 pm, "Lic. José M. Rodriguez Bacallao"
<[EMAIL PROTECTED]> wrote:
> thanks, that work more efficient that my way of do it, I was getting the
> user from the database to see if the user exist. I like your solution, is
> pretty clean and simple. Thanks a lot.
>
> On 7/13/07, Jacob Kaplan-Moss <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 7/13/07, JeffH <[EMAIL PROTECTED]> wrote:
>
> > > if getattr(model_instance, 'id', None) is None:
> > >   model_instance.created_by = whatever
>
> > Also take a look at ``hasattr()``:
> >http://docs.python.org/lib/built-in-funcs.html#l2h-35
>
> > Jacob
>
> --
> Lic. José M. Rodriguez Bacallao
> Cupet
> -
> Todos somos muy ignorantes, lo que ocurre es que no todos ignoramos lo
> mismo.
>
> Recuerda: El arca de Noe fue construida por aficionados, el titanic por
> profesionales
> -


--~--~-~--~~~---~--~~
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: little problem

2007-07-13 Thread JeffH

this works for me:

if getattr(model_instance, 'id', None) is None:
  model_instance.created_by = whatever

On Jul 13, 1:28 pm, "Lic. José M. Rodriguez Bacallao"
<[EMAIL PROTECTED]> wrote:
> Hi, I got a little problem. I need to store in a model the first user who
> created it (created_by) and the user who last modified it
> (last_modified_by). So, with the second one, there is no problem, every time
> a user save the object, the pre_save signal is dispatched and I catch it so
> I can set the "last_modified_by" field to current user but, right there, I
> need to set the "created_by" field and I don't know how to do it, my
> algorithm is pretty simple:
>
> if model_instance.created_by is not set:
> set model_instance.created_by to current user
> .
> .
> .
> continues with save
>
> the problem here is how to know if model_instance.created_by field is set or
> not, I think that it can be known if a can figure out if save method  is
> going to insert or update, but, how  I know it?
>
> --
> Lic. José M. Rodriguez Bacallao
> Cupet
> -
> Todos somos muy ignorantes, lo que ocurre es que no todos ignoramos lo
> mismo.
>
> Recuerda: El arca de Noe fue construida por aficionados, el titanic por
> profesionales
> -


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



SQL VIEWs as Django Models for aggregation --- delete() issues with django.db.models.query: delete_objects

2007-07-13 Thread JeffH

This post relates to two separate Django issues that intertwined for
me:
1. Lack of aggregation support in Django's ORM
(I am delighted to see 
http://groups.google.com/group/django-developers/browse_thread/thread/f433edf7b0ebdbcb/
)
2. Django does not use delete() methods for related objects
(as noted previously in:
http://groups.google.com/group/django-users/browse_thread/thread/3e37575e42de86c9/
and
http://groups.google.com/group/django-users/browse_thread/thread/2d1dc42cea162c4b/
)

I would like to hear from others how they are dealing with #1 and what
their thoughts are about #2.

Here goes:
Experimenting with ways to add aggregated database information into my
Django models, I came across a blog entry several weeks ago where the
author (my apologies for not having the reference to cite) said they
used VIEWs as Django Models, simply putting in the SQL code to drop
the table and create a like-named VIEW in sql/model_name as discussed
at 
http://www.djangoproject.com/documentation/0.96/model-api/#providing-initial-sql-data
for providing initial data. I chose to make my VIEW models one-to-one
with the actual Django model that uses the aggregation data, so I can
say event.event_view.capacity_remaining for instance and the
calculation for the number of seats remaining at an event (taking into
account reserved tables, etc) is quietly done by the SQL VIEW, the
Django query just looks up the result. I added empty delete() and
save() methods to the view models to prevent such activities (or so I
thought!) on a non-updatable view.

This approach, as opposed to coding an aggregation query as a method
of a Model, has the advantage of allowing the use of Django's ORM
elegance to do things like EventView.objects.filter(whatever__lookup)
using one database query rather than doing list comprehensions of
method calls and having separate queries for each instance.

Here the fun begins:
When I tried to delete an inline object in the Django Admin by
clearing all the core=True fields, I got an OperationError 1228, VIEW
not UPDATEable.  Argh! I had just discovered that Django does not use
the delete() methods of Models to delete related objects.

My fix for this specific problem was to patch
django.db.models.query.delete_objects() to see if the related model
overrides the delete() method, and if so, use it instead of the
existing batch SQL DELETE approach:

Starting at line 1059:
# Now delete the actual data
for cls in ordered_classes:
seen_objs[cls].reverse()
pk_list = [pk for pk,instance in seen_objs[cls]]
# if a related object's class overrides the
django.db.models.Model delete method - use it
if filter(lambda o: o.__dict__.has_key('delete'),cls.__mro__)
[0].__module__ != 'django.db.models.base':
map(lambda o: o.delete(),
cls._default_manager.filter(pk__in=pk_list))
else:
for offset in range(0, len(pk_list),
GET_ITERATOR_CHUNK_SIZE):
cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \
(qn(cls._meta.db_table), qn(cls._meta.pk.column),
','.join(['%s' for pk in pk_list[offset:offset
+GET_ITERATOR_CHUNK_SIZE]])),
pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE])

It's 4 lines of code - the patch starts with the second comment - plus
indenting within my else clause the original code used for the delete.

Most likely this patch does not cover cases like ManyToManyFields,
etc, I only had time to make the original error go away.

Thoughts? Comments?


--~--~-~--~~~---~--~~
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 render newforms dynamically created fields?

2007-04-30 Thread JeffH

Two thoughts on this:
First: you could define an appropriate label for the dynamic
formfields as you create them in your FormList class (not shown here)
such as the name of the thing that would be deleted, and then use the
as_p shortcut to render the whole form rather than trying to loop:

with a view like:

def form_list_view(request):
my_form = FormList(queues=[])
return render_to_response('formlist.html',{'form':my_form})

then within the  tags of template formlist.html:

{{ form.as_p }}

If you aren't happy with that approach, then you are in for an ugly
hack, such as a view like:

def form_list_view(request):
my_form = FormList(queues=[])
my_fields = ['%s: %s' % (field.label or
name,field.widget.render(name,'')) for name,field in
my_form.fields.items()]
return render_to_response('formlist.html',{'my_fields':my_fields})

and template code like:

{% for field in my_fields %}
{{ field }}
{% endfor %}

basically hacking out code like in
django.newforms.forms.BaseForm._html_output

On Apr 30, 2:47 am, Mario Graziosi <[EMAIL PROTECTED]> wrote:
> I have a form with several checkboxes created dynamically, where each
> field has a name similar to "mycheck_xxx". From within the template I
> don't know how many checks the form holds, since these are built
> dynamically. How can I render them using the Django template system?
>
> For example, this is my Form (using newforms):
>
> class FormList(forms.Form):
> def __init__(self, queues, *args, **kwargs):
> super(FormList, self).__init__(*args, **kwargs)
> # Create several check boxes
> for n in range(5):
> fieldname = 'mycheck_%d' % n
> self.fields[fieldname] = forms.BooleanField(required=False)
>
> This is the template (one of several tries). Obviously, it doesn't work,
> but it reflects what I'd like to get on my form:
>
> {% for fieldname in form.fields.keys %}
> {{ form.fieldname }}
> {% endfor %}
>
> Does any one know how I might accomplish this?
>
> Thanks in advance for any help.
>
> --
> Mario Graziosi, mailto:[EMAIL PROTECTED]
> FG&A srl (http://www.fgasoftware.com/)
> [EMAIL PROTECTED]: The agile PBX (http://www.voiceatwork.eu/)
> Tel: 02 9350-4780 interno 101, Fax: 02 9139-0172


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



Ticket-worthy? 0.96 newforms custom widget TypeError exception suppressed by render_to_response

2007-04-09 Thread JeffH

Is this worthy of a ticket?

Observed behavior: Django (v0.96) render_to_response renders a
template but renders nothing for {{ form.as_table }} tag when
(unbeknownst to the poor programmer) a TypeError exception is raised
during the rendering of a custom newforms widget.

My preferred behavior: generate a traceback message in the browser

There may be other kinds of exceptions that result in this behavior as
well, I am only sure of this one. I spent many frustrating hours
(granted the frustrating hours were my own fault; I am unfamiliar with
Django & python debugging) trying to debug my custom fields and
widgets when render_to_response would simply not output any HTML for
the form, and encountered several different bugs along the way through
brute force trial and error.

My breakthrough came when I stopped hoping for a traceback in the
browser and set a breakpoint in Wing and then used the debug probe to
print the form. I had a bug in one of my custom widgets for newforms
that resulted in a "TypeError: unsubscriptable object". I could have
discovered it through python manage.py shell also. I readily admit my
frustration was of my own making, and the form being absent in the
browser was certainly a big tip-off that something was wrong.

But isn't the suppression of exceptions like this (particularly in
debug mode) non-desired behavior?

>>> print myform
Traceback (most recent call last):
  File "/usr/local/django/terry/ean/views/news.py", line 1, in ?
# views for news items
  File "/usr/lib/python2.4/site-packages/django/newforms/util.py",
line 26, in __str__
return self.__unicode__().encode(settings.DEFAULT_CHARSET)
  File "/usr/lib/python2.4/site-packages/django/newforms/forms.py",
line 73, in __unicode__
return self.as_table()
  File "/usr/lib/python2.4/site-packages/django/newforms/forms.py",
line 144, in as_table
return self._html_output(u'%(label)s%(errors)s%
(field)s%(help_text)s', u'%s',
'', u'%s', False)
  File "/usr/lib/python2.4/site-packages/django/newforms/forms.py",
line 129, in _html_output
output.append(normal_row % {'errors': bf_errors, 'label': label,
'field': unicode(bf), 'help_text': help_text})
  File "/usr/lib/python2.4/site-packages/django/newforms/forms.py",
line 227, in __unicode__
value = self.as_widget(self.field.widget)
  File "/usr/lib/python2.4/site-packages/django/newforms/forms.py",
line 252, in as_widget
return widget.render(self.html_name, data, attrs=attrs)
  File "/usr/local/django/terry/custom_widgets.py", line 75, in render
if not new_attrs.has_key['id']:
TypeError: unsubscriptable object


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