Re: Why does admin fail on one project and not another?

2010-01-27 Thread grahamu
Two additional notes for this issue:
1. Clicking on _any_ model in the admin causes the same TypeError.
2. Clicking on "+Add" in admin for the User model yields a blank form!
Clicking on "+Add" for any other model shows a valid form.

On Jan 27, 3:08 pm, grahamu <gra...@flyingcracker.com> wrote:
> I'm having a problem with django admin working for one local project
> and not another. Both use the same version of Django (SVN-12311). Both
> have very similar settings.py files.
>
> The issue appears when I click on an app model class name in the root
> admin list (at "/admin/"). In this case I was trying to view "Cam"
> instances from the "cam" application. I believe admin is trying to
> show a list of "Cam" instances, but instead I get an error:
>
>   "Exception Value: changelist_view() takes at least 2 arguments (1
> given)"
>
> Now I'm pretty sure there isn't a problem with Django here, but there
> is also precious little to guide me in my search for where my code
> goes wrong. Can anyone with similar experience provide some advice?
> Thanks!
>
> Graham
>
> From the traceback:
>
> Environment:
>
> Request Method: GET
> Request URL:http://localhost:8000/admin/cam/cam/
> Django Version: 1.2 alpha 1 SVN-12311
> Python Version: 2.5.2
> Installed Applications:
> ['django.contrib.auth',
>  'django.contrib.contenttypes',
>  'django.contrib.sessions',
>  'django.contrib.sites',
>  'django.contrib.admin',
>  'django.contrib.admindocs',
>  'django.contrib.markup',
>  'django.contrib.humanize',
>  'django.contrib.comments',
>  'django_extensions',
>  'django.contrib.flatpages',
>  'mobileadmin',
>  'registration',
>  'serviceclient',
>  'scoresys',
>  'south',
>  'home',
>  'weatherstation',
>  'weather',
>  'food',
>  'blog',
>  'cam',
>  'miniblog',
>  'grill',
>  'fantasy']
> Installed Middleware:
> ('django.middleware.common.CommonMiddleware',
>  'django.contrib.sessions.middleware.SessionMiddleware',
>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>  'django.middleware.csrf.CsrfViewMiddleware',
>  'django.middleware.doc.XViewMiddleware',
>  'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')
>
> Traceback:
> File "c:\django\trunk\django\core\handlers\base.py" in get_response
>   101.                     response = callback(request,
> *callback_args, **callback_kwargs)
> File "c:\django\trunk\django\contrib\admin\options.py" in wrapper
>   238.                 return self.admin_site.admin_view(view)(*args,
> **kwargs)
> File "c:\django\trunk\django\utils\decorators.py" in __call__
>   36.         return self.decorator(self.func)(*args, **kwargs)
> File "c:\django\trunk\django\utils\decorators.py" in _wrapped_view
>   86.                     response = view_func(request, *args,
> **kwargs)
>
> Exception Type: TypeError at /admin/cam/cam/
> Exception Value: changelist_view() takes at least 2 arguments (1
> given)

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



Why does admin fail on one project and not another?

2010-01-27 Thread grahamu
I'm having a problem with django admin working for one local project
and not another. Both use the same version of Django (SVN-12311). Both
have very similar settings.py files.

The issue appears when I click on an app model class name in the root
admin list (at "/admin/"). In this case I was trying to view "Cam"
instances from the "cam" application. I believe admin is trying to
show a list of "Cam" instances, but instead I get an error:

  "Exception Value: changelist_view() takes at least 2 arguments (1
given)"

Now I'm pretty sure there isn't a problem with Django here, but there
is also precious little to guide me in my search for where my code
goes wrong. Can anyone with similar experience provide some advice?
Thanks!

Graham


>From the traceback:

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/cam/cam/
Django Version: 1.2 alpha 1 SVN-12311
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.markup',
 'django.contrib.humanize',
 'django.contrib.comments',
 'django_extensions',
 'django.contrib.flatpages',
 'mobileadmin',
 'registration',
 'serviceclient',
 'scoresys',
 'south',
 'home',
 'weatherstation',
 'weather',
 'food',
 'blog',
 'cam',
 'miniblog',
 'grill',
 'fantasy']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.doc.XViewMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')


Traceback:
File "c:\django\trunk\django\core\handlers\base.py" in get_response
  101. response = callback(request,
*callback_args, **callback_kwargs)
File "c:\django\trunk\django\contrib\admin\options.py" in wrapper
  238. return self.admin_site.admin_view(view)(*args,
**kwargs)
File "c:\django\trunk\django\utils\decorators.py" in __call__
  36. return self.decorator(self.func)(*args, **kwargs)
File "c:\django\trunk\django\utils\decorators.py" in _wrapped_view
  86. response = view_func(request, *args,
**kwargs)

Exception Type: TypeError at /admin/cam/cam/
Exception Value: changelist_view() takes at least 2 arguments (1
given)

-- 
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: Adding ManyToMany field to django comments

2009-08-25 Thread grahamu

The solution I eventually used is to require that the reviewer
queryset be stored in a session variable. Since this queryset is
required in the template context in order for the templatetags to
work, saving the value in a session variable isn't much to ask.

Please let me know if you think this solution is problematic in
nature. Thanks!

Graham

On Aug 19, 5:56 pm, grahamu <gra...@flyingcracker.com> wrote:
> In general, I'm wondering how to retrieve a Queryset provided to a
> Form (choices for a ManyToMany field) from within a view that only
> accepts POST data from that form. This isn't really a question about
> extending django.contrib.comments, but that framework provides a good
> point of reference for the issue.
>
> For example, suppose I wanted to add: "reviewers = models.ManyToMany
> (User)" to the django.contrib.comment Comment model. This would be a
> list of Users who are allowed to review the comment, specified by the
> comment creator.
>
> In order for this to work we need to provide a Queryset of Users when
> creating the form. This can be accomplished with a template tag of the
> form "{% get_comment_form for [object] with [reviewers] as [varname]
> %}", where 'reviewers' is a Queryset passed in the template context.
> This works fine.
>
> However, when the form is posted, we don't have visibility (in the
> post view) to the Queryset of possible reviewers. The post view, after
> checking the validity of several other pieces of data, creates a new
> comment form to check the validity of the received data. Of course the
> form must have a Queryset for the 'reviewers' field, and this isn't
> part of the request POST data.
>
> Any ideas how one might either pass the queryset data to the view in
> the form, or some other way to manage the form validation in this
> situation?
>
> Graham
--~--~-~--~~~---~--~~
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: Displaying username on every page

2009-08-19 Thread grahamu

If you use RequestContext(), you automatically get visibility to the
current user and their permissions. See
http://docs.djangoproject.com/en/dev/topics/auth/#authentication-data-in-templates.
My base templates use a block like this:

{% block user %}
{% if user.is_authenticated %}
User: {{ user.get_full_name }}{% if user.is_staff %}
[staff]{% endif %}
Log out
{% else %}
Log in or Sign up
{% endif %}
{% endblock user %}

Graham

On Aug 19, 4:27 pm, John Barham  wrote:
> Apologies in advance if this is a FAQ but I've searched the list and
> can't find a precise answer.
>
> I want to display the login status of the user at the top of every
> page.  If they were logged in, it should say something like "Logged is
> as  (Log Out)" and if they're not logged in it should show a
> link to the login page.
>
> I could of course pass in the username as a dictionary value for each
> page, but this quickly becomes tedious.  I also use render_to_response
> a lot and if I understand correctly it doesn't pass through the user
> info automatically, but will if you set the context_instance parameter
> to a RequestInstance.  Is there a way I can access the user info from
> any page without having to do the above?
>
>   John
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Adding ManyToMany field to django comments

2009-08-19 Thread grahamu

In general, I'm wondering how to retrieve a Queryset provided to a
Form (choices for a ManyToMany field) from within a view that only
accepts POST data from that form. This isn't really a question about
extending django.contrib.comments, but that framework provides a good
point of reference for the issue.

For example, suppose I wanted to add: "reviewers = models.ManyToMany
(User)" to the django.contrib.comment Comment model. This would be a
list of Users who are allowed to review the comment, specified by the
comment creator.

In order for this to work we need to provide a Queryset of Users when
creating the form. This can be accomplished with a template tag of the
form "{% get_comment_form for [object] with [reviewers] as [varname]
%}", where 'reviewers' is a Queryset passed in the template context.
This works fine.

However, when the form is posted, we don't have visibility (in the
post view) to the Queryset of possible reviewers. The post view, after
checking the validity of several other pieces of data, creates a new
comment form to check the validity of the received data. Of course the
form must have a Queryset for the 'reviewers' field, and this isn't
part of the request POST data.

Any ideas how one might either pass the queryset data to the view in
the form, or some other way to manage the form validation in this
situation?

Graham
--~--~-~--~~~---~--~~
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: forms and modelform

2008-12-03 Thread grahamu

Buddy,

I found this, you might give it a try.

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

Graham

On Nov 28, 9:59 am, Buddy <[EMAIL PROTECTED]> wrote:
> Yes, I try it before to my ask here. I get error if use likethis
> (class B(forms.ModelForm, A):
>
> ###
> TypeError at /A/
>
> Error when calling the metaclass bases
>     metaclass conflict: the metaclass of a derived class must be a
> (non-strict) subclass of the metaclasses of all its bases
>
> Request Method:         GET
> Request URL:    http://127.0.0.1:8000/A/
> Exception Type:         TypeError
> Exception Value:
>
> Error when calling the metaclass bases
>     metaclass conflict: the metaclass of a derived class must be a
> (non-strict) subclass of the metaclasses of all its bases
> #
>
> On 28 нояб, 18:39, Daniel Roseman <[EMAIL PROTECTED]>
> wrote:
>
> > On Nov 28, 3:47 pm, Buddy <[EMAIL PROTECTED]> wrote:
>
> > > I have model:
>
> > > class A(forms.Form):
> > >     p1 = forms.CharField()
> > >     p2 = forms.CharField()
>
> > > class B(A):
> > >     class Meta:
> > >         model = User
> > >         fields = ('username', 'email', 'first_name', 'last_name',)
>
> > >http://dpaste.com/94378/
>
> > > but fields that define in class B not apears when I render it in html.
> > > Why is it not apears?
>
> > Because neither A nor B are ModelForms. You could make B inherit from
> > both ModelForm and A - untested, but should work:
>
> > class B(forms.ModelForm, A):
> >    ... etc
>
> > > PS
> > > Whether exist class'' tree in any a form for common observe?
>
> > Sorry, no idea what you're asking here.
>
> > --
> > 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-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: DB record retrieval from every N minutes

2008-10-16 Thread grahamu

Good idea Thomas. I'll experiment with using __range to get 24
individual records instead of retrieving all records and then looping
over the queryset. Thanks.
Graham

On Oct 15, 1:15 am, Thomas Guettler <[EMAIL PROTECTED]> wrote:
> grahamu schrieb:> I'd like to find an efficient method to retrieve a list of 
> Django DB
> > records (model has a DateTimeField `timestamp`) between datetime
> > 'start' and datetime 'end' with a few conditions. First, we're looking
> > for a record once every 'interval' minutes. Second, I only want a
> > record if it's timestamp within 'fudge' minutes of the target time.
> > Last, if such a record doesn't exist for an interval, put None in the
> > list instead.
>
> The query api supports range searches, which result into SQL's BETWEEN:
>
> You can use datetime.timedelta(minutes=fudge_minutes) to compute the
> start and end times of your target time.
>
> http://docs.djangoproject.com/en/dev/ref/models/querysets/#range
>
> On unix you would set up a cron-job which gets called very N minutes.
>
>  Does this help you?
>
>   Thomas
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



DB record retrieval from every N minutes

2008-10-14 Thread grahamu

I'd like to find an efficient method to retrieve a list of Django DB
records (model has a DateTimeField `timestamp`) between datetime
'start' and datetime 'end' with a few conditions. First, we're looking
for a record once every 'interval' minutes. Second, I only want a
record if it's timestamp within 'fudge' minutes of the target time.
Last, if such a record doesn't exist for an interval, put None in the
list instead.

For example:
'start' = 2008-10-01 00:00:00
'end' = 2008-10-01 12:00:00
'interval' = 60 minutes
'fudge' = 5 minutes

I would expect to get thirteen items in a list (each either a record
or None).
The first record to save is the first record between 23:55:00 and
00:05:00. The second record to be saved would be the first record
betwen 00:55:00 and 01:05:00. And so on.

At the moment I have attacked this with a brute force approach by
processing a QuerySet of all records between 'start' and 'end'. Here
is the QuerySet:

qs = Weather.objects.filter(timestamp__year=date.year,
  timestamp__month=date.month,
 
timestamp__day=date.day).order_by('timestamp')

Here is the processing code:

def periodic_samples(qs, start, fudge, interval, periods):
'''
Returns a list of arbitrary type records (containing attribute
'timestamp')
from `qs`, one record for each target window during a total of
'periods'
windows beginning at 'start'.

`target` = `start` plus a (0 to `periods`) multiple of `interval`.
A target window is defined as: `target`-`fudge` to `target`
+`fudge`.
The first record found in a target window is saved in the list and
all other
records in that window are ignored. If no record is found in the
target
window then None is placed in the list instead of a record.

For instance if `start`=12:00, `fudge`=5 minutes, `interval`=30
minutes,
and `periods`=2, record timestamps must fall in the ranges 11:55 -
12:05
and 12:25 - 12:35.

Parameter types:
`qs` = Queryset of records which have a "timestamp" field
`start` = datetime.datetime
`fudge` = datetime.timedelta
`interval` = datetime.timedelta
`periods` = integer

'''
dataset = []
if len(qs):
target = start
end = start + (periods * interval)
for rec in qs:
if target >= end:
break
ts = rec.timestamp
while ts > (target + fudge):
dataset.append(None)
target += interval
if ts < (target - fudge):
pass
else:
dataset.append(rec)
target += interval
# no more records, fill out the dataset with None values
while target < end:
dataset.append(None)
target += interval
return dataset

Regardless of my finicky needs as outlined above, does anyone know of
a method for efficiently extracting a bunch of records, say one record
an hour, over some range of time? It seems awfully inefficient to look
at each record in the queryset to find what I want.
---
Graham Ullrich
--~--~-~--~~~---~--~~
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: reverse( ) and template tag 'url' fail when pattern has include

2008-02-13 Thread grahamu



On Feb 14, 12:04 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> That's because you are expecting things from reverse() that it
> explicitly doesn't do. In particular, the "args" and "kwargs" parameters
> to reverse are only checked against capturing groups in the URL's
> regular expression.
>
> The reason for this is that to also permit people to specify things in
> extra_dict will rapidly (in fact, already has when people suggested
> this) lead to confusion about what is and isn't possible and how Python
> actually works. String matching is easy: all strings with the same value
> compare as equal. But then people start wanting to put QuerySets in
> there or other class instances or complex objects that have interesting
> equality comparison behaviour and the slippery slope leads straight to
> hell. So, to maintain sanity all around, you can't do that, as you've
> discovered. That's intentional.

LOL, my sanity has been questionable for years.

> Fortunately, there's a solution, I'm pretty sure:
>
> (r'^(?Pdrink)/', include(app.urls))
> (r'^(?Peat)/', include(app.urls))
>
> or, even more succintly:
>
> r'^(?Peat|drink)/', include(app.urls))
>
> These might trip across other urlresolver bugs, from memory (I have a
> feeling the bug still exists where if we don't match the first item
> that's a potential candidate, we fail unconditionally, rather than
> testing everything). In any case, I'll check out those side cases in the
> next few hours, since I'm doing some trunk work at the moment and this
> has come up.
>
> So either the alternatives work right now or will work within a day or
> two. That's certainly the way to approach this, though, because the
> other way just opens up the door to far too many user problems.

Your memory is quite good. I did try exactly what you suggested many
hours ago today and saw the result you describe (see below). If the
first item does not match it fails. So I figured I still didn't have
the syntax correct or something.

Presumably the url template tag will perform similarly to reverse when
the fix is made? So this would be equivalent:

{% url 'food-view' myname='drink' %}

Thanks so much for your help Malcolm.

urlpatterns = patterns('',
(r'^(?Pdrink)/', include('app.urls')),
(r'^(?Peat)/', include('app.urls')),
)

>>> reverse('food-view', kwargs={'myname':'drink'})
'/drink/'

>>> reverse('food-view', kwargs={'myname':'eat'})
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\django\trunk\django\core\urlresolvers.py", line 297, in
reverse
return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname,
*args, **kw
args))
  File "c:\django\trunk\django\core\urlresolvers.py", line 283, in
reverse
return u''.join([reverse_helper(part.regex, *args, **kwargs) for
part in sel
f.reverse_dict[lookup_view]])
  File "c:\django\trunk\django\core\urlresolvers.py", line 88, in
reverse_helper

result = re.sub(r'\(([^)]+)\)', MatchChecker(args, kwargs),
regex.pattern)
  File "C:\Python24\lib\sre.py", line 142, in sub
return _compile(pattern, 0).sub(repl, string, count)
  File "c:\django\trunk\django\core\urlresolvers.py", line 129, in
__call__
raise NoReverseMatch("Value %r didn't match regular expression %r"
% (value,
 test_regex))
NoReverseMatch: Value 'eat' didn't match regular expression 'drink'
--~--~-~--~~~---~--~~
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: reverse( ) and template tag 'url' fail when pattern has include

2008-02-13 Thread grahamu


On Feb 13, 7:15 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
[...]
> As Alex pointed out, you're calling reverse() on something that isn't a
> direct URL pattern. Don't do that. It makes no sense to call reverse()
> on something that is actually a collection of URL patterns. Instead,
> pick one of the URL patterns inside urls2 and call reverse on that.

Good point, one which I now understand from Alex' and your comments.

What I am trying to accomplish is two different project URLs which
both resolve to the same application urlconf, yet can be
differentiated by a view in the application. In other words, the app
view needs to determine the root URL used to reach the view.

A slightly different example is in order. In this example we have a
'mysite' project url config, and an application url config.

mysite.urls contains
[...]
(r'^drink/', include('app.urls'), {'myname':'drink'}),
(r'^eat/', include('app.urls'), {'myname':'eat'}),
[...]

URLs /mysite/drink/ and /mysite/eat/ are next resolved at the
application urlconf:

mysite.app.urls contains
[...]
url(r'^$', 'views.func', name='food-view'),
[...]

At this point /mysite/drink/ and /mysite/eat/ resolve to the same app
view function, "func".

mysite.app.views contains
def func(request, myname):
[...]
originating_url = reverse('food-view',
kwargs={'myname':myname})

This does not give me the results I expect, although it seems that it
should. I expected kwargs 'myname' to help reverse() differentiate
between the two URLs. Instead, both originating URLs (/mysite/drink/
and /mysite/eat/) reverse() resolve to /mysite/drink/ (the first URL
in the project urlconf).

Since this concept is proving difficult to implement while most other
tasks in Django are easy, I began wondering if my design needs
refactoring. For instance, I could have mysite.urls resolve /drink/
and /eat/ to separate app urlconfs:

(r'^drink/', include('app.urls.drink'), {'myname':'drink'}),
(r'^eat/', include('app.urls.eat'), {'myname':'eat'}),

That idea violates DRY, because both app urlconfs will contain exactly
the same subsequent patterns and function calls but with different
pattern names. Most of my refactoring ideas end with the same result,
duplication of code. Perhaps that is inevitable in this case.
Regardless thanks very much for clearing up my initial confusion about
where to name a pattern.
--~--~-~--~~~---~--~~
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: reverse( ) and template tag 'url' fail when pattern has include

2008-02-13 Thread grahamu

Thanks for your explanation, Alex.
Unfortunately, "reverse('views.func')" always returns the first match
for that function in urlpatterns.

My objective is to distinguish between two different URL patterns
which both resolve to the same view function.
Given your suggestion, I tried the following:

   >>> reverse('views.func', kwargs={'myname':'drink'})
   >>> '/drink/'
   >>> reverse('views.func', kwargs={'myname':'exercise'})
   >>> '/drink/'
   >>> reverse('views.func', kwargs={'myname':'eat'})
   >>> '/drink/'
   >>> reverse('views.func', kwargs={'myname':'sleep'})
   >>> '/drink/'

So that solution does not work because the resolver apparently ignores
the kwargs when presented with a function instead of a named URL.


On Feb 13, 4:34 pm, Alex Koshelev <[EMAIL PROTECTED]> wrote:
> Hi, graham
>
> Imagine that your urls2.py has some number of patterns. And then you
> call `reverse('eat')` what of them have to be returned? So to get
> proper result you have to write something like this
> `reverse('views.func')`
>
> On 14 фев, 02:22, grahamu <[EMAIL PROTECTED]> wrote:
>
> > Lots of people correctly suggest using named url patterns and the {%
> > url %} template tag to obtain a URL. The concept is great and follows
> > the DRY principle. However, I believe that if a pattern has an
> > "include()" instead of a view function, the existing
> > mechanism fails. An example of the problem, using three files in a
> > standard Django project:
>
> > --file views.py--
> > def func:
> > pass
> > --end file--
>
> > --file urls.py--
> > from django.conf.urls.defaults import *
> > from views import func
> > urlpatterns = patterns('',
> > (r'^drink/', 'views.func', {'myname':'drink'}, 'drink'),
> > (r'^eat/', include('urls2'), {'myname':'eat'}, 'eat'),
> > url(r'^exercise/', func, kwargs={'myname':'exercise'},
> > name='exercise'),
> > url(r'^sleep/', include('urls2'), kwargs={'myname':'sleep'},
> > name='sleep'),
> > )
> > --end file--
>
> > --file urls2.py--
> > from django.conf.urls.defaults import *
> > urlpatterns = patterns('',
> > (r'^$', 'views.func'),
> > )
> > --end file--
>
> > Invoking "manage.py shell", these are the results of calling reverse()
> > (which I understand from the documentation works very much the same as
> > {% url %}:
>
> > >>> from django.core.urlresolvers import reverse
> > >>> reverse('drink')
> > '/drink/'
> > >>> reverse('eat')
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "c:\django\trunk\django\core\urlresolvers.py", line 297, in
> > reverse
> > return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname,
> > *args, **kw
> > args))
> >   File "c:\django\trunk\django\core\urlresolvers.py", line 284, in
> > reverse
> > raise NoReverseMatch
> > NoReverseMatch>>> reverse('exercise')
> > '/exercise/'
> > >>> reverse('sleep')
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "c:\django\trunk\django\core\urlresolvers.py", line 297, in
> > reverse
> > return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname,
> > *args, **kw
> > args))
> >   File "c:\django\trunk\django\core\urlresolvers.py", line 284, in
> > reverse
> > raise NoReverseMatch
> > NoReverseMatch
>
> > Is there a workaround for this issue? Am I doing something
> > incorrectly? Should I file a ticket?
> > Graham
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



reverse( ) and template tag 'url' fail when pattern has include

2008-02-13 Thread grahamu

Lots of people correctly suggest using named url patterns and the {%
url %} template tag to obtain a URL. The concept is great and follows
the DRY principle. However, I believe that if a pattern has an
"include()" instead of a view function, the existing
mechanism fails. An example of the problem, using three files in a
standard Django project:

--file views.py--
def func:
pass
--end file--

--file urls.py--
from django.conf.urls.defaults import *
from views import func
urlpatterns = patterns('',
(r'^drink/', 'views.func', {'myname':'drink'}, 'drink'),
(r'^eat/', include('urls2'), {'myname':'eat'}, 'eat'),
url(r'^exercise/', func, kwargs={'myname':'exercise'},
name='exercise'),
url(r'^sleep/', include('urls2'), kwargs={'myname':'sleep'},
name='sleep'),
)
--end file--

--file urls2.py--
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^$', 'views.func'),
)
--end file--

Invoking "manage.py shell", these are the results of calling reverse()
(which I understand from the documentation works very much the same as
{% url %}:

>>> from django.core.urlresolvers import reverse
>>> reverse('drink')
'/drink/'
>>> reverse('eat')
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\django\trunk\django\core\urlresolvers.py", line 297, in
reverse
return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname,
*args, **kw
args))
  File "c:\django\trunk\django\core\urlresolvers.py", line 284, in
reverse
raise NoReverseMatch
NoReverseMatch
>>> reverse('exercise')
'/exercise/'
>>> reverse('sleep')
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\django\trunk\django\core\urlresolvers.py", line 297, in
reverse
return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname,
*args, **kw
args))
  File "c:\django\trunk\django\core\urlresolvers.py", line 284, in
reverse
raise NoReverseMatch
NoReverseMatch

Is there a workaround for this issue? Am I doing something
incorrectly? Should I file a ticket?
Graham
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: get blogs with no entries

2008-02-07 Thread grahamu

The best I've been able to come up with is:

qs1 = Blog.objects.all()
qs2 = qs1.filter(entry__blog__isnull=False)
qs3 = filter(lambda x: x not in qs2, qs1)

Surely there is a better method.


On Feb 7, 1:02 pm, grahamu <[EMAIL PROTECTED]> wrote:
> Using the conventional Blog and Entry models from the Django database
> API docs:
>
> class Blog(models.Model):
> name = models.CharField(max_length=100)
> ...
>
> class Entry(models.Model):
> blog = models.ForeignKey(Blog)
> headline = models.CharField(max_length=255)
> ...
>
> How can one retrieve a queryset of Blogs with no Entries?
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



get blogs with no entries

2008-02-07 Thread grahamu

Using the conventional Blog and Entry models from the Django database
API docs:

class Blog(models.Model):
name = models.CharField(max_length=100)
...

class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
...

How can one retrieve a queryset of Blogs with no Entries?
--~--~-~--~~~---~--~~
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: YUI file upload and form errors

2008-01-28 Thread grahamu

Update: The info about "normal location" for response data is
incorrect. With YUI Connection Manager the response data is always in
o.responseText. My problem had something to do with "text/html" mime
encoding of the escaped string "". Somehow this was getting
changed at the browser to "", and that would not JSON
decode. Replacing "" with "" solves the problem because the
pesky escaping weirdness no longer occurs.

On Jan 3, 9:48 am, "Graham Ullrich" <[EMAIL PROTECTED]> wrote:
> Malcolm,
> Thanks so much for your suggestion. With that knowledge I found the problem
> in 10 minutes. The culprit turns out to be the YUI Connection Manager. As it
> turns out, when handling a file upload they change the location of the
> returned data. My response gets placed in a totally different child element
> when there is a file field, and yet the "normal" location contains an
> escaped version of the response.
>
> FWIW, the normal location for the view response data is o.responseText. With
> a file upload, the location is o.responseXML.body.textContent.
>
> Thanks again.
> Graham
>
> On 1/3/08, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Wed, 2008-01-02 at 15:38 -0800, grahamu wrote:
> > [...]
> > > As an example, the JSON response seen by the javascript might be:
>
> > >"{\"valid\": false, \"errors\": {\"options\": \"ul class=\
> > > \"errorlist\\"liThis field is required.\/li\/
> > > ul\"}}"
>
> > > when it should be:
>
> > >"{\"valid\": false, \"errors\": {\"options\": \" > > \"errorlist\\">This field is required.<\/li><\/ul>\"}}"
>
> > > You can see that the Django system encapsulates the entire response in
> > >  tags. Additionally, the underlying error message HTML is
> > > also escaped.
>
> > You might want to double-check that you're debugging the correct
> > problem. There is no code in Django that is adding the "pre" tags here.
> > The only occurrence of the string "<pre" in the source code is in a
> > docstring for the "debug" template tag. So working out at which step
> > that extra content is being added will no doubt help you zero in on the
> > problem code.
>
> > Regards,
> > Malcolm
>
> > --
> > Two wrongs are only the beginning.
> >http://www.pointy-stick.com/blog/
--~--~-~--~~~---~--~~
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: YUI file upload and form errors

2008-01-02 Thread grahamu


On Jan 2, 7:13 pm, grahamu <[EMAIL PROTECTED]> wrote:
> > On Jan 2, 4:43 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
> > wrote:
>
> > > On Wed, 2008-01-02 at 15:38 -0800, grahamu wrote:
> > > > Hi,
> > > > I'm having a problem with Django "HTML escaping" JSON data sent in
> > > > response to an asynchronous form submission when the form has an
> > > >  field. Forms that don't have a file field
> > > > yield proper responses, and when Javascript is disabled on the browser
> > > > normal form submissions work as well.
>
> > > > I'm using the Yahoo User Interface library, specifically the Dialog &
> > > > Connection Manager components, to send and receive asynchronous
> > > > messages to/from my view.
>
> > > > As an example, the JSON response seen by the javascript might be:
>
> > > >"{\"valid\": false, \"errors\": {\"options\": \"ul class=\
> > > > \"errorlist\\"liThis field is required.\/li\/
> > > > ul\"}}"
>
> > > > when it should be:
>
> > > >"{\"valid\": false, \"errors\": {\"options\": \" > > > \"errorlist\\">This field is required.<\/li><\/ul>\"}}"
>
> > > > You can see that the Django system encapsulates the entire response in
> > > >  tags. Additionally, the underlying error message HTML is
> > > > also escaped.
>
> > > > Does anyone know why this escaping might be happening? Can you suggest
> > > > how I might avoid the escaping of the response?
>
> > > Both the "why" and the "how" are documented in docs/templates_python.txt
> > > in the source. The short answer is that any time a variable is rendered
> > > into a template auto-escaping is applied. If you don't want this to
> > > happen, you can mark the particular variable as safe from further
> > > escaping using either mark_safe() in your view (probably the best
> > > approach -- marking it safe as soon as you know that fact) or in the
> > > template with the "safe" filter ({{ some_var|safe }}) or wrap an entire
> > > section of the template within the {% autoescape off %} ... {%
> > > endautoescape %} template tag.
>
> > > Regards,
> > > Malcolm
>
> > > --
> > > A conclusion is the place where you got tired of 
> > > thinking.http://www.pointy-stick.com/blog/
>
> > Malcom,
> > Thanks for your speedy response. I don't believe this is a template
> > issue as I'm returning a JSON response and not rendering to a
> > template.
>
> > The view code logic:
>
> >if not form.is_valid():
> >   return JSONFormErrors(form)
> >else:
> >   # return some other data
>
> > and:
>
> >def JSONFormErrors(form):
> >   errors = form.errors
> >   response_dict = {}
> >   response_dict.update({'valid': not errors})
> >   response_dict.update({'errors': errors})
> >   return JsonResponse(response_dict)
>
> >class JsonResponse(HttpResponse):
> >   def __init__(self, data):
> >  HttpResponse.__init__(self, json_encode(data),
> > mimetype='application/javascript')
>
> > json_encode is a version of Wolfgang Kriesing's encoder (http://
> > dpaste.com/hold/25654/).
>
> Just to be clear, the encoding problem _does not_ occur when the form
> does not have an  field. Form errors are returned
> in the JSON string in perfect form, no HTML escaping happens. And the
> view logic (code path) is identical whether or not a file input field
> is present in the form.
> Graham

I tried marking all error strings as safe...

def JSONFormErrors(form):
from django.utils.safestring import mark_safe
errors = form.errors

# mark each value (string) in the error dictionary as safe
for key in errors:
mark_safe(errors[key])

response_dict = {}
response_dict.update({'valid': not errors})
response_dict.update({'errors': errors})
return = JsonResponse(response_dict)

...but that had no effect. Debugging this is tough, I can't seem to
find the code which is escaping the output. If I can find that perhaps
I can determine why it is getting escaped.

Any ideas?
--~--~-~--~~~---~--~~
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: YUI file upload and form errors

2008-01-02 Thread grahamu

> On Jan 2, 4:43 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > On Wed, 2008-01-02 at 15:38 -0800, grahamu wrote:
> > > Hi,
> > > I'm having a problem with Django "HTML escaping" JSON data sent in
> > > response to an asynchronous form submission when the form has an
> > >  field. Forms that don't have a file field
> > > yield proper responses, and when Javascript is disabled on the browser
> > > normal form submissions work as well.
>
> > > I'm using the Yahoo User Interface library, specifically the Dialog &
> > > Connection Manager components, to send and receive asynchronous
> > > messages to/from my view.
>
> > > As an example, the JSON response seen by the javascript might be:
>
> > >"{\"valid\": false, \"errors\": {\"options\": \"ul class=\
> > > \"errorlist\\"liThis field is required.\/li\/
> > > ul\"}}"
>
> > > when it should be:
>
> > >"{\"valid\": false, \"errors\": {\"options\": \" > > \"errorlist\\">This field is required.<\/li><\/ul>\"}}"
>
> > > You can see that the Django system encapsulates the entire response in
> > >  tags. Additionally, the underlying error message HTML is
> > > also escaped.
>
> > > Does anyone know why this escaping might be happening? Can you suggest
> > > how I might avoid the escaping of the response?
>
> > Both the "why" and the "how" are documented in docs/templates_python.txt
> > in the source. The short answer is that any time a variable is rendered
> > into a template auto-escaping is applied. If you don't want this to
> > happen, you can mark the particular variable as safe from further
> > escaping using either mark_safe() in your view (probably the best
> > approach -- marking it safe as soon as you know that fact) or in the
> > template with the "safe" filter ({{ some_var|safe }}) or wrap an entire
> > section of the template within the {% autoescape off %} ... {%
> > endautoescape %} template tag.
>
> > Regards,
> > Malcolm
>
> > --
> > A conclusion is the place where you got tired of 
> > thinking.http://www.pointy-stick.com/blog/
>
> Malcom,
> Thanks for your speedy response. I don't believe this is a template
> issue as I'm returning a JSON response and not rendering to a
> template.
>
> The view code logic:
>
>if not form.is_valid():
>   return JSONFormErrors(form)
>else:
>   # return some other data
>
> and:
>
>def JSONFormErrors(form):
>   errors = form.errors
>   response_dict = {}
>   response_dict.update({'valid': not errors})
>   response_dict.update({'errors': errors})
>   return JsonResponse(response_dict)
>
>class JsonResponse(HttpResponse):
>   def __init__(self, data):
>  HttpResponse.__init__(self, json_encode(data),
> mimetype='application/javascript')
>
> json_encode is a version of Wolfgang Kriesing's encoder (http://
> dpaste.com/hold/25654/).

Just to be clear, the encoding problem _does not_ occur when the form
does not have an  field. Form errors are returned
in the JSON string in perfect form, no HTML escaping happens. And the
view logic (code path) is identical whether or not a file input field
is present in the form.
Graham

--~--~-~--~~~---~--~~
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: YUI file upload and form errors

2008-01-02 Thread grahamu

On Jan 2, 4:43 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Wed, 2008-01-02 at 15:38 -0800, grahamu wrote:
> > Hi,
> > I'm having a problem with Django "HTML escaping" JSON data sent in
> > response to an asynchronous form submission when the form has an
> >  field. Forms that don't have a file field
> > yield proper responses, and when Javascript is disabled on the browser
> > normal form submissions work as well.
>
> > I'm using the Yahoo User Interface library, specifically the Dialog &
> > Connection Manager components, to send and receive asynchronous
> > messages to/from my view.
>
> > As an example, the JSON response seen by the javascript might be:
>
> >"{\"valid\": false, \"errors\": {\"options\": \"ul class=\
> > \"errorlist\\"liThis field is required.\/li\/
> > ul\"}}"
>
> > when it should be:
>
> >"{\"valid\": false, \"errors\": {\"options\": \" > \"errorlist\\">This field is required.<\/li><\/ul>\"}}"
>
> > You can see that the Django system encapsulates the entire response in
> >  tags. Additionally, the underlying error message HTML is
> > also escaped.
>
> > Does anyone know why this escaping might be happening? Can you suggest
> > how I might avoid the escaping of the response?
>
> Both the "why" and the "how" are documented in docs/templates_python.txt
> in the source. The short answer is that any time a variable is rendered
> into a template auto-escaping is applied. If you don't want this to
> happen, you can mark the particular variable as safe from further
> escaping using either mark_safe() in your view (probably the best
> approach -- marking it safe as soon as you know that fact) or in the
> template with the "safe" filter ({{ some_var|safe }}) or wrap an entire
> section of the template within the {% autoescape off %} ... {%
> endautoescape %} template tag.
>
> Regards,
> Malcolm
>
> --
> A conclusion is the place where you got tired of 
> thinking.http://www.pointy-stick.com/blog/

Malcom,
Thanks for your speedy response. I don't believe this is a template
issue as I'm returning a JSON response and not rendering to a
template.

The view code logic:

   if not form.is_valid():
  return JSONFormErrors(form)
   else:
  # return some other data

and:

   def JSONFormErrors(form):
  errors = form.errors
  response_dict = {}
  response_dict.update({'valid': not errors})
  response_dict.update({'errors': errors})
  return JsonResponse(response_dict)

   class JsonResponse(HttpResponse):
  def __init__(self, data):
 HttpResponse.__init__(self, json_encode(data),
mimetype='application/javascript')

json_encode is a version of Wolfgang Kriesing's encoder (http://
dpaste.com/hold/25654/).

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



YUI file upload and form errors

2008-01-02 Thread grahamu

Hi,
I'm having a problem with Django "HTML escaping" JSON data sent in
response to an asynchronous form submission when the form has an
 field. Forms that don't have a file field
yield proper responses, and when Javascript is disabled on the browser
normal form submissions work as well.

I'm using the Yahoo User Interface library, specifically the Dialog &
Connection Manager components, to send and receive asynchronous
messages to/from my view.

As an example, the JSON response seen by the javascript might be:

   "{\"valid\": false, \"errors\": {\"options\": \"ul class=\
\"errorlist\\"liThis field is required.\/li\/
ul\"}}"

when it should be:

   "{\"valid\": false, \"errors\": {\"options\": \"This field is required.<\/li><\/ul>\"}}"

You can see that the Django system encapsulates the entire response in
 tags. Additionally, the underlying error message HTML is
also escaped.

Does anyone know why this escaping might be happening? Can you suggest
how I might avoid the escaping of the response?

Graham
--~--~-~--~~~---~--~~
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: Newforms: Override FileField save method

2007-06-06 Thread grahamu

Russ,
Perhaps you are correct. I am using 5335 patched with #3297, but guess
I just don't know how to code (or name?) the necessary method.

This explanation of what I'm doing may help:

class ToolRun(models.Model):
revision = models.IntegerField(blank=True, null=True)
project = models.ForeignKey(Project, blank=False)
tool = models.ForeignKey(Tool)
input_file = models.FileField(upload_to="/")

The form is created like this:

FormClass = forms.models.form_for_model(ToolRun)
post_data = request.POST.copy()
post_data.update(request.FILES)
form = FormClass(post_data)

The form has the 'project' and 'revision' fields hidden and
initialized. The form asks the user to enter the 'tool' and
'input_file'. Once POSTed, if the input data is valid I check in the
view for an existing ToolRun instance with matching project, tool and
input_file. If what was entered does not exist, create a new ToolRun
and upload the file. If what was entered does exist, simply upload the
(identically named) file.

clean = form.cleaned_data
try:
toolrun = ToolRun.objects.get(project=clean['project'],
  tool=clean['tool'],
  input_file=clean['input_file']
['filename'])
save_instance(form, toolrun)
except ObjectDoesNotExist:
toolrun = form.save()

Problems I have are threefold:
1. With either type of save I cannot seem to override the 'upload_to'
location string before the file contents are saved.
2. If a file with the same name already exists in the appropriate
'upload_to' location, I want to delete that file prior to saving the
new file.
3. I really don't want the 'upload_to' path prepended to the filename
stored in 'input_file' in the ToolRun instance.

I imagine that newforms has hooks to let me solve this, I just cannot
seem to find them. FWIW, I do have the following additional methods in
the ToolRun class:

def save(self):
# set the upload directory for the input file
for f in self._meta.fields:
if f.attname == 'input_file':
f.upload_to = "/%d/%d' % (self.project.id,
self.tool.id)
super(ToolRun, self).save()

This has no effect on where the uploaded files are stored, so I added
this "save_FOO_file" method to the ToolRun model class:

def save_input_file_file(filename, raw_contents):
# save it in the correct subdir


According to the debugger, this function is never called.

Thanks for your assistance!

Graham


On Jun 6, 6:41 pm, "Russell Keith-Magee" <[EMAIL PROTECTED]>
wrote:
> On 6/7/07, grahamu <[EMAIL PROTECTED]> wrote:
>
>
>
> > Does anyone here know where/how I should override the default save
> > method for a newforms-based FileField?
>
> It looks like you're looking for the functionality requested in ticket
> #3297. The patch that is there works, but probably won't be accepted
> as-is; I've been working on a slightly different patch, which I should
> be able to put up for comment tonight.
>
> However, as a stop-gap measure, the existing patch on #3297 will
> suffice. The differences between my patch and the existing #3297 are
> subtle; transitioning from using one patch to the other shouldn't be
> too onerous.
>
> Yours,
> Russ Magee %-)


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

2007-06-06 Thread grahamu

Just a clarification, the model instance save is being done via
form.save(), not directly from the instance.
Graham

On Jun 6, 3:43 pm, grahamu <[EMAIL PROTECTED]> wrote:
> Does anyone here know where/how I should override the default save
> method for a newforms-based FileField?
>
> Specifically, I want to dictate the location where the file is saved
> because the location will be different for every instance of my model.
> Additionally I want to remove any existing file with the same name
> before saving the new file. Currently if the file already exists,
> underscores are appended to the filename, and this doesn't work for
> me.
>
> Also of interest is stripping the path from the filename before it is
> saved in the model instance.
>
> Thanks,
> Graham


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



Newforms: Override FileField save method

2007-06-06 Thread grahamu

Does anyone here know where/how I should override the default save
method for a newforms-based FileField?

Specifically, I want to dictate the location where the file is saved
because the location will be different for every instance of my model.
Additionally I want to remove any existing file with the same name
before saving the new file. Currently if the file already exists,
underscores are appended to the filename, and this doesn't work for
me.

Also of interest is stripping the path from the filename before it is
saved in the model instance.

Thanks,
Graham


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



Re: Django IDE

2007-04-04 Thread grahamu

Sure, works great. My favorite (and perhaps most useful) feature is
debugging a Django app and stepping through both my code and the
Django code to find out what is happening.
Graham

On Apr 4, 6:56 pm, "Richard Blumberg" <[EMAIL PROTECTED]>
wrote:
> Has anyone had any experience using Komodo as an IDE for Django development?
>
> 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-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to get object after form.save() ?

2007-03-01 Thread grahamu


On Mar 1, 12:53 pm, "Honza Král" <[EMAIL PROTECTED]> wrote:

> > 1. Is there an easy way to get the new object created by form.save()?
>
> obj = form.save()

Thanks, I finally saw that after perusing the django source code.

> > 2. Is is true that one should not call form.save() if the form was
> > instantiated from a class resulting from form_for_instance()?
>
> no, this is not true, if it were the case, why would the method be there?

I agree with you; however, I was referencing the user "chasfs" who
commented in:

(http://groups.google.com/group/django-users/browse_frm/thread/
cbbf169b6aaa3f39/3f08ba5b59feea3d?lnk=st=form_for_instance
+form.save=6#3f08ba5b59feea3d)

writing:

"and finally, if you are using form_for_instance, to update an
existing
instance, you can't use the form.save - instead try something like
this:
  form = forms.form_for_instance(obj,
formfield_callback=obj_callback)
(request.POST)
if form.is_valid():
  for i in form.clean_data:
obj.__setattr__(i, form.clean_data[i])
  obj.save()
  return HttpResponseRedirect(...)"

Thanks for your assistance Honza!
Graham


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



how to get object after form.save() ?

2007-02-28 Thread grahamu

Hi all,
Two newforms questions...

1. Is there an easy way to get the new object created by form.save()?
2. Is is true that one should not call form.save() if the form was
instantiated from a class resulting from form_for_instance()?

Thanks,
Graham


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



Re: setting newforms ModelChoiceField "selection"

2007-02-27 Thread grahamu

Doh!
If I had taken the time to read a post from two hours earlier I would
have seen the answer. Use "initial" when instantiating the form. The
last line below does the trick.

if request.method == 'POST':
form = FormClass(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.save()
return HttpResponseRedirect("/webtools/project/")
else:
if acct:
# if the account is valid, set it as the default in the
choice field
try:
account = Account.objects.get(id=acct)
except Account.DoesNotExist:
form = FormClass()
else:
# set default choice
form = FormClass(initial={'account': account.id})


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



setting newforms ModelChoiceField "selection"

2007-02-27 Thread grahamu

I'm struggling with a newforms issue. Specifically I'm trying to pre-
select an option in a ModelChoiceField and I cannot figure out how
this can be accomplished. Here are the code snippets:

class Account(models.Model):
title = models.CharField(maxlength=30, unique=True,
db_index=True, blank=False)
administrator = models.ForeignKey(User,
related_name="admin_accounts", blank=False)
users = models.ManyToManyField(User, blank=True, null=True)

class Project(models.Model):
account = models.ForeignKey(Account, blank=False)
title = models.CharField(maxlength=50, blank=False)

def add_project(request, acct=None):
# get new Project form class
FormClass = forms.models.form_for_model(Project)

# get accounts associated with this user
FormClass.base_fields['account'] = \
forms.ModelChoiceField
(queryset=Account.objects.filter(users__username=request.user.username))

if acct:
# if the specified account is valid, set it as the
"selection" in the choice field
try:
account = Account.objects.get(id=acct)
except Account.DoesNotExist:
pass
else:
# set default choice here?
pass

if request.method == 'POST':
form = FormClass(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/webtools/project/")
else:
form = FormClass()

return render_to_response('add_project.html', {'form': form})


Before rendering the form I want to pre-select the option in the
'account' choice field that corresponds to this account. Presumably
I'll need to look at the options as created by the ModelChoiceField
and match one with account.id or something. However I cannot figure
out how to set the "selection" value before rendering. Any ideas?

Graham


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