Re: modelformset_factory, initial, and queryset

2010-10-17 Thread Tim Valenta
> The only thing I can think of is that the choices for the field are
> not being set correctly to start with - in the bit where you write
> `(choices=[yada yada]`, what is 'yada yada'? Obviously, this must
> contain *all* possible values for the codes across all responses, so
> that the relevant ones can be selected for each item in the formset.

I had shortened it because it was a gross little bit of code which
effectively takes a queryset of another model and turns them into a
customized "choice" strings.  The result is just a giant tuple of (id,
"name") pairs, where the `id` is the value I'm interested in injecting
into the `codes` field.  You are right about it needing to contains
*all* possible codes.

Did your test work for just `extra` forms, or did it also work out for
existing instances?  The part that kills me as I test is that I have
poked around in the field object after I try to set the `initial`
values, and my inserted ids are there among the other initial values
from the instance value, yet `codes` would just not show up on my the
form.

If it works for you, then I really need to break this down and examine
more contextual details!

Thanks for the input.

-- 
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: modelformset_factory, initial, and queryset

2010-10-17 Thread Tim Valenta
Sir, I just re-examined my code and realized that the integers I was
plugging into `initial` was the wrong value, semantically speaking.
IDs from the wrong model were being used for initial values...
Simplifying my example for this explanation helped me see that pretty
quickly when I pulled my code up just now.

Thanks for the second pair of eyes!  I knew of course that the
`initial` keyword argument worked in my other views, but I doubted
myself.  Surprising how many really lame mistakes you can make even
after a couple years of using Django every day!

Tim

On Sun, Oct 17, 2010 at 08:38, Tim Valenta <tonightslasts...@gmail.com> wrote:
>> The only thing I can think of is that the choices for the field are
>> not being set correctly to start with - in the bit where you write
>> `(choices=[yada yada]`, what is 'yada yada'? Obviously, this must
>> contain *all* possible values for the codes across all responses, so
>> that the relevant ones can be selected for each item in the formset.
>
> I had shortened it because it was a gross little bit of code which
> effectively takes a queryset of another model and turns them into a
> customized "choice" strings.  The result is just a giant tuple of (id,
> "name") pairs, where the `id` is the value I'm interested in injecting
> into the `codes` field.  You are right about it needing to contains
> *all* possible codes.
>
> Did your test work for just `extra` forms, or did it also work out for
> existing instances?  The part that kills me as I test is that I have
> poked around in the field object after I try to set the `initial`
> values, and my inserted ids are there among the other initial values
> from the instance value, yet `codes` would just not show up on my the
> form.
>
> If it works for you, then I really need to break this down and examine
> more contextual details!
>
> Thanks for the input.
>

-- 
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: modelformset_factory, initial, and queryset

2010-10-15 Thread Tim Valenta
I have a model like such:
class Response(models.Model):
raw_text = models.TextField()
respondent = models.ForeignKey('auth.User')

Response has a related model attached to it:
class Code(models.Model):
response = models.ForeignKey(Response)
coded_answer = models.IntegerField()

The idea is that Responses come in as typed text, and then are
processed and assigned standardized Codes to represent the meaning
contained in the text.

Now, it greatly simplifies my life if I can use a normal formset to
represent the main Response objects gathered on a page for processing,
using the 'queryset' parameter to scope the Responses being handled.
I'm making use of the admin's filtered select widget in a ModelForm
for the Response model, like so:
class ResponseCodingForm(forms.ModelForm):
codes = forms.MultipleChoiceField(choices=[yada yada],
widget=FilteredSelectMultiple('Codes', false))
class Meta:
model = Response
fields = ['raw_text']

As you can see, the form only represents the "raw_text" field, but
adds a virtualized field called "codes" to the mix, which I want to
manage myself.  That is, I want to inject data values into it when I
create my formset, as you will soon see.  This approach works great
for when I render the formset, properly placing a field for "codes" on
my forms.  Naturally, the value of this field gets POSTed back to my
view, which I happily read from my form's cleaned_data attribute,
processing as I see fit.

But when it comes time to instantiate my formset, I can't find a way
to pump my own values into this "codes" field on the form.  Here is
the relevant part of the view:
responses = Response.objects.filter( yada yada)
ResponseCodingFormSet = modelformset_factory(Response,
form=ResponseCodingForm, extra=0)
initial = [{
'codes': list(response.code_set.values_list('id', flat=True)),
} for response in responses]

if request.method == 'POST':
# handle validation and save operations
else:
formset = ResponseCodingFormSet(queryset=responses,
initial=initial)


I realize that what I'm doing could be handled by some inline
formsets, but I really wanted to leverage that FilteredSelectMultiple
widget to represent my related model association.

No matter what I do, the formset's value for any of the objects'
"codes" field is empty.

On Oct 14, 3:09 am, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Oct 14, 10:32 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
>
>
>
>
>
>
>
>
> > This is driving me mad, so I must ask the community, in hopes of a
> > workaround:
>
> > I've got a simple formset of models on a page, generated by
> > modelformset_factory.  This particular page will never create forms--
> > it only modifies existing ones.  Therefore the queryset I pass into
> > the formset constructor gets built, and everything works great.
>
> > I've added a field to the formset, but Django seems perfectly happy to
> > totally ignore whatever initial data I want to supply for this
> > 'virtual' field that I've added.  It seems that I've got absolutely no
> > mechanism for setting a dynamically-generated value as a pre-computed
> > field value.
>
> > My situation is that I want to represent an many-to-many relationship
> > on this 'virtual' field, which doesn't actually exist on my model.
> > When the form is submitted, I can easily intercept the values sent and
> > do what I will with them.  However, when the page refreshes after a
> > submission, I cannot for the life of me inject this data back into the
> > form.  As of right now, my select-multiple widget is quite blank, no
> > matter what I do.
>
> > Help?  I've literally been at this for hours off and on.
>
> Can you show some code? It would help to understand what you're doing.
> --
> 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.



modelformset_factory, initial, and queryset

2010-10-14 Thread Tim Valenta
This is driving me mad, so I must ask the community, in hopes of a
workaround:

I've got a simple formset of models on a page, generated by
modelformset_factory.  This particular page will never create forms--
it only modifies existing ones.  Therefore the queryset I pass into
the formset constructor gets built, and everything works great.

I've added a field to the formset, but Django seems perfectly happy to
totally ignore whatever initial data I want to supply for this
'virtual' field that I've added.  It seems that I've got absolutely no
mechanism for setting a dynamically-generated value as a pre-computed
field value.

My situation is that I want to represent an many-to-many relationship
on this 'virtual' field, which doesn't actually exist on my model.
When the form is submitted, I can easily intercept the values sent and
do what I will with them.  However, when the page refreshes after a
submission, I cannot for the life of me inject this data back into the
form.  As of right now, my select-multiple widget is quite blank, no
matter what I do.

Help?  I've literally been at this for hours off and on.

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



Blank Admin changelist with list_display FK

2010-03-16 Thread Tim Valenta
I've noticed this a few times in my code, and it seemed to come and go as an
issue:

Using various revisions from the SVN trunk over the last 4 months, the
following has caused my admin changelist view for a model to go completely
blank:
# events/models.py
class Event(models.Model):
location = models.ForeignKey('organization.Location')

# admin.py
class EventAdmin(admin.ModelAdmin):
list_display = ('location',)

Yet, this works correctly, and everything shows up as expected--- no bad
data or anything:
# admin.py
class EventAdmin(admin.ModelAdmin):
list_display = ('_location_dummy',)
def _location_dummy(self, instance):
return instance.location

I've literally removed everything from EventAdmin except for the
list_display, as shown.

The ticket tracker shows a *possibly* related issue (
http://code.djangoproject.com/ticket/11460), but I don't think it's the same
thing.  In short, when foreign keys are actually invalid, the changelist
wouldn't show the row.  In my case however, the entire changelist goes
blank.

An example screenshot:
http://img251.imageshack.us/img251/9950/90902063.png


I used to think that this could have been related to overriding admin
templates, but I'm not even doing that in this project.

Has anybody ever experienced this?  It was seriously working just an hour
ago, but somehow I've edited something, somewhere, which suddenly began
causing this problem.  I was working on some ModelForms at the time, but
there are no forms involved with my simple example as shown above!

-- 
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: PicklingError with Queryset Refactor

2010-02-24 Thread Tim Valenta
H... I need to redact my statement about pickling working on the
filesystem cache back-end.  On one particular Windows development
machine it works, but not on a linux box with identical code on
Apache.

Which leaves me in an even more strange situation... why does the
development server's pickling action act differently than that in
Apache's?  I don't think it was just failing silently, because I was
specifically trying to lower my database query hits while I coded that
bit of caching, and it was a major contribution to the effort...

Either way, it looks like I'm going to be reworking a piece of my
code, since the development server tricked me into thinking that I
could pickle those QuerySets.

On Feb 24, 8:14 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> There was a topic on this a couple of years ago, and it seems to still
> be around.  
> (Original:http://groups.google.com/group/django-users/browse_thread/thread/3214...)
>
> An exception is raised when trying to use the low-level caching API on
> a QuerySet.  I read from the mentioned thread that pickling the a
> QuerySet after the refactor branch was merged has troubles, and as
> Malcom has said, it's just straight-up "hard".
>
> Especially from the documentation's explanation, I can see why it's no
> easy task:
>
>     "This means that when you unpickle a QuerySet, it contains the
> results at the moment it was pickled, rather than the results that are
> currently in the database."
>
> Is there any hope of this being addressed in the near future?  I know
> 1.2 is feature-frozen, but what's the likelihood that this is going to
> be fixed?  Can the documentation on Pickling QuerySets be updated to
> actually reflect this issue?  The docs don't bring this up at all.
> What's worse, is that pickling the QuerySets actually seems to work
> just fine with the filesystem caching backend.  I can't begin to tell
> you how long it took me to figure out the problem.
>
> So... what's the difference between a pickled QuerySet in a filesystem
> cache and a pickled QuerySet in a database cache?  It's the same
> pickled string in the end.  I had a look at the area of code raising
> the Exception, and I frankly don't understand what the backend has to
> do with that line of code. (http://code.djangoproject.com/browser/
> django/trunk/django/core/cache/backends/db.py line 57)
>
> This creates annoying trouble for someone like me, trying to use a
> database-driven caching system, yet specific parts of my site cannot
> use my back-end of choice.
>
> I've read the workaround of caching the list version of the results,
> and I am looking into that.  I just want to find out a little more
> about what the situation is, two years after that initial thread.
>
> Tim

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



PicklingError with Queryset Refactor

2010-02-24 Thread Tim Valenta
There was a topic on this a couple of years ago, and it seems to still
be around.  (Original: 
http://groups.google.com/group/django-users/browse_thread/thread/32143d024b17dd00?pli=1)

An exception is raised when trying to use the low-level caching API on
a QuerySet.  I read from the mentioned thread that pickling the a
QuerySet after the refactor branch was merged has troubles, and as
Malcom has said, it's just straight-up "hard".

Especially from the documentation's explanation, I can see why it's no
easy task:

"This means that when you unpickle a QuerySet, it contains the
results at the moment it was pickled, rather than the results that are
currently in the database."

Is there any hope of this being addressed in the near future?  I know
1.2 is feature-frozen, but what's the likelihood that this is going to
be fixed?  Can the documentation on Pickling QuerySets be updated to
actually reflect this issue?  The docs don't bring this up at all.
What's worse, is that pickling the QuerySets actually seems to work
just fine with the filesystem caching backend.  I can't begin to tell
you how long it took me to figure out the problem.

So... what's the difference between a pickled QuerySet in a filesystem
cache and a pickled QuerySet in a database cache?  It's the same
pickled string in the end.  I had a look at the area of code raising
the Exception, and I frankly don't understand what the backend has to
do with that line of code. (http://code.djangoproject.com/browser/
django/trunk/django/core/cache/backends/db.py line 57)

This creates annoying trouble for someone like me, trying to use a
database-driven caching system, yet specific parts of my site cannot
use my back-end of choice.

I've read the workaround of caching the list version of the results,
and I am looking into that.  I just want to find out a little more
about what the situation is, two years after that initial thread.

Tim

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

2009-12-16 Thread Tim Valenta
I wanted to echo what Bill has just said.

One simple (yet effective) reason why allowing multiple models/views
in a single file is handy is because you get to remove lots of
duplicate code surrounding imports and utility functions.

Bill's process should be able to work, theoretically.  You may want to
try it out, but I would first suggest evaluating just how necessary
this Java-like structure is, and what it would really do for you.  It
really only makes it more prone to breaking, if a model or view names
change.  You'll have to be sure that such future changes are
propagated into the various __init__.py files required to drive the
directory structure.

On Dec 16, 2:35 pm, Bill Freeman  wrote:
> 1.  You must place a file __init__.py in each sub-directory (folder)
> from which you will import, such as your models and views directories.
>
> 2.  The __init__.py in your models directory must import all modules
> containing modules.  When you add an app to installed apps in
> settings.py, django will import models in that app.  Normally this is
> models.py and importing it causes the model classes to be defined, and
> their __metaclass__ (do not confuse this with the Meta nested class)
> registers the model.  This is how syncdb can know what models exist,
> for example.  But in your case only models/__init__.py is imported,
> unless that, in turn, imports the other modules.  I still can't
> promise that this will work, since I don't know whether other parts of
> django assume and test for the existance of an actual models.py file
> in the app directory.
>
> But. java practice notwithstanding, there is nothing wrong with having
> several models in one models.py module, so why fight against the
> design of django?  If your collection of models is truly so complex
> that they should be separated into more than one module, then perhaps
> your app is too complex, and should be refactored into multiple
> applications.
>
>
>
> On Wed, Dec 16, 2009 at 2:52 PM, Bruno Cordeiro  wrote:
> > I want to create folder inside the app folder eg:
>
> > application
> >          __init__.py
> >          models.py
> >          views.py
> > manager.py
> > ...
>
> > i want to separate in folder, like, one folder to models when i put
> > models class inside like:
>
> > application
> >       __init__.py
> >       models
> >                 partner.py
> >                 anothermodel.py
> >      views
> >                index.py
> >                partner.py
>
> > why i can do it, with the best manner? i know if i make the import
> > inside the normal like models.py file like below this work, but have
> > the best way to do it?
>
> > from application.models.partner import __all__
>
> > --
>
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.

--

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




Re: How do I filter an InlineModelAdmin ForeignKey?

2009-12-16 Thread Tim Valenta
Well, you're probably getting the error on your 'extra' inlines.
self.instance is unbound in that case, and so self.instance.providers
cannot be looked up.

I wrote a little thing to fetch a proper object though... just be sure
to include your parent model's field in your fields on the inline.
Then you can use this generic utility function... you can pick pieces
out of it if you think it wiser.  I just took the sledgehammer to the
wall to get my task accomplished:

def implied_inline_fk(form, implied_model_class, field_name=None):
if not field_name:
field_name = implied_model_class.__name__.lower()
try:
return implied_model_class.objects.get(pk=tuple(i[0] for i in
form.fields[field_name].widget.choices)[1])
except IndexError:
# In the event that both the base 'original' object and inline
object don't exist,
# we need to just throw out the possibility of filtering values.
return None
except KeyError:
raise KeyError("'%s' must be included in the inline ModelAdmin's
'fields' attribute." % field_name)



You could then use this in your PartnerForm:

class PartnerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PartnerForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
# Existing instance-- safe to use
self.fields['default_provider'].queryset =
self.instance.providers
else:
# 'extra' unbound object.  Not safe.
# Must derive through some other means.
parentInstance = implied_inline_fk(self, PARENTMODEL,
'field_name_to_parent_model')
self.fields['default_provider'].queryset =
parentInstance.somelookup_to_provider_filter

Note that sometimes this doesn't really work, depending on your model
hierarchy.  You might have to throw in the towel on 'extra' inlines.
The key is to filter only when it's bound, and to work around the
filter if it's not bound.

Tim


On Dec 16, 11:10 am, Eric Chamberlain  wrote:
> I'd like PartnerRegistration's default_provider field to be filtered in 
> PartnerRegistrationInline, like how Partner's default_provider field is 
> filtered in PartnerAdmin.
>
> When I try the code below, I get a DoesNotExist exception in:
>
>         self.fields['default_provider'].queryset = 
> self.instance.partner.providers
>
>         raise self.field.rel.to.DoesNotExist
>
> What am I doing wrong?
>
> class Partner(Model):
>     id = UUIDField(primary_key=True)
>     providers = ManyToManyField('Provider', related_name='provider_partners', 
> blank=True, null=True)
>     default_provider = ForeignKey('Provider', null=True, blank=True, 
> help_text='The calling service used to make calls through by default when 
> using this partner')
>
> class PartnerForm(forms.ModelForm):
>     """ Filter and only show what belongs to this partner."""
>
>     def __init__(self, *args, **kwargs):
>         super(PartnerForm, self).__init__(*args,**kwargs)
>         self.fields['default_provider'].queryset = self.instance.providers
>
> class PartnerRegistration(Model):
>     id = UUIDField(primary_key=True)
>     partner = ForeignKey('Partner',unique=True)
>     default_provider = ForeignKey('Provider',verbose_name='default calling 
> service', help_text='User this calling service when response doesn\'t specify 
> one.')
>
> class PartnerRegistrationForm(forms.ModelForm):
>     """ Filter and only show what belongs to this partner."""
>
>     def __init__(self, *args, **kwargs):
>         super(PartnerRegistrationForm, self).__init__(*args,**kwargs)
>         self.fields['default_provider'].queryset = 
> self.instance.partner.providers
>
> class PartnerRegistrationInline(StackedInline):
>     model = PartnerRegistration
>     form = PartnerRegistrationForm
>
> class PartnerAdmin(ModelAdmin):
>     form = PartnerForm
>
>     inlines = [ PartnerRegistrationInline, ]

--

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: Save as new and files

2009-11-27 Thread Tim Valenta
Does the newly created model lack a path entirely, or does it have a
path that points to a false location?  In other words, is the right
path making it to the database, yet not to the filesystem to copy the
file?  Also, since you didn't mention anything about it, I would
remind you that a proper test would include trying to make a change to
the FileField.  If you don't try to change it, yet push "Save as new",
it won't be uploading the file again, so it won't be part of the list
of fields that it's manipulating.  And that might be where the problem
lies.  Could you confirm your suspicion from any playing around you
can do?

If you're sure that you really are setting it up for success yet it
fails anyway,  you might consider overriding "save_model" on your
ModelAdmin, so that you can play with the values and see what's going
on:

# ... in your ModelAdmin subclass
def save_model(self, request, obj, form, change):
super( **YourClassName**, self).save_model(self, request,
object, form, change)

# Check if a file upload is present on this save request
if 'your_file_field_name' in request.FILES:

# FileField object, already saved and
# migrated to the supposedly correct "upload_to" location
obj.your_file_field_name

Hope that gets some cogs turning.. :)

Tim

On Nov 27, 7:12 pm, Pawel Pilitowski  wrote:
> Hey,
>
> Mainly I would like to know what the intended behavior of "save as  
> new" is supposed to be, if it is supposed to copy the files, I will  
> look further into why its not working for me.
>
> I was assuming that it would, and didn't find anything in the  
> documentation to the contrary. If it is the desired behavior, any  
> suggestion on a good way to copy the images from one object to the  
> next? custom save() or save_model()? or should i be overwriting  
> something else?
>
> Regards,
>
> Pawel.

--

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: Cannot assign None, does not allow null values

2009-11-27 Thread Tim Valenta
You've got a lot of models in that file.  Which one are you trying to
save when it throws the error?

By the way, I notice that your "ItemWithMedia" class is probably
creating a database table.. if you never need to manipulate it direct
(ie, you only make subclasses of it), I might suggest putting this in
the definition:

class ItemWithMedia(models.Model):
# ... all of your old stuff goes here
class Meta:
abstract = True

That way Django knows it's just a base class.

Not sure what the problem is, yet...

On Nov 27, 3:27 pm, onoxo  wrote:
> btw. here is a full code:
>
> models.pyhttp://snipt.net/vedran/django-models-cannot-assign-none?key=ba151d53...
>
> admin.pyhttp://snipt.net/vedran/django-admin-cannot-assign-none?key=53222b89c...
>
> so... when i go to create new Actual item i get this error:
> Cannot assign None: "Actual.published" does not allow null values.
>
> On Nov 27, 10:57 pm, onoxo  wrote:
>
>
>
> > i get this error when i try to create new item in admin site.
>
> > here is my models.py
> > import datetime
> > from django.db import models
> > from tinymce import models as tinymce_models
> > from filebrowser.fields import FileBrowseField
>
> > class ItemWithMedia(models.Model):
> >     created = models.DateTimeField(auto_now_add=True)
> >     modified = models.DateTimeField(auto_now=True)
>
> > class Actual(ItemWithMedia):
> >     published = models.DateField('Published')
> >     title_hr = models.CharField('(hr)', max_length=200)
> >     title_en = models.CharField('(en)', max_length=200)
> >     body_text_hr = models.TextField('(hr)')
> >     body_text_en = models.TextField('(en)')
>
> >     def __unicode__(self):
> >         return self.title_hr
>
> >     class Meta:
> >         verbose_name = "Aktualno"
> >         verbose_name_plural = "Aktualni"
> >         ordering = ['-published']
>
> > what could be the problem?

--

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: CSRF gone haywire

2009-11-27 Thread Tim Valenta
Okay... so here's the problem.

I've been using a template override for change_form.html to always
check the object-tools block and add things in there.  I tried to be
more modular about it, but it never seemed to work out quite right.
So I'm overriding the entire template on my own, and I must have
copied the template from admin-ui (where, as pointed out, and as I
knew already, admin-ui doesn't implement the CSRF system).
Consequently, my overridden template was working great, until I got
off of the admin-ui branch.  Everything started failing like crazy :)

Lesson to be learned: Don't accidentally copy a template from a
branch.


Also, I've figured out just now while rereading the reply I got, that
"AFAIK" must mean "as far as I know".  Please... can we not use
ridiculous short forms for a language that works better when not
profusely abbreviated?  That would have been a hundred times harder to
figure out if I were a not a native speaker of English.  I can handle
a few of those, like IMHO, but I can't say that I've come across
"AFAIK" often enough to compute that in record time.

Tim

On Nov 27, 10:22 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
> > AFAIK admin uses CSRF by default in SVN version.
>
> I'm sorry, but I have no idea what that means.  What is "AFAIK"?
>
> I've read that page you've linked to, and I fail to see what I've done
> wrong (since I didn't explicitly *do* anything).
>
> Tim
>
> On Nov 27, 10:18 am, rebus_ <r.dav...@gmail.com> wrote:
>
>
>
> > 2009/11/27 Tim Valenta <tonightslasts...@gmail.com>:
>
> > > Has anybody else experienced a senseless failure of the dev trunk's
> > > CSRF verification?  Very suddenly this morning, Django won't let me
> > > change anything in my admin sites.  I didn't update my copy of the SVN
> > > trunk, but as soon as I took myself off of the admin-ui branch, it
> > > flipped out.
>
> > > Step by step, all I did was move my copy of the main trunk to
> > > "_django" instead of "django".  I then uncompressed the admin-ui
> > > branch to "django" as a replacement.  All was well.  There are some
> > > broken "Add new item" links in that branch, and I got sick of it not
> > > working.  So I moved my admin-ui trunk to "admin-ui" for safekeeping,
> > > and then put back my original copy of the main trunk.
>
> > > Everything seemed right and good in the world, but for some reason the
> > > changelist view wouldn't show any items in its list.  Every model
> > > suffered from the lack of display.  It was weird.  It showed a correct
> > > total number of items that *should* have been in the list, but no
> > > items were present.  The HTML was literally not there.
>
> > > And when I jump directly to a changeform page via the id I knew I was
> > > working with, the page would should up, but saving the model keeps
> > > triggering the CSRF error response.  I don't think the CSRF token is
> > > being rendered in the changeform.
>
> > > Has anybody else experienced this?  I seriously haven't touched my
> > > copy of the main trunk between my little adventure with the admin-ui
> > > branch.  For good measure, I updated the repository just now, and it
> > > didn't fix it.  I removed all of the .pyc files in the Django
> > > directory and my project home.
>
> > > I'm just totally at a loss for what happened.  I've dropped the
> > > database and rebuilt it... no luck.  I'm ready to swear that I didn't
> > > change anything at all, and I don't use the CSRF system explicitly, so
> > > it's not like I've got bad imports.
>
> > > Any help?
>
> > AFAIK admin uses CSRF by default in SVN version.
>
> >http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

--

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: CSRF gone haywire

2009-11-27 Thread Tim Valenta
> AFAIK admin uses CSRF by default in SVN version.

I'm sorry, but I have no idea what that means.  What is "AFAIK"?

I've read that page you've linked to, and I fail to see what I've done
wrong (since I didn't explicitly *do* anything).

Tim

On Nov 27, 10:18 am, rebus_ <r.dav...@gmail.com> wrote:
> 2009/11/27 Tim Valenta <tonightslasts...@gmail.com>:
>
>
>
>
>
> > Has anybody else experienced a senseless failure of the dev trunk's
> > CSRF verification?  Very suddenly this morning, Django won't let me
> > change anything in my admin sites.  I didn't update my copy of the SVN
> > trunk, but as soon as I took myself off of the admin-ui branch, it
> > flipped out.
>
> > Step by step, all I did was move my copy of the main trunk to
> > "_django" instead of "django".  I then uncompressed the admin-ui
> > branch to "django" as a replacement.  All was well.  There are some
> > broken "Add new item" links in that branch, and I got sick of it not
> > working.  So I moved my admin-ui trunk to "admin-ui" for safekeeping,
> > and then put back my original copy of the main trunk.
>
> > Everything seemed right and good in the world, but for some reason the
> > changelist view wouldn't show any items in its list.  Every model
> > suffered from the lack of display.  It was weird.  It showed a correct
> > total number of items that *should* have been in the list, but no
> > items were present.  The HTML was literally not there.
>
> > And when I jump directly to a changeform page via the id I knew I was
> > working with, the page would should up, but saving the model keeps
> > triggering the CSRF error response.  I don't think the CSRF token is
> > being rendered in the changeform.
>
> > Has anybody else experienced this?  I seriously haven't touched my
> > copy of the main trunk between my little adventure with the admin-ui
> > branch.  For good measure, I updated the repository just now, and it
> > didn't fix it.  I removed all of the .pyc files in the Django
> > directory and my project home.
>
> > I'm just totally at a loss for what happened.  I've dropped the
> > database and rebuilt it... no luck.  I'm ready to swear that I didn't
> > change anything at all, and I don't use the CSRF system explicitly, so
> > it's not like I've got bad imports.
>
> > Any help?
>
> AFAIK admin uses CSRF by default in SVN version.
>
> http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

--

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.




CSRF gone haywire

2009-11-27 Thread Tim Valenta
Has anybody else experienced a senseless failure of the dev trunk's
CSRF verification?  Very suddenly this morning, Django won't let me
change anything in my admin sites.  I didn't update my copy of the SVN
trunk, but as soon as I took myself off of the admin-ui branch, it
flipped out.

Step by step, all I did was move my copy of the main trunk to
"_django" instead of "django".  I then uncompressed the admin-ui
branch to "django" as a replacement.  All was well.  There are some
broken "Add new item" links in that branch, and I got sick of it not
working.  So I moved my admin-ui trunk to "admin-ui" for safekeeping,
and then put back my original copy of the main trunk.

Everything seemed right and good in the world, but for some reason the
changelist view wouldn't show any items in its list.  Every model
suffered from the lack of display.  It was weird.  It showed a correct
total number of items that *should* have been in the list, but no
items were present.  The HTML was literally not there.

And when I jump directly to a changeform page via the id I knew I was
working with, the page would should up, but saving the model keeps
triggering the CSRF error response.  I don't think the CSRF token is
being rendered in the changeform.

Has anybody else experienced this?  I seriously haven't touched my
copy of the main trunk between my little adventure with the admin-ui
branch.  For good measure, I updated the repository just now, and it
didn't fix it.  I removed all of the .pyc files in the Django
directory and my project home.

I'm just totally at a loss for what happened.  I've dropped the
database and rebuilt it... no luck.  I'm ready to swear that I didn't
change anything at all, and I don't use the CSRF system explicitly, so
it's not like I've got bad imports.

Any help?

--

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




Re: Issue when saving a model form

2009-11-27 Thread Tim Valenta
Try overriding your AddRestaurantForm's "save" method:

def save(self, commit=True):
self.instance.city = get_object_or_404(City,
name=self.instance.city)

# Finish by passing control back to the normal Django flow:
super(AddRestaurantForm, self).save(commit)

I think that'd work.  Sometimes 'super' causes recursion errors in
Django, so if that gives you problems, try calling the method all by
itself:

# Finish by passing control back tot he normal Django flow:
forms.ModelForm.save(self, commit)

Tim

On Nov 27, 8:57 am, jul  wrote:
> Previous post wasn't finished. Wrong key :(
> Here's the complete one:
>
> Hi,
>
> I've got the ModelForm and Model shown below.
> I'm overriding the 'city' field to get a CharField instead of a City
> foreign key.
> When saving the Restaurant instance, it returns ""Restaurant.city"
> must be a "City" instance".
> How can I save the Restaurant instance with the City instance got or
> created before?
>
> Thanks
>
> def addRestaurant(request):
>
>     if request.user.is_authenticated():
>
>         if request.method == 'POST':
>
>             form = AddRestaurantForm(request.POST)
>
>             if form.is_valid():
>
>                 geonameID = request.POST.get('city_geonameId','')
>                 country = Country.objects.get(code=request.POST.get
> ('city_countryCode',''))
>                 city, created = City.objects.get_or_create
> (geonameID=geonameID, country = country, name = form.cleaned_data
> ['city'])
>
>                 if created: #stuff
>
>                 city.save()
>
>                 new_restaurant = form.save
> (commit=False)
>                 new_restaurant.city = city
>
> class AddRestaurantForm(ModelForm):
>
>     rating = forms.IntegerField(widget=forms.Select(choices =
> RATING_CHOICE), required=False)
>     city = forms.CharField(max_length=100)
>
>     class Meta:
>         model = Restaurant
>         exclude = ('slug')
>
> class Restaurant(models.Model):
>
>     name = models.CharField(max_length=100)
>     country=models.ForeignKey(Country)
>     city=models.ForeignKey(City)
>     street=models.CharField(max_length=100)
>     street_number=models.PositiveSmallIntegerField()
>     phone_number=models.CharField(max_length=16, blank=True,
> null=True)
>     price_range=models.PositiveSmallIntegerField(blank=True,
> null=True)
>     category=models.ManyToManyField(Category, blank=True, null=True)
>     tag=models.ManyToManyField(Tag, blank=True, null=True)
>     slug = models.SlugField(unique=True)
>
>     def get_absolute_url(self):
>         return "/restaurant/%s/" % self.slug
>
>     def __unicode__(self):
>         return self.name
>
>     def save(self):
>         self.slug = slugify(self.name)
>         super(Restaurant, self).save()

--

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: add permission by name instead of number

2009-11-27 Thread Tim Valenta
You can expand your .add() statement slightly, by passing it an object
instead of an id:

request.user.user_permissions.add(Permission.objects.get(name='some
permission name'))

You could alternatively do a lookup with the "codename='some_name'"
instead of the human-readable name.  The codename is arguably less
prone to change than the straight "name" parameter.

Just be sure to import the Permission model.  It in
django.contrib.auth.models

Tim

On Nov 26, 2:59 am, Adonis  wrote:
> Hi,
>
> I have been going through the permission documentation and i know i
> can assign users with permissions like this,
>
> *
> request.user.user_permissions.add(1)
> *
>
> But having 100 or more permissions i find this method a bit weird. Is
> not there a way to say,
>
> *
> request.user.user_permissions.add('auth.delete_permission') or what i
> found in an other post,
> *
>
> *
> def get_permission_object(perm_label):
>     from django.contrib.contenttypes.models import ContentType
>     from django.contrib.auth.models import Permission
>     app_label,perm_code_name = perm_label.split('.')
>     content_type = ContentType.objects.get(app_label=app_label)
>     perm = Permission.objects.get
> (content_type=content_type,codename=perm_code_name)
>     return perm
>
> def add_perm_to_user(user,perm_label):
>     user.user_permissions.add(get_permission_object(perm_label))
>     user.save()
>     return user
> *
>
> Any suggestions?
> Thanks in advance!

--

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: distinct related objects

2009-11-27 Thread Tim Valenta
It looks like the problem is that you're trying to group by
Technology, but your queryset is in Projects.  You could experiment
with the "regroup" template tag
( http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
)

It's a little hard to understand at first, but I think it's pretty
much what you're trying to do.  You would be able to remove the
".distinct" part of your query because dictionary keys are already
can't be doubled.

Hope that helps.

Tim

On Nov 26, 7:04 am, andreas schmid  wrote:
> hi,
>
> i have a question about retrieving related objects avoiding double entries.
> actually i have 3 models:
>     topics
>     projects
>     technologies
>
> the projects model has foreignkeys to topics and technologies. i have a
> view for the topic detail like this:
>
>     def topic_detail(request, slug):
>         topic = get_object_or_404(Topic, slug=slug)
>         return object_list(request,
>                            queryset=topic.project_set.all(),
>                            paginate_by=20,
>                            template_name='FSlabs/topic_detail.html',
>                            extra_context={ 'topic': topic })
>
> in the template i can loop trough the projects and  get those  assigned
> to this topic.
> but im having problems to retrieve the technologies used by those
> projects without having double entries.
>
> i tried this in the template with a list for every project
> assigned...which of course is not what i want:
>
>     {% for project in object_list  %}
>             {% for technology in project.technologies.distinct %}
>                 {{
>     technology.title }}
>                 {% if forloop.last %}{% else %}
>                 {% ifequal forloop.revcounter0 1 %}and {% else %}, {%
>     endifequal %}
>                 {% endif %}
>             {% endfor %}
>         {% endfor %}
>
> can somebody point me to the right way to get what i need?
>
> thx

--

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




Re: How can I change the values of select options created by a ModelForm?

2009-11-27 Thread Tim Valenta
You could tell Django to designate the 'code' field as the primary
key, which will automatically make it unique.  Any forms will then be
forced to identify by the code, rather than some numeric id:

class Country(models.Model):
code = models.CharField(max_length=5, primary_key=True)
name = models.CharField(max_length=100, unique=True)

Hope that helps!  There is another way to do it as well, but I opted
to keep it simple.

Tim

On Nov 26, 10:28 am, jul  wrote:
> hi,
>
> I'm generating, using ModelForm, a form from a Restaurant model, which
> has a Country field.
> Country has a 'code' and a 'name' fields.
> When the form is created in my template, the values of the select
> options are the Country ids. How can I replace them by the Country
> 'code' values. Is it possible to choose which field is used as the
> value by overriding the Country field in the ModelForm?
>
> thanks
>
> I have that:
>
> Country:  id="id_country">
> -
> Andorra
> United Arab Emirates
> Afghanistan
>
> and I want that:
>
> Country:  id="id_country">
> -
> Andorra
> United Arab Emirates
> Afghanistan
>
> Models and ModelForm:
>
> class Country(models.Model):
>     code = models.CharField(max_length=5, unique=True)
>     name = models.CharField(max_length=100, unique=True)
>
>     class Meta:
>         verbose_name_plural = 'Countries'
>
>     def __unicode__(self):
>         return self.name
>
> class Restaurant(models.Model):
>
>     name = models.CharField(max_length=100)
>     country=models.ForeignKey(Country)
>     city=models.ForeignKey(City)
>     street=models.CharField(max_length=100)
>     street_number=models.PositiveSmallIntegerField()
>     phone_number=models.CharField(max_length=16, blank=True,
> null=True)
>     price_range=models.PositiveSmallIntegerField(blank=True,
> null=True)
>     category=models.ManyToManyField(Category, blank=True,
> null=True)
>     tag=models.ManyToManyField(Tag, blank=True, null=True)
>     slug = models.SlugField(unique=True)
>
>     def get_absolute_url(self):
>         return "/restaurant/%s/" % self.slug
>
>     def __unicode__(self):
>         return self.name
>
>     def save(self):
>         self.slug = slugify(self.name)
>         super(Restaurant, self).save()
>
> class AddRestaurantForm(ModelForm):
>
>     class Meta:
>         model = Restaurant
>         exclude = ('slug')

--

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: better error handling in templatetags?

2009-11-27 Thread Tim Valenta
spite* us all.

Sorry :)

On Nov 27, 8:27 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
> Django is forced to catch your errors, and then bubble them back up to
> you.  If you notice, none of the traceback lines are even in your
> code-- it's all in Python libs or an Django code.  The issue is that
> you're not seeing raw exceptions, but instead you're seeing reproduced
> exceptions.
>
> I agree that template tags are had to debug, especially when it's a
> big complex tag that goes wrong all of the sudden.  However, don't
> forget that it's just a Python object or method, just why not fire up
> the shell and import it, testing it out?  Step through it with input
> that you *know* you're getting, and use the Django modules to create
> dummy contexts if needed (although you could probably get away with
> just Python dict objects, since the template rendering engine won't
> actually be involved).
>
> Fixing the reporting would be amazingly welcome by many of us, but
> it's not like it's a simple matter of printing a single debug variable
> that accidentally got omitted.  I don't know enough about how Django
> bubbles exceptions, so I can't say much more on the subject, but it's
> clear to me that it's not something that they're doing on purpose to
> spit us all.
>
> Tim
>
> On Nov 27, 3:58 am, "KONTRA, Gergely" <pihent...@gmail.com> wrote:
>
>
>
> > Seems like you built your own project, and not using my zip.
>
> > However, the result IS different.
>
> > In my traceback I do not have any snippet referencing customtag.py.
>
> > See my trace:http://dpaste.com/hold/125819/
>
> > thanks
> > Gergo
> > +-[ Gergely Kontra <pihent...@gmail.com> ]--+
> > |   |
> > | Mobile:(+36 20)356 9656   |
> > |   |
> > +- "Olyan lángész vagyok, hogy poroltóval kellene járnom!" -+
>
> > On Fri, Nov 27, 2009 at 04:38, Karen Tracey <kmtra...@gmail.com> wrote:
> > > On Thu, Nov 26, 2009 at 6:02 PM, KONTRA, Gergely <pihent...@gmail.com>
> > > wrote:
>
> > >> My problem is the error handling of django in templatetags, not the
> > >> specific dummy error, which I programmed:
>
> > >> @register.simple_tag
> > >> def current_time():
> > >>        1/0
> > >>        return unicode(datetime.datetime.now())
>
> > >> What annoys me, that you cannot find the line number of the error,
> > >> just a message, that somewhere there is an error rendering the
> > >> current_time tag.
>
> > > With DEBUG=True, TEMPLATE_DEBUG=DEBUG, I get a TemplateSyntaxError debug
> > > page with exception value:
>
> > > Caught an exception while rendering: integer division or modulo by zero
>
> > > Original Traceback (most recent call last):
> > >   File "d:\u\kmt\django\trunk\django\template\debug.py", line 71, in
> > > render_node
> > >     result = node.render(context)
> > >   File "d:\u\kmt\django\trunk\django\template\__init__.py", line 909, in
> > > render
> > >     return func(*resolved_vars)
> > >   File "D:\u\kmt\software\web\playground\ttt\templatetags\tstuff.py", line
> > > 6, in current_time
> > >     1/0
> > > ZeroDivisionError: integer division or modulo by zero
>
> > > So I am seeing the line number of the error reported.  It's (somewhat
> > > annoyingly) not actually in the traceback portion of the page, but it is 
> > > on
> > > the page.  Are you seeing something different?
>
> > > Karen
>
> > > --
>
> > > You received this message because you are subscribed to the Google Groups
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.

--

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: better error handling in templatetags?

2009-11-27 Thread Tim Valenta
Django is forced to catch your errors, and then bubble them back up to
you.  If you notice, none of the traceback lines are even in your
code-- it's all in Python libs or an Django code.  The issue is that
you're not seeing raw exceptions, but instead you're seeing reproduced
exceptions.

I agree that template tags are had to debug, especially when it's a
big complex tag that goes wrong all of the sudden.  However, don't
forget that it's just a Python object or method, just why not fire up
the shell and import it, testing it out?  Step through it with input
that you *know* you're getting, and use the Django modules to create
dummy contexts if needed (although you could probably get away with
just Python dict objects, since the template rendering engine won't
actually be involved).

Fixing the reporting would be amazingly welcome by many of us, but
it's not like it's a simple matter of printing a single debug variable
that accidentally got omitted.  I don't know enough about how Django
bubbles exceptions, so I can't say much more on the subject, but it's
clear to me that it's not something that they're doing on purpose to
spit us all.

Tim

On Nov 27, 3:58 am, "KONTRA, Gergely"  wrote:
> Seems like you built your own project, and not using my zip.
>
> However, the result IS different.
>
> In my traceback I do not have any snippet referencing customtag.py.
>
> See my trace:http://dpaste.com/hold/125819/
>
> thanks
> Gergo
> +-[ Gergely Kontra  ]--+
> |   |
> | Mobile:(+36 20)356 9656   |
> |   |
> +- "Olyan lángész vagyok, hogy poroltóval kellene járnom!" -+
>
>
>
> On Fri, Nov 27, 2009 at 04:38, Karen Tracey  wrote:
> > On Thu, Nov 26, 2009 at 6:02 PM, KONTRA, Gergely 
> > wrote:
>
> >> My problem is the error handling of django in templatetags, not the
> >> specific dummy error, which I programmed:
>
> >> @register.simple_tag
> >> def current_time():
> >>        1/0
> >>        return unicode(datetime.datetime.now())
>
> >> What annoys me, that you cannot find the line number of the error,
> >> just a message, that somewhere there is an error rendering the
> >> current_time tag.
>
> > With DEBUG=True, TEMPLATE_DEBUG=DEBUG, I get a TemplateSyntaxError debug
> > page with exception value:
>
> > Caught an exception while rendering: integer division or modulo by zero
>
> > Original Traceback (most recent call last):
> >   File "d:\u\kmt\django\trunk\django\template\debug.py", line 71, in
> > render_node
> >     result = node.render(context)
> >   File "d:\u\kmt\django\trunk\django\template\__init__.py", line 909, in
> > render
> >     return func(*resolved_vars)
> >   File "D:\u\kmt\software\web\playground\ttt\templatetags\tstuff.py", line
> > 6, in current_time
> >     1/0
> > ZeroDivisionError: integer division or modulo by zero
>
> > So I am seeing the line number of the error reported.  It's (somewhat
> > annoyingly) not actually in the traceback portion of the page, but it is on
> > the page.  Are you seeing something different?
>
> > Karen
>
> > --
>
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

--

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: More media collection nightmares

2009-11-25 Thread Tim Valenta
I tend to find that Django's true potential bubbles up when all of the
components work together in an interdependent manner.  Normally that
sounds like a bad idea (too much interdependency could make it hard to
grasp the bigger picture), but for some reason, Django comes together
very nicely as you figure out how all of these components can co-
exist.

I hadn't realized that form media comes out of the queue after widget
media.  That does seem pretty backwards, since it's totally logical to
place form-wide media dependencies on the form itself.  If you're
certain that that's what it's doing, you might consider making a
simple bug report on it, with your reasoning for reporting it as
such.  The developers who go over the tickets are always looking for
solid "real-world" problems that a bug report claims to exist.  If
it's only a preferential thing, it won't get much consideration.  But
if you can prove why changing it makes more sense, you'll have a case
for making an improvement.  Bugs will be the focus of version 1.2's
development once January comes around.

Anyway, I hope things are rolling for you now :)

Tim

On Nov 25, 4:00 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> Actually, a widget required a js file that required core.js, but did not 
> specify it.  So I added core.js to the form's media list - but apparently it 
> renders the widget media, then the form media - so no good.
>
> Your second suggestion was the best - I now just include the jsi18n and 
> core.js on every page as part of the base template.
>
> So far so good.  Hopefully I won't find any more widgets with surprise 
> dependencies.
>
> -Todd Blanchard
>
> On Nov 25, 2009, at 12:14 PM, Tim Valenta wrote:
>
>
>
> > Is it a widget that has the "core.js"?  I'd suggest putting that on
> > the form instead, if that's the case.  Alternatively, if the page
> > should always have this JS anyway, you could always insert it directly
> > to the template, to avoid any ambiguity for any future eyeballs
> > wondering how it all works.

--

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

2009-11-25 Thread Tim Valenta
I know how messed up this all seems, so I sympathize.  I totally want
to store items according to a related object's name or id or whatever.

However, I'm using upload_to in a more straightforward manner, and it
seems to work out alright.  Tell me if you've already tried it this
way:

class ScreenShot(models.Model):
def _image_location(instance, filename):
return ''.join("web_projects/%Y/", instance.project.slug,
"/", filename)
# ...
image = models.ImageField(upload_to=_image_location)

The thing you pass to your field's "upload_to" value can be a
callable, which takes two arguments: the instance of `ScreenShot`
being altered, and the filename of the original file that was
uploaded.  You then just return a string of the path to save in,
including the filename.

It's all described here, which it looks like you've already read:
http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to

Does that not work for you?  I do exactly the same thing for various
fields on some of my models.  I could see how it might complicate
things if you were doing it on an inline. I admit that I haven't
tried that one out, as luck would have it.  If the main model already
exists, it should work, though.

Just brainstorming to find a simpler solution.  Have you already tried
it that way?

Tim

On Nov 25, 12:08 pm, neridaj  wrote:
> I'm trying to access the current instance of ScreenShot related to the
> current instance of WebProject, in order to get the slug field of
> WebProject to use as a upload directory but I don't think I can
> because there's no primary key in the db yet. I need to call
> change_upload_to when the instance of WebProject tries to save because
> it saves before the instance of ScreenShot i.e., before slug is
> obtained to append to the upload_to directory. Are you suggesting I
> should just add the ImageField to the WebProject class? I don't want
> to have a fixed number of ImageFields for WebProject, if there's a way
> to do that without using another class that would work. Can I access
> the save method of ScreenShot from WebProject? Should I just add
> another slug field to ScreenShot?
>
> class ScreenShotInline(admin.StackedInline):
>         model = ScreenShot
>         extra = 3
>
> class WebProjectAdmin(admin.ModelAdmin):
>         prepopulated_fields = {'slug': ('title',)}
>         inlines = [ScreenShotInline]
>
> On Nov 25, 9:46 am, Preston Holmes  wrote:
>
>
>
> > I'm a bit confused on a few points here.  The upload_to field
> > attribute should be atomic to the imagefield - it doesn't rely on
> > related models.
>
> > your change_upload_to creates a new screenshot - but doesn't connect
> > it to the current WebProject instance.  Is that what you are trying to
> > do?
>
> > s = ScreenShot(project=instance)
>
> > Is there a reason your WebProject is not defined when you create a
> > screenshot in your view?
>
> > Something about this seems like it is making it more complicated than
> > it needs to be. but details are lacking t
>
> > -Preston
>
> > On Nov 24, 5:52 pm, neridaj  wrote:
>
> > > Hello,
>
> > > I'm trying to change the upload_to attribute of an ImageField so that
> > > it is in the format "web_projects/year/slug/". The problem I am having
> > > is that the ForeignKey model is getting saved before the related
> > > ScreenShot model is able to call it's save method to change upload_to.
> > > I'm trying to use a pre_save signal to reverse the order of saving but
> > > I'm not sure how to access the current instance of the ScreenShot
> > > model to call it's save method. Thanks for any suggestions.
>
> > > class ScreenShot(models.Model):
> > >         project = models.ForeignKey(WebProject)
> > >         image = models.ImageField(upload_to="web_projects/%Y/")
> > >         page_title = models.CharField(max_length=250, help_text="Maximum 
> > > 250
> > > characters.")
>
> > >         def __unicode__(self):
> > >                 return self.page_title
>
> > >         def save(self):
> > >                 self.image.upload_to="web_projects/%Y/"+self.project.slug
> > >                 super(ScreenShot, self).save()
>
> > > def change_upload_to(sender, **kwargs):
> > >         s = ScreenShot() # not sure how to access current instance
> > >         s.save()
>
> > > pre_save.connect(change_upload_to, sender=WebProject)

--

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: middleware to log request/response objects for testing purposes?

2009-11-25 Thread Tim Valenta
http://code.google.com/p/django-logging/

*shrug*  I haven't used it, but he's got a screen-cast about how the
thing is set up.  He builds it off of built-in Python logging
modules.  It looks like it provides some decorators for suppressing
logging output on methods, etc.  Might be worth the time to figure it
out!  I'm considering it myself, now that I've looked at it!

Tim

On Nov 25, 1:52 pm, Sean Neilan  wrote:
> Dear Django Community,
>
> I am curious if anyone has built some middleware to log all request/
> response objects & possibly view & exception calls. I could do this
> myself easily, but, I would like to not reinvent the wheel.
>
> Thank you for your time.
>
> -Sean Neilan

--

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: Is it possible to 'order' the left side of a filter_horizontal?

2009-11-25 Thread Tim Valenta
Well, you've got a couple of options.  One is easiest and most
straightforward, but could impact performance.  The second is a little
bit more work, but would limit the ordering to only taking effect on
that one form.

The first way is to use the Meta option `ordering = ('fieldname',)`,
as described here:
http://docs.djangoproject.com/en/dev/ref/models/options/#ordering

Bare in mind that this will passively affect ALL queries you do to
that model's objects, unless you specifically tell it not to order
during the query.  If you think that you'll *always* want that sort
order to take effect, then this is the preferred method of
accomplishing that.

The second way is to intercept the form's queryset powering the
widget.  If you're not using Form objects with your admin (ie, you're
just specifying 'fields' or 'fieldsets' on your ModelAdmin), then
you'll have to take a quick sidequest:

Create a class somewhere (preferably in your app's directory, in a
"forms.py" file or something obvious) like so:

from django import forms
from models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
self.fields['myfieldname'].queryset =
MyModel.objects.order_by('custom_sort_field_name')

And then back in your ModelAdmin, add this attribute to the class:

# ...
from forms import MyModelForm
form = MyModelForm

This will cause the admin to use *your* form instead of the default.
What I've done is created a form which simply hijacks the queryset on
'myfieldname' (the field you're trying to sort), and alters it before
the widget has a chance to render itself.


Both methods are effective, but be sure to consider my initial
statement, about performance impact.  Pick the method that strikes the
balance in your mind between performance and practicality.

Hope that helps!

On Nov 25, 1:06 pm, rc  wrote:
> I have configured a modeladmin which uses the filter_horizontal
> feature. I would like to be able to order left side of this feature by
> name instead of the default (which I believe is by id). Is this
> possible? I see how to use "ordering" in the display for change lists,
> but not sure how to apply that to the 'left' side data of the
> filter_horizontal.

--

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: cannot import name settings - accessing Django environment from external script

2009-11-25 Thread Tim Valenta
Hah.. wow.  I'm glad you figured that out.  I haven't used pth files
in any serious manner before, so I totally wasn't thinking about that.

Best of luck to you!

On Nov 25, 1:08 pm, Stodge <sto...@gmail.com> wrote:
> What do you know - it's my .pth file. My Mercurial hook is in /home/
> mike/hooks and I have a path file /usr/lib64/python2.5/site-packages/
> hooks.pth defined, which contains:
>
> /home/mike/hooks
>
> If I comment this line out, I can do ./manage.py shell. If I uncomment
> this line, manage.py doesn't work
>
> Thanks for your help.
>
> On Nov 25, 3:04 pm, Stodge <sto...@gmail.com> wrote:
>
>
>
> > I can successfully start python and import the settings file. My
> > settings file only imports os.
>
> > On Nov 25, 3:01 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
> > > Well, does it have errors?  If you navigate to the directory where
> > > it's kept, can you enter the python shell and do "import settings"?
> > > Given all of the trouble you're having, can you verify that it imports
> > > successfully?  The settings module itself should have no immediate
> > > dependencies, unless you've placed a bunch of extra stuff in it.
>
> > > On Nov 25, 12:53 pm, Stodge <sto...@gmail.com> wrote:
>
> > > > It fails even if I delete the hg and .hg directories now. It worked a
> > > > few times before, but no longer. Odd.
>
> > > > > /usr/lib/python2.5/site-packages/django/core/management/base.py(194)run_fro
> > > > >  m_argv()
>
> > > > -> handle_default_options(options)
> > > > (Pdb) print options
> > > > {'pythonpath': None, 'verbosity': '1', 'traceback': None, 'plain':
> > > > None, 'settings': None}
> > > > (Pdb) n> 
> > > > /usr/lib/python2.5/site-packages/django/core/management/base.py(195)run_fro
> > > >  m_argv()
>
> > > > -> self.execute(*args, **options.__dict__)
> > > > (Pdb) print args
> > > > []
> > > > (Pdb) print options.__dict__
> > > > {'pythonpath': None, 'verbosity': '1', 'traceback': None, 'plain':
> > > > None, 'settings': None}
> > > > (Pdb) n
> > > > Error: Could not import settings 'indigo.settings' (Is it on sys.path?
> > > > Does it have syntax errors?): No module named settings
> > > > SystemExit: 1> 
> > > > /usr/lib/python2.5/site-packages/django/core/management/base.py(195)run_fro
> > > >  m_argv()
>
> > > > -> self.execute(*args, **options.__dict__)
>
> > > > ./manage.py shell --settings=/var/www/sites/indigo/settings.py
> > > > Error: Could not import settings '/var/www/sites/indigo/
> > > > settings.py' (Is it on sys.path? Does it have syntax errors?): No
> > > > module named /var/www/sites/indigo/settings.py
>
> > > > On Nov 25, 2:37 pm, Bill Freeman <ke1g...@gmail.com> wrote:
>
> > > > > Interesting.
>
> > > > > I take it that hg and hg/hooks both have __init__.py files?  Otherwise
> > > > > I'm not sure how django sees them.  Unless hg is also an app, listed
> > > > > in installed apps and has a models.py file.  That is, I don't believe 
> > > > > that
> > > > > the name 'hg' has any special meaning to django.
>
> > > > > You might try sticking "import pdb;pdb.set_trace()" in the beginning 
> > > > > of
> > > > > settings.py to see if it is at least trying to be imported.  If the 
> > > > > breakpoint
> > > > > is hit, you could "n" your way through the file to see if something is
> > > > > getting an exception that prevents the import from succeeding, then
> > > > > back up by moving the set_trace() to just before the failing item, 
> > > > > restart,
> > > > > and "s" your way into the failing item to see how it manages to depend
> > > > > on the presence of an "hg" directory.
>
> > > > > On Wed, Nov 25, 2009 at 2:18 PM, Stodge <sto...@gmail.com> wrote:
> > > > > > I think I have it. I'm developing a Mercurial hook in 
> > > > > > /var/www/sites/
> > > > > > project/hg/hooks. If I delete this directory it works. If I recreate
> > > > > > the directory and the hook, it fails. Guess Django is getting 
> > > > > > confused
> > > > > > by its existence.
>
> > > > > > On Nov 25,

Re: More media collection nightmares

2009-11-25 Thread Tim Valenta
It looks to me like the Media class managing the files stores JS files
in a Python list, so order should be remembered.  I can see the issue
though if a *widget* has critical "core" media, which isn't rendered
until after other bits of media already went out the hatch.

Is it a widget that has the "core.js"?  I'd suggest putting that on
the form instead, if that's the case.  Alternatively, if the page
should always have this JS anyway, you could always insert it directly
to the template, to avoid any ambiguity for any future eyeballs
wondering how it all works.

On Nov 25, 12:43 pm, Todd Blanchard  wrote:
> The latest is that the media collection strategy apparently has no concept of 
> order dependence when specifying or loading javascript and in my form it 
> seems to be sticking core.js somewhere in the middle which contains addEvent 
> which is required by something being loaded sooner and thus it results in 
> failure.
>
> Is there some way to specify order dependency in js files using this 
> mechanism? Otherwise I think it is worthless.
>
> -Todd Blanchard

--

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: cannot import name settings - accessing Django environment from external script

2009-11-25 Thread Tim Valenta
Well, does it have errors?  If you navigate to the directory where
it's kept, can you enter the python shell and do "import settings"?
Given all of the trouble you're having, can you verify that it imports
successfully?  The settings module itself should have no immediate
dependencies, unless you've placed a bunch of extra stuff in it.

On Nov 25, 12:53 pm, Stodge  wrote:
> It fails even if I delete the hg and .hg directories now. It worked a
> few times before, but no longer. Odd.
>
> > /usr/lib/python2.5/site-packages/django/core/management/base.py(194)run_fro 
> > m_argv()
>
> -> handle_default_options(options)
> (Pdb) print options
> {'pythonpath': None, 'verbosity': '1', 'traceback': None, 'plain':
> None, 'settings': None}
> (Pdb) n> 
> /usr/lib/python2.5/site-packages/django/core/management/base.py(195)run_fro 
> m_argv()
>
> -> self.execute(*args, **options.__dict__)
> (Pdb) print args
> []
> (Pdb) print options.__dict__
> {'pythonpath': None, 'verbosity': '1', 'traceback': None, 'plain':
> None, 'settings': None}
> (Pdb) n
> Error: Could not import settings 'indigo.settings' (Is it on sys.path?
> Does it have syntax errors?): No module named settings
> SystemExit: 1> 
> /usr/lib/python2.5/site-packages/django/core/management/base.py(195)run_fro 
> m_argv()
>
> -> self.execute(*args, **options.__dict__)
>
> ./manage.py shell --settings=/var/www/sites/indigo/settings.py
> Error: Could not import settings '/var/www/sites/indigo/
> settings.py' (Is it on sys.path? Does it have syntax errors?): No
> module named /var/www/sites/indigo/settings.py
>
> On Nov 25, 2:37 pm, Bill Freeman  wrote:
>
>
>
> > Interesting.
>
> > I take it that hg and hg/hooks both have __init__.py files?  Otherwise
> > I'm not sure how django sees them.  Unless hg is also an app, listed
> > in installed apps and has a models.py file.  That is, I don't believe that
> > the name 'hg' has any special meaning to django.
>
> > You might try sticking "import pdb;pdb.set_trace()" in the beginning of
> > settings.py to see if it is at least trying to be imported.  If the 
> > breakpoint
> > is hit, you could "n" your way through the file to see if something is
> > getting an exception that prevents the import from succeeding, then
> > back up by moving the set_trace() to just before the failing item, restart,
> > and "s" your way into the failing item to see how it manages to depend
> > on the presence of an "hg" directory.
>
> > On Wed, Nov 25, 2009 at 2:18 PM, Stodge  wrote:
> > > I think I have it. I'm developing a Mercurial hook in /var/www/sites/
> > > project/hg/hooks. If I delete this directory it works. If I recreate
> > > the directory and the hook, it fails. Guess Django is getting confused
> > > by its existence.
>
> > > On Nov 25, 12:56 pm, Bill Freeman  wrote:
> > >> Does /var/www/sites/project/__init__.py exist?
>
> > >> Are the files and directories readable, and the directories searchable
> > >> (excutable)
> > >> by the user as which the webserver runs?
>
> > >> On Wed, Nov 25, 2009 at 12:21 PM, Stodge  wrote:
> > >> > If I break the code out and write a simple python script that only
> > >> > contains:
>
> > >> > import sys, os
> > >> > sys.path.append("/var/www/sites")
> > >> > from project import settings
> > >> > from django.core.management import setup_environ
> > >> > setup_environ(settings)
>
> > >> > Even this doesn't work yet as far as I can tell, it should. 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-us...@googlegroups.com.
> > >> > To unsubscribe from this group, send email to 
> > >> > django-users+unsubscr...@googlegroups.com.
> > >> > For more options, visit this group 
> > >> > athttp://groups.google.com/group/django-users?hl=en.
>
> > > --
>
> > > You received this message because you are subscribed to the Google Groups 
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to 
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group 
> > > athttp://groups.google.com/group/django-users?hl=en.

--

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




Re: applying a patch

2009-11-25 Thread Tim Valenta
It's meant to be done through an SVN checkout, since that's the format
that the Django development repository is kept.

If you haven't got SVN, I'd start there.  If you're on Windows, the
"nicest" solution is "tortoisesvn", which integrates pretty simply
into the Windows shell for easy right-click controls.  If you've got
some form of Unix, then you'll have to decide if you've already got
the commandline client program.

If you've got SVN under your belt, then you're pretty much already
almost there.  If you're using the command line, you'll have to
navigate to your repository, and then use:

patch -p0 < /path/to/patch.diff

If you're using that Windows "TortoiseSVN", you can right-click the
repository folder, and use the menus to find the "Apply patch"
command.  Just locate it and it should be done.

There are some complications with command line patching where file
renames are involved.  Hopefully your patch is pretty simple.  There's
quite a bit of info in the blog circles about this stuff, so you can
find more specifics by searching online.

Tim

On Nov 25, 12:12 pm, paulh  wrote:
> I am interested in applying patch 7028, but I don't know what to apply
> it to.
> Any help would be appreciated.
>
> Paul Hide

--

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: Sick of defining urls

2009-11-25 Thread Tim Valenta
I usually don't find myself writing too many redundant views, since
the built-in admin site does so much of that automatically.  Then I
just build views specific to the site's public UI.  I still find it
curious that you would find yourself recreating said urls.  I run a
company database through the admin and three urls and three views.
There should only have to be one url pattern defined per model, plus
any extra views for looking at that one model.  I don't mean to
belittle what it is you're doing, but I can't say that I can identify
very well.  How many of your models have exactly the same set of
views?  My tendency is to think that those should be caught through
some keyword captures.

There are, however, generic views (http://docs.djangoproject.com/en/
dev/ref/generic-views/) which might help.  You might look at it and
not think that it is as easy to use as you might like, but they are
quite good for automatically handling dates in URLs, etc.

I can't explain too much about generic views, as I haven't had to use
them much.  I'm totally not an authority on that end.

If they don't really work out, you could always write a url which
captures each of those three things as keyword arguments:

urlpatterns = patterns('',
(r'^(?P[^/]+)/(?P[^/]+)/(?P\d+)/',
'magic_view_handler'),
)

"magic_view_handler" would then be a view that gets called, whose
signature looks something like:

magic_view_handler(request, app, view, id):
view_function = None
try:
view_function = import('%s.%s' % (app, view))
except ImportError:
raise Http404
view_function(request, id)

It'd then be up to your *real* view to check to ensure that the id is
legit.

I forget precise syntax on that import() function.  I don't use it
often.  The idea is to import a dynamic module based on some string
you've got handy.

I think that the reason why this latter suggestion doesn't have a
reason to exist is because you've always got to validate all sorts of
stuff very specific to the model.  By making one generic view, you're
bound to never really allowing yourself any custom processing.  You'd
always be passing your variably-defined model to the same template.
How could the same template render entirely different models to the
page?

Anyway, "sticky" the word for it, at best.  I'm totally curious, so
could I ask that you give an example of your url conf?  If feels like
there might be something missing that could simplify your task.

Tim

On Nov 25, 12:07 pm, Todd Blanchard  wrote:
> It is mostly a waste of time and busy work.
>
> I like the rails strategy of /controller/action/id
>
> I'd like to define a similar one time couple rules in urls.py
>
> Something like /application/view/id where view is the name of the function in 
> the views.py in that application.
>
> Anybody got a little snippet or recipe to do this generically once and for 
> all?
>
> -Todd Blanchard

--

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




Re: Form foreign key add new

2009-11-25 Thread Tim Valenta
> I don't know what to replace XXX with, I know it's a db_field
>  but I don't
> know how/where to get it from.

AutoFields are the auto-incrementing primary key of your model.  By
default, your models get an automatic "id" attribute, which is what
this is.  Django frequently deals with the raw database objects,
instead of their values.

I've never tried to do what you're trying to accomplish, so I'm not
sure that I have much else to suggest.

Tim

On Nov 25, 9:25 am, cerberos  wrote:
> I want the same add new functionality as model foreign key select
> boxes in admin, there the select widget is passed through
> django.contrib.admin.widgets.RelatedFieldWidgetWrapper to add the
> additional html (image, links etc).
>
> The __init__.py takes the admin_site instance, I want this
> functionality for my site, not admin area so I'm trying to extend the
> class and override the init method so admin_site is not required.
>
> from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
>
> class MyRelatedFieldWidgetWrapper(RelatedFieldWidgetWrapper):
>     """
>     This class is a wrapper to a given widget to add the add icon.
>     """
>     def __init__(self, widget, rel):
>         self.is_hidden = widget.is_hidden
>         self.needs_multipart_form = widget.needs_multipart_form
>         self.attrs = widget.attrs
>         self.choices = widget.choices
>         self.widget = widget
>         self.rel = rel
>
> And here's how I'm using it
>
> class DDCForm(forms.ModelForm):
>     """
>     Enables a form to be created from the model
>     """
>     location = forms.ModelChoiceField(Location.objects.all(), >>>
> widget=widgets.MyRelatedFieldWidgetWrapper(forms.Select(),XXX))
>
>     class Meta:
>         model = DDC
>
> I don't know what to replace XXX with, I know it's a db_field
>  but I don't
> know how/where to get it from.

--

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: string-based fields and null

2009-11-25 Thread Tim Valenta
In most cases, any string field should be allowed to be blank, and can
easily survive WITHOUT "null=True".  As stated before me, this is
preferable.  For instance, you asked about FileField, among others.
This is perfectly fine to only use "blank=True".

You'll primarily only be using "null=True" on fields that cannot
actually be blank in the database.  A Date/DateTime field, for
instance.  an empty string isn't a valid value in MySQL, therefore you
must also use "null=True", to achieve the blank effect.  The same goes
for a BooleanField in Django.  Again, a blank string isn't a valid
boolean value, so null=True is required.

In short, always try to make "blank=True" work out, and only pair it
up with "null=True" when you're dealing with database fields that
actually cannot legally have a blank string as a value.

Tim

On Nov 25, 8:58 am, Bill Freeman  wrote:
> The major problem that I see with NULL in strings is that there may be 
> databases
> out there that don't distinguish between NULL and "", that is that store them
> the same way.
>
> "" is just as good in most cases.  It behaves like False in python and
> template tag
> tests.  And it has the advantage that if you go ahead and apply a
> string operation
> to it without checking first, it won't raise an exception because the
> operation isn't
> applicable to the None object.  You can't test for it by using ISNULL
> in SQL, but
> unless NULL has a different meaning for you than "empty", who cares?
>
> There are certainly cases where you might, for example, want to
> distinguish between
> "never been set" or "is unset", and "displays as no characters", and you could
> encode the former states as NULL.  But you could also use a separate boolean.
> Think about which code is going to be easier to maintain, especially
> if by someone
> else when they don't have you to talk to.  If this table will have
> billions of rows, then
> it might be worth thinking about the memory consumed for that boolean,
>   But then
> in an year and a half, hard drives will be twice as big.
>
> Still, python (and lisp and C) programmers are used to thinking about
> the possibility
> of None (or nil or (void *)0), so experienced programmers may have an easy 
> time
> with maintenance or a NULL flag design.
>
> So, it's not a hard and fast rule.  I still think that inconsistent
> backend support is the
> major factor.
>
> Bill
>
>
>
> On Tue, Nov 24, 2009 at 1:08 AM, chefsmart  wrote:
> > The Django docs suggest "Avoid using null on string-based fields such
> > as CharField and TextField unless you have an excellent reason."
>
> > ImageField, EmailField, FileField, FilePathField, IPAddressField,
> > SlugField, URLField, XMLField are also a string-based fields at the db
> > level, so am I right in assuming that null=True is best avoided in
> > these case also, "unless you have an excellent reason."?
>
> > I am hoping Django has code to deal with the empty string value in
> > these fields. For example, I am hoping that Django understands that an
> > empty string in an ImageField means there is no corresponding image.
>
> > --
>
> > 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 
> > athttp://groups.google.com/group/django-users?hl=en.

--

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




Re: reversing URLs

2009-11-25 Thread Tim Valenta
I thank you, Karen, for the pointer on that user-issue I had :)

For the sake of putting this information on the same thread, I wanted
to make note of the following:

I had not realized that models.permalink depends on the `sites`
application.  I had removed this for the sake of simplifying the admin
options as much as possible for those who would use it.  But, having
removed that app a long time ago, I now get a different exception.

'servicetrac.django_site' doesn't exist

A patch to the docs on permalink might be worthwhile, to point out
simply that this dependency.  ... or... is it a "reverse" method
dependency?  Given my confusion over how to use it in the past, I've
never really checked specifically to see if `sites` was required for
reversing to begin with.  Either way, I'm not seeing docs which state
this.

I'll correct the issue, now that I'm on the right track, but is there
anything else that you could add about the dependency I've noted?

Thanks,

Tim

On Nov 24, 10:39 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> Holy cow you're right.  That was an extreme case of needing another pair of
> eyes.  I thought I had tested the view after using that syntax, but I must
> not have tested the right scenario.
>
> Many thanks. I will check it out in the morning :)
>
> Tim
>
> Sent from my iPod; pardon any typos and poor grammar!
>
> On Nov 24, 2009, at 10:33 PM, Karen Tracey <kmtra...@gmail.com> wrote:
>
> On Tue, Nov 24, 2009 at 11:20 PM, Tim Valenta 
> <tonightslasts...@gmail.com>wrote:
>
>
>
>
>
> > Thanks for the reply.  Yes, I can give a bit more info on it.
>
> > So, for starters, my (abbreviated) main url conf looks like this:
>
> >    urlpatterns = patterns('',
> >        (r'^surveys/', include('servicetrac.surveys.urls')),
> >    )
>
> > ... which links over to the app's urls:
>
> >    urlpatterns = patterns('servicetrac.surveys.views',
> >        (r'^(?P[^/]+)/(?P\d+)/web/take/(?
> > P\d+)', 'take_survey', {
> >            'name': 'this_is_a_name',
> >        }),
>
> From what you have below it sounds like you are intending to name this url
> pattern 'this_is_a_name'.  But that is not what you have done here --
> rather, you are passing an additional keyword parameter, name, with value
> 'this_is_a_name', to your take_survey view.  (Which is going to cause an
> error an any use of this pattern, since your view isn't expecting that
> keyword parameter.)
>
> To name this pattern, you would either do:
>
>       (r'^(?P[^/]+)/(?P\d+)/web/take/(?P\d+)',
> 'take_survey', {}, 'this_is_a_name'),
>
> That is, specify the name as the 4th item in the tuple -- you must include
> an empty optional dictionary as the 3rd item since there is no way to
> specify a 4th item without a 3rd using the tuple format.  Or use the url
> function, and specify the name keyword argument to it:
>
> url(r'^(?P[^/]+)/(?P\d+)/web/take/(?P\d+)',
> 'take_survey'. name='this_is_a_name'),
>
>
>
>
>
> >        (r'^(?P[^/]+)/(?P\d+)/web/take',
> > 'take_survey', {'page': 1}),
> >    )
>
> > And the "take_survey" view signature:
>
> >    take_survey(request, company_slug, event_id, page=1)
>
> > The default parameter for 'page' is a little redundant to what the
> > urls define, but it's self-documenting, in my mind.
>
> > So, up to this point, everything works as expected.  Absolutely no
> > problems.  The view works great, tested under both of the possible
> > urls to get there.  But of course, I wanted to partake of the niceness
> > of having a "View on site ->" link on the admin page for the object,
> > so I began to implement the "get_absolute_url" method, employing the
> > decorator "models.permalink", as described previously:
>
> >    # in my "Event" model
> >   �...@models.permalink
> >    def get_absolute_url(self):
> >        return ('this_is_a_name', (), {
> >            'company_slug': self.company.slug
> >            'event_id': self.id
> >            'page': 1
> >        })
>
> Once you get the naming working, I'd expect this to work,assuming you have
> commas on the end of a couple of those lines.  Alternatively, don't use the
> name but rather specify 'servicetrac.surveys.views.take_survey' -- that is
> the full name, including prefix from the patterns() call.
>
> Karen
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

--

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




Re: settings.py seems to be cached or stuck

2009-11-25 Thread Tim Valenta
> Thanks Karen. Is annoying sometimes when you see people don't bother
> reading past the single mod_wsgi page on Django site even though I put
> disclaimers at front to try and encourage people to do so without
> making it too blatant that what I wanted to say was 'STOP BEING LAZY
> AND GO READ THE REAL MOD_WSGI DOCUMENTATION'. ;-)

Since that had stemmed from what I had initially said, I'd briefly
defend the position I had taken, since my personal preference is to
not run my ever-changing development code on a production web server.
I've read that blog post Karen linked to a long time ago, but I
clearly forgot about it, given that I have never required my
production server to reload development files.

I've read the docs.  I just forgot about this capability.  I'm not
lazy :)  Just busy.  Apologies to the original thread-starter for my
inaccurate conclusion.

Tim

On Nov 24, 10:55 pm, Graham Dumpleton <graham.dumple...@gmail.com>
wrote:
> On Nov 25, 3:58 pm, Karen Tracey <kmtra...@gmail.com> wrote:
>
>
>
>
>
> > On Tue, Nov 24, 2009 at 11:32 PM, Tim Valenta 
> > <tonightslasts...@gmail.com>wrote:
>
> > > Yeah, production servers aren't really very friendly to changes.
> > > Languages like PHP are specifically built to circumvent such woes.
> > > You would have to actually bounce apache in order to get the changes
> > > to take.
>
> > > This is why the development server is so nice, because when you alter
> > > certain files that it watches, it actually restarts automatically for
> > > you.  There's not really going to be a solution for this problem,
> > > since this is inherent to production-class web servers, where PHP and
> > > general CGI is the exception.
>
> > > Hope that's not a big problem!
>
> > > I still liked to run a production server version of my project, so I
> > > made a local SVN repository which I would commit changes to.  I
> > > checked out a copy of the repository to where my production server
> > > wanted to see it, and then put up a clumsy cron job would
> > > automatically update the production machine's repository each day, and
> > > bounce Apache for me.
>
> > > That's about as close as it'll get, I think :P
>
> > You don't give details on what your production environment is so I don't
> > know if you can get closer there, but with mod_wsgi you can get closer.
>
> > With mod_wsgi in daemon mode just touching the wsgi script file will result
> > in a reload on the next request.  You can even set things up so that it
> > reloads automatically on source code changes.  Graham Dumpleton sets outs
> > all the details in a blog entry here:
>
> >http://blog.dscpl.com.au/2008/12/using-modwsgi-when-developing-django...
>
> Thanks Karen. Is annoying sometimes when you see people don't bother
> reading past the single mod_wsgi page on Django site even though I put
> disclaimers at front to try and encourage people to do so without
> making it too blatant that what I wanted to say was 'STOP BEING LAZY
> AND GO READ THE REAL MOD_WSGI DOCUMENTATION'. ;-)
>
> 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-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: calendar.js can't find variable gettext

2009-11-25 Thread Tim Valenta


On Nov 24, 10:32 pm, Todd Blanchard  wrote:
> Yep, I solved this by ripping and copying some code out of admin/sites.py
> and adding a url conf for it.
>
> It works now, but this should be included by default through the widget media 
> dependency system.  Not very slick.  I tried filing a bug and the submission 
> was rejected as spam.

I'd just sign up for the account.  It's pretty simple.  Filing bugs is
how this thing gets better-- I'd urge you not to just let it drop.

Glad that that worked out for you.  I learned something about it,
myself.  It had never struck me that it was a view :)

Tim

>
> -Todd Blanchard
>
> On Nov 24, 2009, at 8:42 PM, Karen Tracey wrote:
>
>
>
> > On Tue, Nov 24, 2009 at 8:56 PM, Todd Blanchard  wrote:
> > I'm trying to use the date/time entry widgets from admin and I get this 
> > javascript error and the controls don't render.
>
> > Where is this supposed to come from?
>
> > In annoyance, I have copied the head section precisely from an admin page 
> > that work.  Still doesn't work in my page.
>
> >     
> >     
> >     
>
> >     
>
> > This is the one gettext would be coming from and I'm guessing the relative 
> > path here is causing a problem.  (gettext is internationalization support, 
> > and jsi18n is javascript internationalization support, I'd guess)  jsi18n 
> > is an admin view:
>
> >http://code.djangoproject.com/browser/django/tags/releases/1.1.1/djan...
> >http://code.djangoproject.com/browser/django/tags/releases/1.1.1/djan...
>
> > It is not being pulled in via a form media definition but rather looks to 
> > be hardcoded into the templates that depend on it, for example:
>
> >http://code.djangoproject.com/browser/django/tags/releases/1.1.1/djan...
>
> > It seems using the admin widgets that use the i18n javascript is a bit more 
> > involved than just importing them and using them.  Maybe there is some 
> > elegant way you're supposed to pull in this javascript, but I don't know it 
> > (I don't know much when it comes to javascript).
>
> > Karen
>
> > --
>
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.

--

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




Re: reversing URLs

2009-11-24 Thread Tim Valenta
Holy cow you're right.  That was an extreme case of needing another pair of
eyes.  I thought I had tested the view after using that syntax, but I must
not have tested the right scenario.

Many thanks. I will check it out in the morning :)

Tim

Sent from my iPod; pardon any typos and poor grammar!

On Nov 24, 2009, at 10:33 PM, Karen Tracey <kmtra...@gmail.com> wrote:

On Tue, Nov 24, 2009 at 11:20 PM, Tim Valenta <tonightslasts...@gmail.com>wrote:

> Thanks for the reply.  Yes, I can give a bit more info on it.
>
> So, for starters, my (abbreviated) main url conf looks like this:
>
>urlpatterns = patterns('',
>(r'^surveys/', include('servicetrac.surveys.urls')),
>)
>
> ... which links over to the app's urls:
>
>urlpatterns = patterns('servicetrac.surveys.views',
>(r'^(?P[^/]+)/(?P\d+)/web/take/(?
> P\d+)', 'take_survey', {
>'name': 'this_is_a_name',
>}),
>

>From what you have below it sounds like you are intending to name this url
pattern 'this_is_a_name'.  But that is not what you have done here --
rather, you are passing an additional keyword parameter, name, with value
'this_is_a_name', to your take_survey view.  (Which is going to cause an
error an any use of this pattern, since your view isn't expecting that
keyword parameter.)

To name this pattern, you would either do:

  (r'^(?P[^/]+)/(?P\d+)/web/take/(?P\d+)',
'take_survey', {}, 'this_is_a_name'),

That is, specify the name as the 4th item in the tuple -- you must include
an empty optional dictionary as the 3rd item since there is no way to
specify a 4th item without a 3rd using the tuple format.  Or use the url
function, and specify the name keyword argument to it:


url(r'^(?P[^/]+)/(?P\d+)/web/take/(?P\d+)',
'take_survey'. name='this_is_a_name'),



>(r'^(?P[^/]+)/(?P\d+)/web/take',
> 'take_survey', {'page': 1}),
>)
>
> And the "take_survey" view signature:
>
>take_survey(request, company_slug, event_id, page=1)
>
> The default parameter for 'page' is a little redundant to what the
> urls define, but it's self-documenting, in my mind.
>
> So, up to this point, everything works as expected.  Absolutely no
> problems.  The view works great, tested under both of the possible
> urls to get there.  But of course, I wanted to partake of the niceness
> of having a "View on site ->" link on the admin page for the object,
> so I began to implement the "get_absolute_url" method, employing the
> decorator "models.permalink", as described previously:
>
># in my "Event" model
>@models.permalink
>def get_absolute_url(self):
>return ('this_is_a_name', (), {
>'company_slug': self.company.slug
>'event_id': self.id
>'page': 1
>})
>
>
>
Once you get the naming working, I'd expect this to work,assuming you have
commas on the end of a couple of those lines.  Alternatively, don't use the
name but rather specify 'servicetrac.surveys.views.take_survey' -- that is
the full name, including prefix from the patterns() call.

Karen

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

--

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: Best way to use django for sql with raw LIKE statement

2009-11-24 Thread Tim Valenta
It sounds like you've been using the right sorts of methods for that
job, but the complexity of the query is getting to be too much :)

There's a 'regex' lookup... 
http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex

That's a pretty intense example text parsing search.  I think the
usual Django philosophy might conclude that whatever you've got in
that field could be broken up into multiple fields? :)  Unless it's a
TextField, but then you might be best off with regex anyway.

I can't quite wrap my brain around the requirement for such a lookup
yet, because I've never yet come across the need for any raw SQL to go
into my queries.  Apologies if this doesn't really address the type of
solution you need.

Tim

On Nov 24, 8:50 pm, valhalla  wrote:
> Hi,
>
> I'm basically looking for the best way to implement something that
> produces SQL similar to:
>
> select col1, col2 from table1 where col1 like '%this%is%some%search
> %string?with?wildcards'
>
> I have worked around this with using the extra() method of the query
> but this can get real messy real fast.
> I have also split the string on the wild cards and chained startswith,
> endswith and contains. but the contains elements don't maintain the
> order that I would like (and sometime absolutely must have)
>
> does anyone have a neat solution to this that I have missed?

--

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: settings.py seems to be cached or stuck

2009-11-24 Thread Tim Valenta
Yeah, production servers aren't really very friendly to changes.
Languages like PHP are specifically built to circumvent such woes.
You would have to actually bounce apache in order to get the changes
to take.

This is why the development server is so nice, because when you alter
certain files that it watches, it actually restarts automatically for
you.  There's not really going to be a solution for this problem,
since this is inherent to production-class web servers, where PHP and
general CGI is the exception.

Hope that's not a big problem!

I still liked to run a production server version of my project, so I
made a local SVN repository which I would commit changes to.  I
checked out a copy of the repository to where my production server
wanted to see it, and then put up a clumsy cron job would
automatically update the production machine's repository each day, and
bounce Apache for me.

That's about as close as it'll get, I think :P

Tim

On Nov 24, 8:12 pm, Tom <t.scr...@gmail.com> wrote:
> Sorry, I should have mentioned that this has only come up after
> deploying the project to a production server using mod_wsgi.  It works
> absolutely fine under development.
>
> Tom
>
> On Nov 25, 2:24 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
>
>
> > Are you using the development server?  There's definitely caching
> > funny-business in a production web server, but that should affect you
> > if you're using "manage.py runserver"
>
> > Does stopping and starting the development server change anything?
>
> > Tim
>
> > On Nov 24, 6:54 pm, Tom <t.scr...@gmail.com> wrote:
>
> > > Hi all,
>
> > > I am experiencing TemplateDoesNotExist errors.  Initially I thought I
> > > had my TEMPLATE_DIRS variable set incorrectly, but much
> > > experimentation yielded nothing.  I then noticed that on the browser
> > > TemplateDoesNotExist error pages the TEMPLATE_DIRS setting reads as an
> > > empty tuple ().  I then tried changing several other settings in
> > > settings.py including database name and engine, and adding and
> > > removing installed apps.  None of these changes are showing up in the
> > > settings listed on error pages.
>
> > > It seems like the settings file has been cached somewhere because
> > > nothing I do to my settings.py file is making any difference.  I have
> > > even tried deleting the file altogether and still nothing changes.  I
> > > have also tried recreating my project from scratch, but still no joy.
>
> > > This is really weird; does anybody have any ideas what is going on?
>
> > > Thanks in advance,
>
> > > Tom

--

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




Re: reversing URLs

2009-11-24 Thread Tim Valenta
Thanks for the reply.  Yes, I can give a bit more info on it.

So, for starters, my (abbreviated) main url conf looks like this:

urlpatterns = patterns('',
(r'^surveys/', include('servicetrac.surveys.urls')),
)

... which links over to the app's urls:

urlpatterns = patterns('servicetrac.surveys.views',
(r'^(?P[^/]+)/(?P\d+)/web/take/(?
P\d+)', 'take_survey', {
'name': 'this_is_a_name',
}),
(r'^(?P[^/]+)/(?P\d+)/web/take',
'take_survey', {'page': 1}),
)

And the "take_survey" view signature:

take_survey(request, company_slug, event_id, page=1)

The default parameter for 'page' is a little redundant to what the
urls define, but it's self-documenting, in my mind.

So, up to this point, everything works as expected.  Absolutely no
problems.  The view works great, tested under both of the possible
urls to get there.  But of course, I wanted to partake of the niceness
of having a "View on site ->" link on the admin page for the object,
so I began to implement the "get_absolute_url" method, employing the
decorator "models.permalink", as described previously:

# in my "Event" model
@models.permalink
def get_absolute_url(self):
return ('this_is_a_name', (), {
'company_slug': self.company.slug
'event_id': self.id
'page': 1
})


Now, my case doesn't seem too abnormal, but I find it difficult to
even track what happens after this.  Using my wishful "View on site"
link yields the same result as calling the method in the manage.py
shell:

>>> event.get_aboslute_url()
Traceback (most recent call last):
 snip...
NoReverseMatch: Reverse for 'this_is_a_name' with arguments '()' and
keyword arguments '{'event_id': 1L, 'company_slug': u'mycompany',
'page': 1}' not found.



Now, I've tried to simplify my task as much as possible, by naming the
view and everything.  I thought maybe some funny-business was going on
with the optional parameter, but changes don't seem to make any
difference.

Any thoughts?  I'm pretty sure there's no more info to give... the
full traceback stays in Django files, never directly touching my own,
and doesn't reveal anything more than I've posted.

Thanks,

Tim

On Nov 24, 8:52 pm, Karen Tracey <kmtra...@gmail.com> wrote:
> On Tue, Nov 24, 2009 at 4:49 PM, Tim Valenta 
> <tonightslasts...@gmail.com>wrote:
>
>
>
>
>
> > Ever since day one, I've never had a firm grasp on what the heck URL
> > reversing can do.  I understand the concepts involved, even the admin
> > namespacing that can occur with different admin sites, and I know that
> > the admin uses it regularly, but it seems like a crazy unpredictable
> > wildcard when I try to use it manually.
>
> > For instance, I'm trying to get the permalink decorator to work on a
> > "get_absolute_url()" method on my model, and I haven't got the
> > slightest clue what the hell it's doing.  I'm getting errors about it
> > not being able to reverse it properly when I try to click on the admin-
> > generated "View on site ->" link from the change form.  It says that
> > it can't find the view.
>
> > Basically, I've tried making the method refer to the view object, a
> > view name as a string (explicitly setting the name in the url conf),
> > an absolute module-path string ("myproject.myapp.views.my_view"), and
> > nothing works.  It can never find it, even on a view with just a
> > single required keyword argument.
>
> > Is there any amazing breakdown on how to better wrap my brain around
> > how this url reversing thing works?  I typically don't think of myself
> > as an idiot, but I really cannot even begin to feel like I can use it
> > proficiently.
>
> I could point you to the doc 
> (http://docs.djangoproject.com/en/dev/ref/models/instances/#the-permal...)
> but it sounds like you have already read that.
>
> Alternatively I could try to explain the errors you are getting for the
> various things you have tried, but there aren't enough specifics here to do
> that.  Spell out the URLConf info, exactly what you have tried for the
> permalink/ger_abosolute_url code, and exactly what the error is, and someone
> can likely help.
>
> I'm assuming you are getting NoReverseMatch and that's what you mean when
> you say "It says that it can't find the view"?  Those can be frustrating to
> debug, but they tend be right and mean exactly what they say: given the
> URLConf in place, there is no URL pattern in there that would result in the
> specified view being called with the noted parameters.  The trick then is to
> figure out why, since clearly you're expecting the URLConf to c

Re: Configure multi-field multi-select form in Django Admin

2009-11-24 Thread Tim Valenta
> The javascript will be found somewhere under django/contrib/admin/media/js.

To be clear, rc, although the javascript is of course available for
viewing, you should only need to put that attribute
"filter_horizontal" on your ModelAdmin.  There shouldn't be any need
for inserting any custom javascript commands anywhere.  That one
attribute does it all.

And... this might pose a problem, but I don't see any ManyToManyFields
in your models.  It won't work unless you're using those, instead of
ForeignKeys.

For the extra mile, you shouldn't need those various "_id =
models.AutoField(primary_key=True)" parts.  Django does that
automatically, but names each one just "id", instead of "[modelname]
_id".  Unless you specifically want them to be named differently than
"id", you don't have to specify it, which helps it be more readable.
But it's of course your own project :)  Do it however you wish!

Tim

On Nov 24, 6:01 pm, Karen Tracey  wrote:
> On Tue, Nov 24, 2009 at 12:32 PM, rc  wrote:
> > As I mentioned, the Django admin has exactly what I want with the user
> > permission form (auth_user, auth_permissions and
> > auth_user_user_permission). Does anyone know where that code is
> > located in the Django environment?
>
> That's done with javascript, activated by listing the fields in:
>
> http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contri...
>
> The javascript will be found somewhere under django/contrib/admin/media/js.
>
> Karen

--

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




Re: calendar.js can't find variable gettext

2009-11-24 Thread Tim Valenta
I'm a little unclear on part of that... does this not work only on
certain pages?  If it doesn't work at all anywhere, I'm not sure where
you got the HTML for a working page.

Are you sure that all of those URLs resolve to the right JS files?  If
you go to the page which messes up, and view the source, I'd go
through the links one at a time and try to find out which one of them
may not work.  It sounds like one of those is messing up.

Can you verify whether or not all of those links *for sure* work,
right there in the browser?

Tim

On Nov 24, 6:56 pm, Todd Blanchard  wrote:
> I'm trying to use the date/time entry widgets from admin and I get this 
> javascript error and the controls don't render.
>
> Where is this supposed to come from?
>
> In annoyance, I have copied the head section precisely from an admin page 
> that work.  Still doesn't work in my page.
>
>     
>     
>     
>
>     
>      media="all" rel="stylesheet" />
>     
>      src="/media/js/admin/RelatedObjectLookups.js">
>      src="/media/js/getElementsBySelector.js">
>     
>     
>      src="/media/js/admin/DateTimeShortcuts.js">
>      src="http://openlayers.org/api/2.8/OpenLayers.js";>
>      src="/static/olwidget/js/olwidget.js">
>      src="http://openstreetmap.org/openlayers/OpenStreetMap.js";>

--

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: settings.py seems to be cached or stuck

2009-11-24 Thread Tim Valenta
Are you using the development server?  There's definitely caching
funny-business in a production web server, but that should affect you
if you're using "manage.py runserver"

Does stopping and starting the development server change anything?

Tim

On Nov 24, 6:54 pm, Tom  wrote:
> Hi all,
>
> I am experiencing TemplateDoesNotExist errors.  Initially I thought I
> had my TEMPLATE_DIRS variable set incorrectly, but much
> experimentation yielded nothing.  I then noticed that on the browser
> TemplateDoesNotExist error pages the TEMPLATE_DIRS setting reads as an
> empty tuple ().  I then tried changing several other settings in
> settings.py including database name and engine, and adding and
> removing installed apps.  None of these changes are showing up in the
> settings listed on error pages.
>
> It seems like the settings file has been cached somewhere because
> nothing I do to my settings.py file is making any difference.  I have
> even tried deleting the file altogether and still nothing changes.  I
> have also tried recreating my project from scratch, but still no joy.
>
> This is really weird; does anybody have any ideas what is going on?
>
> Thanks in advance,
>
> Tom

--

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




Re: Accessing model instance on pre_save signal

2009-11-24 Thread Tim Valenta
I think the answer is just in the documentation on the method:

http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save

No worries though.  Signals are such a strangely uncovered topic in
the main tutorials, and aren't easy to find documentation for unless
you know what you're after.

It'll be in kwargs['instance']

Tim

On Nov 24, 6:52 pm, neridaj  wrote:
> Hello,
>
> I'm trying to change the upload_to attribute of an ImageField so that
> it is in the format "web_projects/year/slug/". The problem I am having
> is that the ForeignKey model is getting saved before the related
> ScreenShot model is able to call it's save method to change upload_to.
> I'm trying to use a pre_save signal to reverse the order of saving but
> I'm not sure how to access the current instance of the ScreenShot
> model to call it's save method. Thanks for any suggestions.
>
> class ScreenShot(models.Model):
>         project = models.ForeignKey(WebProject)
>         image = models.ImageField(upload_to="web_projects/%Y/")
>         page_title = models.CharField(max_length=250, help_text="Maximum 250
> characters.")
>
>         def __unicode__(self):
>                 return self.page_title
>
>         def save(self):
>                 self.image.upload_to="web_projects/%Y/"+self.project.slug
>                 super(ScreenShot, self).save()
>
> def change_upload_to(sender, **kwargs):
>         s = ScreenShot() # not sure how to access current instance
>         s.save()
>
> pre_save.connect(change_upload_to, sender=WebProject)

--

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: creating a drop down filter in Admin site

2009-11-24 Thread Tim Valenta
Not to my knowledge.  Condensing them into drop-downs could be an
option, though.  That might make an interesting patch.  I'm not
familiar with that part of the code, but it would honestly be more of
a template tweak than much code.

I'm busy with several projects for the time being, but it would be
interesting to look into.  I know that there's a branch called "admin-
ui" which will be replacing the current admin in March, with version
1.2.  I'm only aware of just a couple of changes, and I'm not sure
that this is one of them, but there could be something in there to
help facilitate that.

Tim

On Nov 24, 4:09 pm, Jase  wrote:
> Hoping someone could help me out. I am updating an admin site and
> added a couple "list_filter"s. They are rather long so I wanted to
> turn them into a drop down filter. Can this be done? Any suggestions?
> Thanks,
> Jase

--

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: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
Oops damn 'send' button on the iPod.

The media attribute is a python property which aggregates all widget
media. So everything is simplified to just using myform.media.

Widgets are specified on form fields, if you want to change it from
the default widget.

Sent from my iPod; pardon any typos and poor grammar!

On Nov 24, 2009, at 5:02 PM, Todd Blanchard <tblanch...@mac.com> wrote:

> Thanks, I feel like I'm making progress.
>
> Widgets define media too.  I'm really fuzzy about how widgets get
> loaded and how their media declarations get collected into the media
> object list. (I'm using contrib.gis which has nifty map widgets and
> it "just works" in the admin but now I'm building my own UI).
>
> In fact, I'm pretty fuzzy in general about how code like widgets
> gets "found" and loaded.
>
> -Todd Blanchard
>
>
> On Nov 24, 2009, at 3:52 PM, Tim Valenta wrote:
>
>> Sorry-- I got out of sync with the replies.
>>
>>> Or am I missing something.  Seems like I am getting very much NON-
>>> DRY here.
>>
>> How many pages do you have dozens of forms on?  If ever, I find that
>> I've got a single form on the page.  If you're writing an app complex
>> enough to need such amazingly complicated nested forms should you
>> use the admin, and let it do all that for you?
>>
>> We're not really working with specifics here, so I'm unsure of what
>> you're trying to accomplish.
>>
>> How would you propose we get around this problem?  You've got a
>> python
>> list of form objects.  How on earth is Django supposed to know what
>> variable you've got your forms in?  By forcing you to put all your
>> forms in a single variable, it would make Django dictate too strongly
>> "the one and only variable which can hold forms".  That exactly what
>> it's trying not to do.
>>
>> Just set up a template, perhaps "base.html".  Make it something like
>> this:
>>
>> 
>> 
>>   blah
>>   {% block my_media %}
>>   {{ media }}
>>   {% endblock %}
>> 
>> 
>>   {% content %}{% endcontent %}
>> 
>> 
>>
>>
>> Then, in your views, you'll render the actual template you want to
>> use
>> (as in, don't render "base.html", render the one that you'd normally
>> render), but make sure it extends base:
>> {# mytemplate.html #}
>> {% extends "base.html" %}
>>
>> {% block content %}
>>   my content goes here...
>>   
>>   {% for form in forms %}
>>   {{ form.as_p }}
>>   {% endfor %}
>>   
>> {% endblock %}
>>
>>
>> The idea is that the 'base.html' template will *always* try to grab
>> the context variable "media" and render it.  That means that all you
>> ever have to do is make sure that the context variable "media"
>> contains the cumulative media of what you want to include.  Note,
>> though, that when you want to use this "extends" approach, you become
>> required to work in those blocks.  that's why I put a "content" block
>> in the base template, and override it in the extended one.  Stuff
>> outside of blocks in mytemplate.html won't get displayed.  This is a
>> very common approach, though, so don't feel like you're getting
>> cheated.
>>
>> Then, if you ever want to for whatever reason add more media beyond
>> the form media, you can either slap it into the 'media' context var
>> in
>> your view, or you can do that block override I kept using the first
>> examples:
>>
>> {# mytemplate.html #}
>> {% block my_media %}
>>   {{ block.super }}
>>   
>> {% endblock %}
>>
>> {% block content %}
>>   {# continue as usual #}
>> {% endblock %}
>>
>>
>>
>> I hope I'm not spouting nonsense that you are already familiar with.
>> Feel free to ask anything more, if you've got specifics that you're
>> trying to nail down, design-wise.
>>
>> Tim
>>
>> On Nov 24, 4:36 pm, Todd Blanchard <tblanch...@mac.com> wrote:
>>> No no no, I really really appreciate the help.
>>>
>>> But I'm definitely beginning to feel like my app is 80% boilerplate.
>>>
>>> On Nov 24, 2009, at 3:35 PM, Tim Valenta wrote:
>>>
>>>
>>>
>>>> PS -- I hope I don't sound like I'm insulting your
>>>> intelligence--- I'm
>>>> not.  I've often felt like there aren't enough policies in Django,
>>>> myself.  But pick your battles.  This is an easy one.  I prefer
>>>&

Re: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
The 'media' attribute on forms are actually python proterties

Sent from my iPod; pardon any typos and poor grammar!

On Nov 24, 2009, at 5:02 PM, Todd Blanchard <tblanch...@mac.com> wrote:

> Thanks, I feel like I'm making progress.
>
> Widgets define media too.  I'm really fuzzy about how widgets get
> loaded and how their media declarations get collected into the media
> object list. (I'm using contrib.gis which has nifty map widgets and
> it "just works" in the admin but now I'm building my own UI).
>
> In fact, I'm pretty fuzzy in general about how code like widgets
> gets "found" and loaded.
>
> -Todd Blanchard
>
>
> On Nov 24, 2009, at 3:52 PM, Tim Valenta wrote:
>
>> Sorry-- I got out of sync with the replies.
>>
>>> Or am I missing something.  Seems like I am getting very much NON-
>>> DRY here.
>>
>> How many pages do you have dozens of forms on?  If ever, I find that
>> I've got a single form on the page.  If you're writing an app complex
>> enough to need such amazingly complicated nested forms should you
>> use the admin, and let it do all that for you?
>>
>> We're not really working with specifics here, so I'm unsure of what
>> you're trying to accomplish.
>>
>> How would you propose we get around this problem?  You've got a
>> python
>> list of form objects.  How on earth is Django supposed to know what
>> variable you've got your forms in?  By forcing you to put all your
>> forms in a single variable, it would make Django dictate too strongly
>> "the one and only variable which can hold forms".  That exactly what
>> it's trying not to do.
>>
>> Just set up a template, perhaps "base.html".  Make it something like
>> this:
>>
>> 
>> 
>>   blah
>>   {% block my_media %}
>>   {{ media }}
>>   {% endblock %}
>> 
>> 
>>   {% content %}{% endcontent %}
>> 
>> 
>>
>>
>> Then, in your views, you'll render the actual template you want to
>> use
>> (as in, don't render "base.html", render the one that you'd normally
>> render), but make sure it extends base:
>> {# mytemplate.html #}
>> {% extends "base.html" %}
>>
>> {% block content %}
>>   my content goes here...
>>   
>>   {% for form in forms %}
>>   {{ form.as_p }}
>>   {% endfor %}
>>   
>> {% endblock %}
>>
>>
>> The idea is that the 'base.html' template will *always* try to grab
>> the context variable "media" and render it.  That means that all you
>> ever have to do is make sure that the context variable "media"
>> contains the cumulative media of what you want to include.  Note,
>> though, that when you want to use this "extends" approach, you become
>> required to work in those blocks.  that's why I put a "content" block
>> in the base template, and override it in the extended one.  Stuff
>> outside of blocks in mytemplate.html won't get displayed.  This is a
>> very common approach, though, so don't feel like you're getting
>> cheated.
>>
>> Then, if you ever want to for whatever reason add more media beyond
>> the form media, you can either slap it into the 'media' context var
>> in
>> your view, or you can do that block override I kept using the first
>> examples:
>>
>> {# mytemplate.html #}
>> {% block my_media %}
>>   {{ block.super }}
>>   
>> {% endblock %}
>>
>> {% block content %}
>>   {# continue as usual #}
>> {% endblock %}
>>
>>
>>
>> I hope I'm not spouting nonsense that you are already familiar with.
>> Feel free to ask anything more, if you've got specifics that you're
>> trying to nail down, design-wise.
>>
>> Tim
>>
>> On Nov 24, 4:36 pm, Todd Blanchard <tblanch...@mac.com> wrote:
>>> No no no, I really really appreciate the help.
>>>
>>> But I'm definitely beginning to feel like my app is 80% boilerplate.
>>>
>>> On Nov 24, 2009, at 3:35 PM, Tim Valenta wrote:
>>>
>>>
>>>
>>>> PS -- I hope I don't sound like I'm insulting your
>>>> intelligence--- I'm
>>>> not.  I've often felt like there aren't enough policies in Django,
>>>> myself.  But pick your battles.  This is an easy one.  I prefer
>>>> Django
>>>> over Rails, when it comes down to it.  Feel fortunate that Django
>>>> has
>>>> practically the best documentation on the planet.  I hate mo

Re: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
Sorry-- I got out of sync with the replies.

> Or am I missing something.  Seems like I am getting very much NON-DRY here.

How many pages do you have dozens of forms on?  If ever, I find that
I've got a single form on the page.  If you're writing an app complex
enough to need such amazingly complicated nested forms should you
use the admin, and let it do all that for you?

We're not really working with specifics here, so I'm unsure of what
you're trying to accomplish.

How would you propose we get around this problem?  You've got a python
list of form objects.  How on earth is Django supposed to know what
variable you've got your forms in?  By forcing you to put all your
forms in a single variable, it would make Django dictate too strongly
"the one and only variable which can hold forms".  That exactly what
it's trying not to do.

Just set up a template, perhaps "base.html".  Make it something like
this:



blah
{% block my_media %}
{{ media }}
{% endblock %}


{% content %}{% endcontent %}




Then, in your views, you'll render the actual template you want to use
(as in, don't render "base.html", render the one that you'd normally
render), but make sure it extends base:
{# mytemplate.html #}
{% extends "base.html" %}

{% block content %}
my content goes here...

{% for form in forms %}
{{ form.as_p }}
{% endfor %}

{% endblock %}


The idea is that the 'base.html' template will *always* try to grab
the context variable "media" and render it.  That means that all you
ever have to do is make sure that the context variable "media"
contains the cumulative media of what you want to include.  Note,
though, that when you want to use this "extends" approach, you become
required to work in those blocks.  that's why I put a "content" block
in the base template, and override it in the extended one.  Stuff
outside of blocks in mytemplate.html won't get displayed.  This is a
very common approach, though, so don't feel like you're getting
cheated.

Then, if you ever want to for whatever reason add more media beyond
the form media, you can either slap it into the 'media' context var in
your view, or you can do that block override I kept using the first
examples:

{# mytemplate.html #}
{% block my_media %}
{{ block.super }}

{% endblock %}

{% block content %}
{# continue as usual #}
{% endblock %}



I hope I'm not spouting nonsense that you are already familiar with.
Feel free to ask anything more, if you've got specifics that you're
trying to nail down, design-wise.

Tim

On Nov 24, 4:36 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> No no no, I really really appreciate the help.
>
> But I'm definitely beginning to feel like my app is 80% boilerplate.
>
> On Nov 24, 2009, at 3:35 PM, Tim Valenta wrote:
>
>
>
> > PS -- I hope I don't sound like I'm insulting your intelligence--- I'm
> > not.  I've often felt like there aren't enough policies in Django,
> > myself.  But pick your battles.  This is an easy one.  I prefer Django
> > over Rails, when it comes down to it.  Feel fortunate that Django has
> > practically the best documentation on the planet.  I hate more open
> > source docs, because it was written by a guy who don't know how to use
> > proper english!
>
> > I'm just trying to drive home the point that this isn't the worst
> > thing that you could be stuck on.
>
> > Sincerely hoping it helps,
> > Tim
>
> > On Nov 24, 4:28 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> >> Sorry it's not working out for you, but I'd disagree about the
> >> comparison to X-Windows :)  I'd be defending Django, and not X-
> >> windows, when I say that.
>
> >> I'm serious.  Just add them together.  I'm not sure you're
> >> appreciating the slick objects that have been crafted for this very
> >> purpose.
>
> >> Your view:
> >>     cumulative_media = form.media for form in forms
> >>     return render_to_response('mytemplate.html', {'media':
> >> cumulative_media})
>
> >> Your template:
> >>     {% block my_media_block %}
> >>         {{ block.super }}
> >>         {{ media }}
> >>     {% endblock %}
>
> >> I fail to see what is so hard about this.
>
> >> Tim
>
> >> On Nov 24, 4:13 pm, Todd Blanchard <tblanch...@mac.com> wrote:
>
> >>> You know what, this is absolutely too much BS.  Why would one bother to 
> >>> use the media declaration stuff at all if there is no mechanism to 
> >>> properly consume it (a built in template tag for instance).
>
> >>> I think I will just hardcode them in the head in the base template.  The

Re: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
PS -- I hope I don't sound like I'm insulting your intelligence--- I'm
not.  I've often felt like there aren't enough policies in Django,
myself.  But pick your battles.  This is an easy one.  I prefer Django
over Rails, when it comes down to it.  Feel fortunate that Django has
practically the best documentation on the planet.  I hate more open
source docs, because it was written by a guy who don't know how to use
proper english!

I'm just trying to drive home the point that this isn't the worst
thing that you could be stuck on.

Sincerely hoping it helps,
Tim

On Nov 24, 4:28 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> Sorry it's not working out for you, but I'd disagree about the
> comparison to X-Windows :)  I'd be defending Django, and not X-
> windows, when I say that.
>
> I'm serious.  Just add them together.  I'm not sure you're
> appreciating the slick objects that have been crafted for this very
> purpose.
>
> Your view:
>     cumulative_media = form.media for form in forms
>     return render_to_response('mytemplate.html', {'media':
> cumulative_media})
>
> Your template:
>     {% block my_media_block %}
>         {{ block.super }}
>         {{ media }}
>     {% endblock %}
>
> I fail to see what is so hard about this.
>
> Tim
>
> On Nov 24, 4:13 pm, Todd Blanchard <tblanch...@mac.com> wrote:
>
>
>
> > You know what, this is absolutely too much BS.  Why would one bother to use 
> > the media declaration stuff at all if there is no mechanism to properly 
> > consume it (a built in template tag for instance).
>
> > I think I will just hardcode them in the head in the base template.  They 
> > seldom change and browser caching being what it is having them never change 
> > is just fine.
>
> > After three weeks of seriously trying to get traction with django, my 
> > conclusion is it has all of the elegance of X-windows.  It can do anything 
> > but out of the box it does nothing except present a zillion confusing parts 
> > to the programmer and it has too many mechanisms but no policies.
>
> > I'm beginning to very much pine for rails.  At least it does something out 
> > of the box.
>
> > Very frustrated today - still haven't got a single record/entry form 
> > working.  Too many little files and indirection to keep it all straight in 
> > my head.
>
> > -Todd Blanchard
>
> > On Nov 24, 2009, at 2:05 PM, Tim Valenta wrote:
>
> > > The idea is along the lines of what you initially guessed.
>
> > > The admin accomplishes the non-duplicate effect in django/django/
> > > contrib/admin/options.py, starting at line 770.  It loops over the
> > > forms and combines the existing media with the media on each form
> > > object.  It ends up using a series of objects to do it, including a
> > > Media class, but it's not doing anything too special.  When an item
> > > gets added, it checks to make sure that the path doesn't already exist
> > > in the list.
>
> > > So, short story: loop over your forms and add the media attributes
> > > together.  The underlying Media class ought to be dropping duplicates.
>
> > > Then just save a context variable with the result, and do the
> > > following in your template:
>
> > > {% block extrahead %} {# or whatever you call your header block #}
> > >    {{ block.super }}
> > >    {{ cumulative_media }}
> > > {% endblock %}
>
> > > Tim
>
> > > On Nov 24, 12:30 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> > >> What about de-duping?
> > >> If two forms want the same js file, will it get included twice?
> > >> It seems like this is the kind of thing that the framework should handle 
> > >> and the current "solution" is kind of half baked.
>
> > >> -Todd
>
> > >> On Nov 23, 2009, at 2:40 PM, Mark (Nosrednakram) wrote:
>
> > >>> Hello,
>
> > >>> I have something like the following in my generic genericform.html.  I
> > >>> think this is what you're looking for if not hope you find a better
> > >>> answer. The extramedia block is back in my base.html  template and my
> > >>> form template extends it. I'm not sure if it's in the admin base.html
> > >>> but you can take a look at if for there media blocks I believe are
> > >>> something like extrastyle etc...
>
> > >>> {% block extramedia %}
> > >>> {% if forms %}
> > >>>    {% for form in forms %}
> > >>>       {{ form.media }}
> > >>>    {% endfor 

Re: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
Sorry it's not working out for you, but I'd disagree about the
comparison to X-Windows :)  I'd be defending Django, and not X-
windows, when I say that.

I'm serious.  Just add them together.  I'm not sure you're
appreciating the slick objects that have been crafted for this very
purpose.

Your view:
cumulative_media = form.media for form in forms
return render_to_response('mytemplate.html', {'media':
cumulative_media})

Your template:
{% block my_media_block %}
{{ block.super }}
{{ media }}
{% endblock %}

I fail to see what is so hard about this.

Tim

On Nov 24, 4:13 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> You know what, this is absolutely too much BS.  Why would one bother to use 
> the media declaration stuff at all if there is no mechanism to properly 
> consume it (a built in template tag for instance).
>
> I think I will just hardcode them in the head in the base template.  They 
> seldom change and browser caching being what it is having them never change 
> is just fine.
>
> After three weeks of seriously trying to get traction with django, my 
> conclusion is it has all of the elegance of X-windows.  It can do anything 
> but out of the box it does nothing except present a zillion confusing parts 
> to the programmer and it has too many mechanisms but no policies.
>
> I'm beginning to very much pine for rails.  At least it does something out of 
> the box.
>
> Very frustrated today - still haven't got a single record/entry form working. 
>  Too many little files and indirection to keep it all straight in my head.
>
> -Todd Blanchard
>
> On Nov 24, 2009, at 2:05 PM, Tim Valenta wrote:
>
>
>
> > The idea is along the lines of what you initially guessed.
>
> > The admin accomplishes the non-duplicate effect in django/django/
> > contrib/admin/options.py, starting at line 770.  It loops over the
> > forms and combines the existing media with the media on each form
> > object.  It ends up using a series of objects to do it, including a
> > Media class, but it's not doing anything too special.  When an item
> > gets added, it checks to make sure that the path doesn't already exist
> > in the list.
>
> > So, short story: loop over your forms and add the media attributes
> > together.  The underlying Media class ought to be dropping duplicates.
>
> > Then just save a context variable with the result, and do the
> > following in your template:
>
> > {% block extrahead %} {# or whatever you call your header block #}
> >    {{ block.super }}
> >    {{ cumulative_media }}
> > {% endblock %}
>
> > Tim
>
> > On Nov 24, 12:30 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> >> What about de-duping?
> >> If two forms want the same js file, will it get included twice?
> >> It seems like this is the kind of thing that the framework should handle 
> >> and the current "solution" is kind of half baked.
>
> >> -Todd
>
> >> On Nov 23, 2009, at 2:40 PM, Mark (Nosrednakram) wrote:
>
> >>> Hello,
>
> >>> I have something like the following in my generic genericform.html.  I
> >>> think this is what you're looking for if not hope you find a better
> >>> answer. The extramedia block is back in my base.html  template and my
> >>> form template extends it. I'm not sure if it's in the admin base.html
> >>> but you can take a look at if for there media blocks I believe are
> >>> something like extrastyle etc...
>
> >>> {% block extramedia %}
> >>> {% if forms %}
> >>>    {% for form in forms %}
> >>>       {{ form.media }}
> >>>    {% endfor %}
> >>> {% else %}
> >>>   {{ form.media }}
> >>> {% endif %}
>
> >>> Mark
>
> >>> On Nov 23, 1:31 pm, Todd Blanchard <tblanch...@mac.com> wrote:
> >>>> I've read this:
>
> >>>>http://docs.djangoproject.com/en/dev/topics/forms/media/
>
> >>>> Nifty.  
>
> >>>> Now, how exactly do I make sure that the media urls get spewed properly 
> >>>> into the head section of the page?  This is apparently omitted 
> >>>> everywhere I've looked.  The admin template seems to pull it off 
> >>>> properly but I cannot figure out how.  Seems like I should be able to do 
> >>>> something like
>
> >>>> 
> >>>> 
> >>>> {{ media }}  
> >>>> 
>
> >>>> but I cannot figure out exactly how to properly aggregate all the forms' 
> >>>> 

Re: Module ho.pis can not be found when running on apache

2009-11-24 Thread Tim Valenta
I was caught by surprise when I moved my stuff to a production server,
too.  The live pythonpath is clearly different than you're expecting,
which I'm sure you know already.

My ultimate problem was that I was taking advantage of the fact that
Django's development server puts your project on the pythonpath
environment variable.  Apache does not.  So even once you get it
successfully running, things won't work properly sometimes, because
the various files in my project were omitting the project name when I
was trying to do imports.  I had to go back and add my project name in
as part of my imports ("from myapp.models import *" -> "from
myproject.myapp.models import *").

This may or may not be the exact problem, but when I look at your
pythonpath and glanced at Brad's link he pasted, I noticed that the
contents of your projects is on the path, but not the parent directory
of the project.  You may need an extra "__init__.py" in the parent
directory, too.

It all got really confusing, especially when I was trying to deploy
multiple Django sites.

Is any of that relevant to your problem?  I'm not exactly an expert,
but I know that I got harassed by this type of issue, too.

Tim

On Nov 24, 12:43 pm, "philip.bar...@impaerospace.com"
 wrote:
> When I try running my project via Apache I get a "No module named
> ho.pisa" error message.
>
> However, when I run the same project from django's built-in dev
> server, it works just fine.
>
> Similarly, when I access python, or go through python manage.py shell,
> I can import ho.pisa without error.
>
> I've tried reinstalling Pisa. I've double checked that Pisa is one my
> site packages and that my site packages are in my python path.
>
> I'm using Ubuntu 9.10, Apache 2.2, Django 1.0.3 and Python 2.5
>
> Setting python 2.5 as default was done with the following steps:
> /usr/bin/python is a symlink to /usr/bin/python2.5
> /usr/share/python/debian_defaults has been edited to specify python2.5
> has my default python
> And a partial recompile of mod python
>
> I successfully got this working using a different system running
> Ubuntu 8.10, so it might be a problem with Ubuntu 9.10.
>
> Anyone have any thoughts as to what to try next?
>
> Something that might be related that I couldn't figure out was that
> the error page from Django claims that the Django version is 2.6.4,
> which it shouldn't be.
>
> Full error read out follows:
>
> ViewDoesNotExist at /nsr/wizard/
>
> Could not import idms.nsr.views. Error was: No module named ho.pisa
>
> Request Method:         GET
> Request URL:    http://localhost/nsr/wizard/
> Exception Type:         ViewDoesNotExist
> Exception Value:
>
> Could not import idms.nsr.views. Error was: No module named ho.pisa
>
> Exception Location:     /usr/lib/python2.5/site-packages/django/core/
> urlresolvers.py in _get_callback, line 133
> Python Executable:      /usr/bin/python
> Python Version:         2.6.4
> Python Path:    ['/usr/lib/python2.5/site-packages', '/home/ase/Desktop/
> idms_project', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2',
> '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/
> python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/
> python2.6/dist-packages/Numeric', '/usr/lib/python2.6/dist-packages/
> PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/
> python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/
> pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-
> gtk2-unicode', '/usr/local/lib/python2.6/dist-packages']
> Server time:    Tue, 24 Nov 2009 21:38:28 +
>
> Environment:
>
> Request Method: GET
> Request URL:http://localhost/nsr/wizard/
> Django Version: 1.0.3
> Python Version: 2.6.4
> Installed Applications:
> ['django.contrib.auth',
>  'django.contrib.contenttypes',
>  'django.contrib.sessions',
>  'django.contrib.sites',
>  'django.contrib.admin',
>  'idms.general',
>  'idms.ipl',
>  'idms.doc',
>  'idms.ssi',
>  'idms.fsr',
>  'idms.dar',
>  'idms.dmm',
>  'idms.tdm',
>  'idms.ssir',
>  'idms.nsr',
>  'idms.ssir.templatetags',
>  'idms.ffd']
> Installed Middleware:
> ('django.middleware.common.CommonMiddleware',
>  'django.contrib.sessions.middleware.SessionMiddleware',
>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>  'django.middleware.doc.XViewMiddleware',
>  'django.middleware.transaction.TransactionMiddleware')
>
> Traceback:
> File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py"
> in get_response
>   82.                     request.path_info)
> File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py" in
> resolve
>   183.                     sub_match = pattern.resolve(new_path)
> File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py" in
> resolve
>   183.                     sub_match = pattern.resolve(new_path)
> File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py" in
> resolve
>   124.             return 

Re: How to unregister model?

2009-11-24 Thread Tim Valenta
> http://code.djangoproject.com/ticket/10829

Seeing as how it was last updated over a month ago, you might be best
off by downloading his patch and applying it, because there may not be
a solution very quickly.  Development for version 1.2 is going on
right now, and they're focusing on brand-new features at the moment.
Bug fixes and such tweaks (which I think this will be categorized as)
won't start getting attention until January.

If you've got an SVN checkout of Django, you can apply the patch with
some simple SVN commands (easily Google'd).  Just look for something
about applying a patch, specifically with that vocabulary.

If you've got a frozen downloaded version, you could open up the
".diff" patch in a text editor and figure out which file it's
patching, and add any lines with a "+" in front of it, and remove any
with a "-" in front of it.

I'm afraid there won't be a core update right away, and it sounds like
you're in need of one.  Unless someone more knowledgeable with the
Database layer can help out, I'm unsure of what else you might be able
to do.

On Nov 24, 3:02 pm, Tomasz Zieliński
<tomasz.zielin...@pyconsultant.eu> wrote:
> On 24 Lis, 22:42, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
> > > I want my unmanaged models to literally disappear from Django sight,
> > > and then re-appear on demand.
>
> > That sounds rather hack-ish... I'm not sure Django can do that
> > exactly.  I'm not familiar with the situation, exactly, so I'm unsure
> > of what you might be able to do differently.
>
> I'm suffering from something similar to this:
>
> http://code.djangoproject.com/ticket/10829
>
> - and I prefer to avoid hacking Django core, resorting to raw SQL etc.
> I only I could hide those unmanaged models, things would be smooth
> again,
> even though it's not the cleanest solution.
>
> --
> Tomasz Zielinskihttp://pyconsultant.eu

--

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: Designing base template - how to include media properly?

2009-11-24 Thread Tim Valenta
The idea is along the lines of what you initially guessed.

The admin accomplishes the non-duplicate effect in django/django/
contrib/admin/options.py, starting at line 770.  It loops over the
forms and combines the existing media with the media on each form
object.  It ends up using a series of objects to do it, including a
Media class, but it's not doing anything too special.  When an item
gets added, it checks to make sure that the path doesn't already exist
in the list.

So, short story: loop over your forms and add the media attributes
together.  The underlying Media class ought to be dropping duplicates.

Then just save a context variable with the result, and do the
following in your template:

{% block extrahead %} {# or whatever you call your header block #}
{{ block.super }}
{{ cumulative_media }}
{% endblock %}

Tim

On Nov 24, 12:30 pm, Todd Blanchard  wrote:
> What about de-duping?
> If two forms want the same js file, will it get included twice?
> It seems like this is the kind of thing that the framework should handle and 
> the current "solution" is kind of half baked.
>
> -Todd
>
> On Nov 23, 2009, at 2:40 PM, Mark (Nosrednakram) wrote:
>
>
>
>
>
> > Hello,
>
> > I have something like the following in my generic genericform.html.  I
> > think this is what you're looking for if not hope you find a better
> > answer. The extramedia block is back in my base.html  template and my
> > form template extends it. I'm not sure if it's in the admin base.html
> > but you can take a look at if for there media blocks I believe are
> > something like extrastyle etc...
>
> > {% block extramedia %}
> > {% if forms %}
> >    {% for form in forms %}
> >       {{ form.media }}
> >    {% endfor %}
> > {% else %}
> >   {{ form.media }}
> > {% endif %}
>
> > Mark
>
> > On Nov 23, 1:31 pm, Todd Blanchard  wrote:
> >> I've read this:
>
> >>http://docs.djangoproject.com/en/dev/topics/forms/media/
>
> >> Nifty.  
>
> >> Now, how exactly do I make sure that the media urls get spewed properly 
> >> into the head section of the page?  This is apparently omitted everywhere 
> >> I've looked.  The admin template seems to pull it off properly but I 
> >> cannot figure out how.  Seems like I should be able to do something like
>
> >> 
> >> 
> >> {{ media }}  
> >> 
>
> >> but I cannot figure out exactly how to properly aggregate all the forms' 
> >> media's and get them spewed into the templates properly.
>
> >> -Todd
>
> > --
>
> > 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 
> > athttp://groups.google.com/group/django-users?hl=.

--

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.




reversing URLs

2009-11-24 Thread Tim Valenta
Ever since day one, I've never had a firm grasp on what the heck URL
reversing can do.  I understand the concepts involved, even the admin
namespacing that can occur with different admin sites, and I know that
the admin uses it regularly, but it seems like a crazy unpredictable
wildcard when I try to use it manually.

For instance, I'm trying to get the permalink decorator to work on a
"get_absolute_url()" method on my model, and I haven't got the
slightest clue what the hell it's doing.  I'm getting errors about it
not being able to reverse it properly when I try to click on the admin-
generated "View on site ->" link from the change form.  It says that
it can't find the view.

Basically, I've tried making the method refer to the view object, a
view name as a string (explicitly setting the name in the url conf),
an absolute module-path string ("myproject.myapp.views.my_view"), and
nothing works.  It can never find it, even on a view with just a
single required keyword argument.

Is there any amazing breakdown on how to better wrap my brain around
how this url reversing thing works?  I typically don't think of myself
as an idiot, but I really cannot even begin to feel like I can use it
proficiently.

Thanks in advance.

--

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




Re: How to unregister model?

2009-11-24 Thread Tim Valenta
> I want my unmanaged models to literally disappear from Django sight,
> and then re-appear on demand.

That sounds rather hack-ish... I'm not sure Django can do that
exactly.  I'm not familiar with the situation, exactly, so I'm unsure
of what you might be able to do differently.

Apologies.

Tim

On Nov 24, 2:18 pm, Tomasz Zieliński
<tomasz.zielin...@pyconsultant.eu> wrote:
> On 24 Lis, 22:15, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
> > If you're not doing anything fancy with AdminSite objects (ie, you're
> > only using the default admin site), then do this:
>
> > # assuming you've already done: from django.contrib import admin
> > admin.site.unregister(MyModel)
>
> The 'unregister' word seems to have been misleading, as I wasn't
> referring
> to admin panel at all :)
>
> I want my unmanaged models to literally disappear from Django sight,
> and then re-appear on demand.
>
> --
> Tomasz Zielinskihttp://pyconsultant.eu

--

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: newbie questions regarding models and admin

2009-11-24 Thread Tim Valenta
Your first question about how to separate fields is not perfectly
clear to me.  However, I can say that I typically put *all* fields on
the actual admin objects, since an admin is typically not the one
you're trying to restrict.  Then, in your own custom views (and the
forms you render in those views), you just include the items that you
want to be publicly visible.

> But as far as I understand it this only works on the
> admin page and not generally.

You are correct.  Notice how you're setting the "max_num" attribute on
your subclassed ModelAdmin.  The Admin is really just an app, though
bundled with Django.  Anything you do with the admin won't ever have a
Django- or site-wide impact.  That might seem frustrating, but it does
help a lot for people who write general apps, which they distribute to
others.  We would find it far *more* frustrating to have to deal with
site-wide side effects that only were intended for the admin site.

The actual solution, since you seem to want to make your own forms and
not use the admin, would be to code this maximum-of-8 logic into your
views.  When you render the form, you'll want to do one of two things.

  1) If you think you want to just hard code this, just copy and paste
your template HTML to a total of 8 times, so that your form will
appear that many times.  You'll of course want to take care to use
proper HTML "name" attributes on the various elements, so that each of
the 8 forms has unique values there.  Point blank, you need the 8
forms to have unique names so that they don't get in a traffic jam
when you submit the form.

  2) A better solution might be to generate the 8 forms in Python in
your actual view function.  slap them in a list, and then just use the
template language to iterate them with a for loop.  This way, you can
more easily manipulate the data before it gets to the template.

And when they submit the form back onto the same view, the view will
check for `request.method == "POST"`, and then verify that there are
no more than 8 being submitted.  Defensive coding.

> Second thing I don't know is how to have the 8 subexperiments have their
> number automatically set. Is there a way to create the 8 subexperiments
> when an experiment is created?

This can go in a couple of directions...  If all you care about is the
way the name is display, you can make your __unicode__ method do
something like the following, assuming your top-level model was
"Parent", and your sub-level model was "Child"

def __unicode__(self):
total_children = self.parent.child_set.count()
return u'Experiment %d' % (i+1,) for i in range(0,
total_children)

This is a bigger hit to the database, but it could be totally
negligible if this is a fairly small project.

The idea is that you just count how many children there are, and
dynamically render a name based on their order.  Once you create a new
one, it'll automatically get a name in sequence with the others.

I hope that helps.

On Nov 24, 8:11 am, Andreas Kuntzagk 
wrote:
> Hi
>
> nek4life wrote:
> > The philosophy of the admin app is that it is a simple CRUD interface
> > for trusted staff members to manage data.  If you need data entry for
> > non staff members (i.e. people you do not trust with the admin) you
> > should create public facing forms and setup some permissions for the
> > users to be able to use them.
>
> Ok, will look into this.
>
> > As for you second question it sounds like you need two models, one for
> > experiment_x and one for sub_experiment_x with a foreignkey to
> > experiment_x.  You could probably use inline formsets to generate the
> > extra 8 forms.  I'm not sure how you would limit the inline formsets
> > though to exactly 8.
>
> I already have it like this. But I was wondering if there is a
> possibility to set it fixed to 8. I set extra and max_num to 8 for the
> StackedInline. But as far as I understand it this only works on the
> admin page and not generally.
> Second thing I don't know is how to have the 8 subexperiments have their
> number automatically set. Is there a way to create the 8 subexperiments
> when an experiment is created?
>
> Regards, Andreas
>
>
>
>
>
> > Hope this helps.
>
> > On Nov 24, 5:33 am, Andreas Kuntzagk 
> > wrote:
> >> Hi,
>
> >> I'm quite new to django and very new to this list.
> >> I'm in the process of writing a small webapp for our lab.
> >> Working with the tutorial I already put together a small model and some
> >> admin pages.
> >> But now I came to some stumbling blocks:
>
> >> First is a broader question: I'm wondering what belongs to an admin page
> >>   and what should be in a "normal" form. I want to keep track on some
> >> experiments so some (authenticated) users should create experiment
> >> entries and add comments etc. And then I have "machines" where these
> >> experiments run. These don't change so often. So does setting these
> >> things belong into the admin 

Re: Django-1.1.1 builtin Development WebServer crashes with a core dump

2009-11-24 Thread Tim Valenta
It's not very clear what is happening.  If you start a brand new
project, there won't be any URLs for you to visit yet.  It will most
probably give you the error page, telling you that there is no URL
matching the query.

A better copy-and-paste would be what the browser is displaying.

I hope I've understood properly,

Tim

On Nov 24, 10:24 am, lbockhold  wrote:
> Hello users,
> I am new to django, just installed Django-1.1.1.tar.gz
> but:
>
> Machine HPUX:
> th...@dex: /home/th18bl > uname -a
> HP-UX dex B.11.11 U 9000/785 4042425557 unlimited-user license
>
> python:
> th...@dex: /home/th18bl > python
> ActivePython 2.6.2.2 (ActiveState Software Inc.) based on
> Python 2.6.2 (r262:71600, Apr 21 2009, 15:06:28) [C] on hp-ux11
> Type "help", "copyright", "credits" or "license" for more information.
> dd
> 1.django-admin.py startproject mysite "ok"
> 2. python manage.py runserver "ok"
>     Validating models ...
>     0 errors found
>     ...
>     Quit the server ...
> 3. But when I use a browser to go to that page - the Dev. Server just
> quits and writes a big "core" file!
>
> Thanks for help
>
> Greetings Lars

--

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




Re: How to unregister model?

2009-11-24 Thread Tim Valenta
Sorry for double-post.

Additionally, you might experiment with the Meta class attribute,
"abstract = True" on your wrapper models.  It makes Django ignore the
model when it does database table creation.  That way, your wrapper
acts more like a true Python inheritance object, where you simply get
the benefits of inherited methods and fields, without the wrapper
creating its own lonely table without any data.

Not sure if it fits your situation, but it's good to know about.  It
seems like you're having to worry a bit too much about the extra
models.  There are all kinds of uses once you figure out how to use
it.

Here's the docs on it:

http://docs.djangoproject.com/en/dev/topics/db/models/#id6

On Nov 24, 2:15 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> If you're not doing anything fancy with AdminSite objects (ie, you're
> only using the default admin site), then do this:
>
> # assuming you've already done: from django.contrib import admin
> admin.site.unregister(MyModel)
>
> Note that it's exactly the opposite of the normal "admin.site.register
> ()" method, except that it only ever takes the one argument, not two.
>
> I do this for changing the default User model admin. I unregister it,
> alter the UserAdmin provided in Django, and then re-register it with
> my own.
>
> Tim
>
> On Nov 24, 1:54 pm, Tomasz Zieliñski
>
>
>
> <tomasz.zielin...@pyconsultant.eu> wrote:
> > Is there a way to unregister model from being seen by Django model
> > manager?
> > I have some unmanaged models that are wrappers around read-only
> > database views
> > and also have foreign keys to 'real' models.
>
> > Now, when I'm trying to delete instance of 'real' model that is
> > referenced by unmanaged model,
> > I'm getting OperationalErrors as Django tries to perform cascade
> > delete.
>
> > As a solution, I'd like to unregister my unmanaged models
> > before .delete(),
> > and re-registering them after, but I don't know how to do it.
>
> > --
> > Tomasz Zielinskihttp://pyconsultant.eu

--

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




Re: How to unregister model?

2009-11-24 Thread Tim Valenta
If you're not doing anything fancy with AdminSite objects (ie, you're
only using the default admin site), then do this:

# assuming you've already done: from django.contrib import admin
admin.site.unregister(MyModel)

Note that it's exactly the opposite of the normal "admin.site.register
()" method, except that it only ever takes the one argument, not two.

I do this for changing the default User model admin. I unregister it,
alter the UserAdmin provided in Django, and then re-register it with
my own.

Tim

On Nov 24, 1:54 pm, Tomasz Zieliński
 wrote:
> Is there a way to unregister model from being seen by Django model
> manager?
> I have some unmanaged models that are wrappers around read-only
> database views
> and also have foreign keys to 'real' models.
>
> Now, when I'm trying to delete instance of 'real' model that is
> referenced by unmanaged model,
> I'm getting OperationalErrors as Django tries to perform cascade
> delete.
>
> As a solution, I'd like to unregister my unmanaged models
> before .delete(),
> and re-registering them after, but I don't know how to do it.
>
> --
> Tomasz Zielinskihttp://pyconsultant.eu

--

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: Forms ModelMultipleChoiceField with checkboxes?

2009-11-23 Thread Tim Valenta
Actually-- quick followup:

The widget looks alright if you haven't got the 'aligned' css class on
the fieldset.  But if you do, watch out :P

On Nov 23, 4:20 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> That widget doesn't seem to look right on *any* browser.  It's got
> this weird step-like appearance.  Firefox is the only browser where it
> appears even close to acceptable.  I might be submitting a patch for
> the CSS soon...  It's horrible.
>
> On Nov 23, 1:14 pm, aa56280 <aa56...@gmail.com> wrote:
>
>
>
> > leoz01, Django comes with a widget for precisely this use case (check
> > link above). Creating your own would be a complete waste of time.
>
> > On Nov 20, 3:52 am, leoz01 <leozleo...@gmail.com> wrote:
>
> > > I think the easiest way is to make your own widget or otherwise you
> > > can make your own form field.
>
> > > On 19 nov, 10:19, Benjamin Wolf <b...@shs-it.de> wrote:
>
> > > > Hello,
>
> > > > I'm using Django's form and ModelMultipleChoiceField.
> > > > ModelMultipleChoiceField produces a select list with multiple options.
> > > > Is it possible to use
> > > >checkboxesinstead?
>
> > > > Thanks,
> > > > Greets Ben

--

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




Re: Forms ModelMultipleChoiceField with checkboxes?

2009-11-23 Thread Tim Valenta
That widget doesn't seem to look right on *any* browser.  It's got
this weird step-like appearance.  Firefox is the only browser where it
appears even close to acceptable.  I might be submitting a patch for
the CSS soon...  It's horrible.

On Nov 23, 1:14 pm, aa56280  wrote:
> leoz01, Django comes with a widget for precisely this use case (check
> link above). Creating your own would be a complete waste of time.
>
> On Nov 20, 3:52 am, leoz01  wrote:
>
>
>
> > I think the easiest way is to make your own widget or otherwise you
> > can make your own form field.
>
> > On 19 nov, 10:19, Benjamin Wolf  wrote:
>
> > > Hello,
>
> > > I'm using Django's form and ModelMultipleChoiceField.
> > > ModelMultipleChoiceField produces a select list with multiple options.
> > > Is it possible to use
> > >checkboxesinstead?
>
> > > Thanks,
> > > Greets Ben

--

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




Re: Autocomplete for Generic Foreign Keys

2009-11-23 Thread Tim Valenta
What's the context, exactly?  When used as an inline, the Generic-
family isn't any different than a normal inline.  I'm not sure why you
specify that you're looking for a solution for *Generic* foreign keys.

If you register a generic model directly to the admin, it gets kind of
kooky, so is that what you're doing?

On Nov 23, 1:38 pm, eka  wrote:
> Hi, Is there an autocomplete solution for Generic Foreign Keys?
>
> Found this:http://code.djangoproject.com/wiki/AutoCompleteSolutions
> But they don't work.
>
> Regards

--

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




Re: Definitive solution for foreignkey filtering in Admin

2009-11-05 Thread Tim Valenta

After considering the severe disadvantage imposed by lacking a
handling case for the 'add' view, I figured it out and wrote it up
here, for the sake of more verbose documentation:

http://mangos.dontexist.net/blog/?p=345

Primarily, the idea is that for inlines, I can grab the hidden field
providing the id of the primary parent field.  Using that id I can
traverse up to the parent, and then back down to filter options
accordingly.  For non-inline 'add' view cases, this is still an issue,
but if you can fill out enough required fields, you can actually do
something like the following:

class MyInlineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
if 'instance' in kwargs:
instance = kwargs['instance']
else:
instance = MyParentModel.objects.get(pk=tuple(i[0] for i
in form.fields['myparentmodel'].widget.choices)[1])
self.fields['othermodel'].queryset = OtherModel.objects.filter
(parent=instance)

Sorry if the abstraction to generic names is hard to read.  Basically
you get into the 'choices' on the hidden field (which are oddly still
fully assembled, with u'' and all) and grab the only id in the
list, using it to look up the proper model.  You could forgo the
actual model lookup, and just filter OtherModel by a lookup to the id
only, but in complex cases like my own (I've only touched the surface
with the Company-Contract-Location scenario) I need the model instance
itself.

Tim

On Nov 5, 4:37 pm, Tim Valenta <tonightslasts...@gmail.com> wrote:
> I don't know what changed, but updating my SVN in the last week
> sometime has fixed the problem that I was having.
>
> The dev trunk and I have a love-hate relationship :)
>
> I would make a note to anybody reading this that if the 'add' view is
> being used, you should kick off the code block with a "if 'instance'
> in kwargs"
>
> Working code:
>
>   # used in a direct subclass of ModelAdmin
>   class ContractForm(forms.ModelForm):
>       def __init__(self, *args, **kwargs):
>           forms.ModelForm.__init__(self, *args, **kwargs)
>           if 'instance' in kwargs:
>               contract = kwargs['instance']
>               self.fields['locations'].queryset =
> Location.objects.filter(company=contract.company)
>
>   # used in a TabularInline of that same ModelAdmin's inlines
>   class EventInlineForm(forms.ModelForm):
>       def __init__(self, *args, **kwargs):
>           forms.ModelForm.__init__(self, *args, **kwargs)
>           if 'instance' in kwargs:
>               contract = kwargs['instance']
>               self.fields['location'].queryset =
> Location.objects.filter(company=contract.company)
>
> Thank you, God.  I've been pulling my hair out over this.
>
> Tim
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Definitive solution for foreignkey filtering in Admin

2009-11-05 Thread Tim Valenta

I don't know what changed, but updating my SVN in the last week
sometime has fixed the problem that I was having.

The dev trunk and I have a love-hate relationship :)


I would make a note to anybody reading this that if the 'add' view is
being used, you should kick off the code block with a "if 'instance'
in kwargs"

Working code:

  # used in a direct subclass of ModelAdmin
  class ContractForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
  forms.ModelForm.__init__(self, *args, **kwargs)
  if 'instance' in kwargs:
  contract = kwargs['instance']
  self.fields['locations'].queryset =
Location.objects.filter(company=contract.company)

  # used in a TabularInline of that same ModelAdmin's inlines
  class EventInlineForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
  forms.ModelForm.__init__(self, *args, **kwargs)
  if 'instance' in kwargs:
  contract = kwargs['instance']
  self.fields['location'].queryset =
Location.objects.filter(company=contract.company)

Thank you, God.  I've been pulling my hair out over this.

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



Re: Definitive solution for foreignkey filtering in Admin

2009-10-26 Thread Tim Valenta

> forms.ModelForm.__init__(self, *args, **kwargs)
> location = kwargs.get('instance', None)
> if location:
> self.fields['contract'].queryset = Contract.objects.filter
> (company=location.company)

It seems that editing the values in self.fields yields rendering
errors:

Caught an exception while rendering: 'QuerySet' object has no
attribute 'label'

It appears that the values are not vanilla QuerySets... I've been
browsing the code again, and I really don't know what the values are.
It's fairly convoluted with that __metaclass__ business in there.  Do
we know what kind of datatype is in self.fields?  When the template
iterates the Form object, it's wrapping it as a BoundField, but
clearly something's messing up during that iteration.  I'm afraid I
don't know much about how the mechanics of this area work in the
Python code.

Any more pointers would be great.  Other than this speedbump, I think
this will do nicely.

Tim

On Oct 26, 8:53 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
> Many many thanks for the response.
>
> I had tried that approach, but had no idea what was coming through in
> kwargs.  I feel like 'kwargs' on most class objects needs more
> thorough documentation for the general users who refer primarily to
> the on-site docs.  Even digging through some code, I simply had no
> idea.
>
> This should provide a working fix for the sort of filtering I need to
> do.  I hope that maybe I or some other person can provide some code to
> help simplify this amazingly common dilemma.  Any models that group in
> logical relationships of 3 seem to always have this problem, and I'd
> love to have a simpler fix to write off in the docs.
>
> Tim
>
> On Oct 25, 8:28 pm, Matt Schinckel <matt.schinc...@gmail.com> wrote:
>
>
>
> > On Oct 24, 5:14 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
> > > I've been searching for a while on how to intercept querysets in
> > > forms, to apply a custom filter to the choices on both foreignkey and
> > > m2m widgets.  I'm surprised at how there are so many similar questions
> > > out there, dating back to 2006.
>
> > [snip]
>
> > > The only solution I've seen has dealt with filtering by User foreign
> > > key (being that User is available in the request object in views), and
> > > that's primarily for non-Admin views.
>
> > [snip]
>
> > > I've been looking at the code for the above noted API method,
> > > formfield_for_foreignkey, and I really can't see a way to get
> > > references to an instance of the object being edited.  I would need
> > > such a reference to successfully override that method and filter my
> > > queryset on this relationship.
>
> > I too spent some time looking at formfield_for_foreignkey, and had no
> > luck.
>
> > You can subclass ModelAdmin, and then limit the objects in the field's
> > queryset.
>
> > ** admin.py **
>
> > class LocationAdminForm(forms.ModelForm):
> >     def __init__(self, *args, **kwargs):
> >         forms.ModelForm.__init__(self, *args, **kwargs)
> >         location = kwargs.get('instance', None)
> >         if location:
> >             self.fields['contract'].queryset = Contract.objects.filter
> > (company=location.company)
>
> > class LocationAdmin(admin.ModelAdmin):
> >     model = Location
> >     form = LocationAdminForm
>
> > I also had to do something similar with Inlines, when I did the same
> > type of thing.  This is not my exact code, but it is very close, and
> > suited toward your use case.
>
> > Matt.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Definitive solution for foreignkey filtering in Admin

2009-10-26 Thread Tim Valenta

Many many thanks for the response.

I had tried that approach, but had no idea what was coming through in
kwargs.  I feel like 'kwargs' on most class objects needs more
thorough documentation for the general users who refer primarily to
the on-site docs.  Even digging through some code, I simply had no
idea.

This should provide a working fix for the sort of filtering I need to
do.  I hope that maybe I or some other person can provide some code to
help simplify this amazingly common dilemma.  Any models that group in
logical relationships of 3 seem to always have this problem, and I'd
love to have a simpler fix to write off in the docs.

Tim

On Oct 25, 8:28 pm, Matt Schinckel <matt.schinc...@gmail.com> wrote:
> On Oct 24, 5:14 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
>
> > I've been searching for a while on how to intercept querysets in
> > forms, to apply a custom filter to the choices on both foreignkey and
> > m2m widgets.  I'm surprised at how there are so many similar questions
> > out there, dating back to 2006.
>
> [snip]
>
> > The only solution I've seen has dealt with filtering by User foreign
> > key (being that User is available in the request object in views), and
> > that's primarily for non-Admin views.
>
> [snip]
>
> > I've been looking at the code for the above noted API method,
> > formfield_for_foreignkey, and I really can't see a way to get
> > references to an instance of the object being edited.  I would need
> > such a reference to successfully override that method and filter my
> > queryset on this relationship.
>
> I too spent some time looking at formfield_for_foreignkey, and had no
> luck.
>
> You can subclass ModelAdmin, and then limit the objects in the field's
> queryset.
>
> ** admin.py **
>
> class LocationAdminForm(forms.ModelForm):
>     def __init__(self, *args, **kwargs):
>         forms.ModelForm.__init__(self, *args, **kwargs)
>         location = kwargs.get('instance', None)
>         if location:
>             self.fields['contract'].queryset = Contract.objects.filter
> (company=location.company)
>
> class LocationAdmin(admin.ModelAdmin):
>     model = Location
>     form = LocationAdminForm
>
> I also had to do something similar with Inlines, when I did the same
> type of thing.  This is not my exact code, but it is very close, and
> suited toward your use case.
>
> Matt.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Need Help Migrating to Windows 7 (64-bit), Python 2.6, Django 1.1

2009-10-24 Thread Tim Valenta

I would still raise the warning of caution, that certain external
Python libraries do not have 64-bit versions, like PIL.  I tried the
whole 64-bit Python thing, and I just couldn't do it because of some
library dependancies.

I also use a setup like yours on Windows 7, except with MySQL, and a
32-bit version of Python.  I'd like to keep my eyes open for a 64-bit
version of PIL...

On Oct 24, 10:12 am, JimR  wrote:
> Turns out the problem was with PostgreSQL.  The prior installation was
> running 8.3 (not 8.4 as noted).  The new installation was using 8.4.
> Dropping back to 8.3 on the new installation corrected the issue for
> me.  I'm sure there are migration issues to consider moving from 8.3
> to 8.4, but I'll leave those for the future.
>
> So I'm currently successfully running Python 2.6.3, Django 1.1.1, and
> PostgreSQL 8.3 on Windows 7.
>
> On Oct 21, 12:03 pm, JimR  wrote:
>
>
>
> > Hello, All,
>
> > I  am trying to migrate my application from Python 2.5, Dango 1.0,
> > PostgreSQL 8.4,WindowsXP (32-bit) to Python 2.6, Django 1.1,
> > PostgreSQL 8.4,Windows7(64-bit).  I have donwloaded and installed
> > the 64-bit version of Python 2.6.
>
> > I am having a problem with a particular model under the new
> > configuration that doesn't give me any problems in the old
> > configuration.  I get the same error in my application as I do in the
> > generic admin view.  All of my other models and views seem to be
> > working fine, except those that utilize this model.
>
> > I've excerpted the relevant code and error messages below, but
> > hesitate to post the traceback and model definition since both are
> > rather lengthy, and if this is a relatively straightforward error, I'd
> > rather not waste your time and the space.
>
> > Any suggestions or ideas on where to focus my efforts?  If you'd like
> > to see the model and traceback, I'd be happy to post it.
>
> > Thanks,
> > Jim
>
> > App:
> > Caught an exception while rendering: maximum recursion depth exceeded
> > in cmp
> > ...
> > {% for r in reg_list %}
> > ...
> > (from views.py: reg_list = Registration.objects.filter
> > (registered_by=request.user).select_related()
>
> > Admin:
> > TemplateSyntaxError at /admin/registration/registration/
> > Caught an exception while rendering: maximum recursion depth exceeded
> > c:\python26\lib\site-packages\django\contrib\admin\templates\admin
> > \change_list.html, error at line 78:
>
> > 76     {% block result_list %}
> > 77          {% if action_form and actions_on_top and cl.full_result_count
> > %}{% admin_actions %}{% endif %}
> > 78          {% result_list cl %}
> > 79          {% if action_form and actions_on_bottom and
> > cl.full_result_count %}{% admin_actions %}{% endif %}
> > 80      {% endblock %}
>
> > The traceback is rather lengthy,
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



SQL syntax error in Admin

2009-10-24 Thread Tim Valenta

If there's nothing I can determine here, I'll move over to submitting
a ticket on the matter.  Wanted to check in here first.

Using...

Django 1.2 SVN revision 11653, (updated just 2 minutes ago)
MySQL 5.1.31

Models:
class Category(models.Model):
category = models.CharField()
class Question(models.Model):
category = models.ForeignKey(Category)
class Template(models.Model):
categories = models.ManyToManyField(Category,
related_name='templates')
questions = models.ManyToManyField('Question',
related_name='templates', limit_choices_to=Q(category__in=F
('templates__categories')))

The error popped up while I was playing with that 'limit_choices_to'
option on Template.questions.

The error text:
Caught an exception while rendering: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near
'`surveys_surveytemplate_categories`.`surveycategory_id`' at line 1")


The logic behind the model setup is that a Template consists of
Categories and Questions.  Since each Question has an underlying
Category of its own, I want to filter the Question list to only
contain items whose own Category is found on the base Template's m2m
relationship to Category.

Please ask if clarification is needed..

This setup works great if I remove the usage of 'F
("templates__categories")' and just hardcode a '[1,2]' in its place.
Something about using 'F' in a 'Q' in 'limit_choices_to' is not
working.

Any ideas on how I could snag the SQL and print it out somehow?  This
isn't like PHP where I can just throw down a print line anywhere in
the code, even if I use an event listener attached to the query-making
pipeline.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Definitive solution for foreignkey filtering in Admin

2009-10-23 Thread Tim Valenta

I've been searching for a while on how to intercept querysets in
forms, to apply a custom filter to the choices on both foreignkey and
m2m widgets.  I'm surprised at how there are so many similar questions
out there, dating back to 2006.

I came across the documentation for
ModelAdmin.formfield_for_foreignkey (http://docs.djangoproject.com/en/
dev/ref/contrib/admin/
#django.contrib.admin.ModelAdmin.formfield_for_foreignkey), and
thought I had a perfect solution, but the method doesn't seem to
entirely fit the hole I'm trying to fill.

Consider these models:

# models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)

So, Company is at the top of the hierarchy, with both Contract and
Location holding foreign keys to Company, and then Contract and
Location share an m2m relationship.

The admin presents this data so that the m2m widget on Contract lets
you pick from any Location in the database.  Arguably, there should be
an option for the implied common relationship to take effect, of both
Contract and Location to Company.

The only solution I've seen has dealt with filtering by User foreign
key (being that User is available in the request object in views), and
that's primarily for non-Admin views.




I've been looking at the code for the above noted API method,
formfield_for_foreignkey, and I really can't see a way to get
references to an instance of the object being edited.  I would need
such a reference to successfully override that method and filter my
queryset on this relationship.

Any thoughts?  There are dozens of unanswered questions just like this
all over popular sites on the internet.  We need a solution.  The
feature list for Django 1.2 does not seem to reference anything on
this matter!

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



Re: Limit choices based on a foreign key

2009-10-22 Thread Tim Valenta

I would very much be interested in a solution to this problem.  I
can't yet understand why Django is so wonderful at so many things, yet
has absolutely no mechanism for this.  Every time there seems to be
hope of a working solution, it never works for inlines.

For the sake of painting up another example of what I understand to be
the same problem, I've got these models:

# models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)

# admin.py
class LocationInline(admin.TabularInline):
model = Location
class ContractInline(admin.TabularInline):
model = Contract
class CompanyAdmin(admin.ModelAdmin):
inlines = (ContractInline, LocationInline)


This creates a problem when setting up the Admin for Company, because
it has inlines for both Contract and Location, and Contract's m2m
options for Location are not properly filtered according to the
Company that you're currently editing.

Is there anyone out there who knows of something straightforward to
satisfy this badly needed shortcut? Every "solution" I find doesn't
really deal with the Admin site, and it involves sketchy views that
try to use middleware to catch the object pk out of the URL.  totally
not ideal.

Back when I made PHP admins for this sort of thing, this was
considered basic functionality! In fact, it was always automatic, and
had to be disabled if you really didn't want it!

I've seen stranded unanswered posts on this subject for 3 years!  We
need a solution!  I just can't figure out anything that doesn't
require digging into the guts of the code and adding a new shortcut
API method on admin.ModelAdmin / TabularInline to help achieve this
goal.

Tim

On Oct 12, 9:36 am, Christian Wittwer  wrote:
> Ok, I found a way, but it's still not perfect.
>
> class GoalForm(forms.ModelForm):
>
>     class Meta:
>         model = Goal
>
>     def __init__(self, *args, **kwargs):
>         super(GoalForm, self).__init__(*args, **kwargs)
>         self.fields['goal_scorer'].queryset =
> Player.objects.filter(gameroster__game=self.instance.game)
>
> class GoalInline(admin.TabularInline):
>     model = Goal
>     extra = 4
>     #form= GoalForm
>
> class GameAdmin(admin.ModelAdmin):
>     list_display = ('date_time', 'home_team', 'opponent_team',
> 'is_home_game', 'season', 'league', 'type', 'result')
>     list_filter = ['league', 'season']
>     inlines = [GameRosterInline, GoalInline, PenaltyInline]
>     ordering       = ('date_time',)
>
> That works as long as I edit the model game not inline. The selection
> of player gets limited as I want.
> When I try to edit it inline in the game, the GoalForm seems not to
> work. It's going to be ignored.
> When I try to comment in "form= GoalForm", the whole app doesn't run
> anymore. I got a DoesNotExist exception, but I think this is because
> it can't register theform..
>
> Any ideas who to activate my customformfor the inline mode?
>
> Chris
>
> 2009/10/12 Christian Wittwer :
>
>
>
> > Hi,
> > I have a question regarding the admin interface of django.
>
> > My models
>
> > class Team(models.Model):
> >    name = models.CharField(max_length=10)
>
> > class Player(models.Model):
> >    lastname = models.CharField(max_length=60)
>
> > class Goal(models.Model):
> >    game = models.ForeignKey(Game)
> >    goal_scorer =
> > models.ForeignKey(Player,related_name='goal_scorer',blank=True,null=True)
>
> > class Game(models.Model):
> >    home_team = models.ForeignKey(Team,related_name='home_team')
>
> > class GameRoster(models.Model):
> >    player = models.ForeignKey(Player)
> >    game = models.ForeignKey(Game)
>
> > Each Goal is scored by a Player in a Game. I'm using a inlineformto
> > insert goals for a game.
> > The players are somehow connected to the team (gameroster), and
> > therefore to the game.
>
> > I found the place to hook in to limit the choices of player.
>
> > class GoalInline(admin.TabularInline):
> >    model = Goal
> >    extra = 4
>
> >    def formfield_for_foreignkey(self, db_field, request, **kwargs):
> >        if db_field.name == "goal_scorer":
> >            kwargs["queryset"] =
> > Player.objects.filter(gameroster__game=self.game)
> >            return db_field.formfield(**kwargs)
>
> >        return super(GoalInline,
> > self).formfield_for_foreignkey(db_field, request, **kwargs)
>
> > The missing point is now: How to access game, which is connected to
> > the goal to limit the players?
> > I tried self.game as you can see, but that doesn't work.
> > How can I access the model from within this function?
>
> > Chris
--~--~-~--~~~---~--~~
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 

Re: m2m trouble when referencing "self"

2009-04-26 Thread Tim Valenta

Amazing, thanks.  I just couldn't find the documentation to prove it
one way or the other.  I just didn't guess that anything would be
different by default!

Much appreciated,
Tim

On Apr 25, 4:28 pm, Alex Gaynor <alex.gay...@gmail.com> wrote:
> On Sat, Apr 25, 2009 at 6:26 PM, Tim Valenta 
> <tonightslasts...@gmail.com>wrote:
>
>
>
>
>
> > Hello all.  I tried the IRC, but it's too chaotic and not enough
> > people take you seriously :)
>
> > Very very abbreviated example code:
>
> > class Person(models.Model):
> >    parents = models.ManyToManyField('self', related_name='children')
>
> > Now, the exact relationship is just an example, but it demonstrates my
> > problem.
>
> > Two things happen which don't seem to be normal.  By "normal", I mean
> > m2m relationships that relate to other models, and not "self".
>
> > 1) using the admin site, I make Persons A and B.  A will be a parent,
> > and B will be a child.  So, I use the admin site to change B,
> > selecting A as a parent.  But now when I go to A's change form, it
> > lists B in its selected 'parents' widget.  That's completely contrary
> > to my previous experience with the m2m relationship.  Shouldn't A only
> > list B when I access "children.all()" from A?
>
> > 2) But then that leads me to the second oddity.  From the shell:
> > >>> personA = Person.objects.get(pk=1)
> > >>> personA.children.all()
> > AttributeError: 'Person' object has no attribute 'children'
>
> > I've been practically cursing my laptop as I've been battling this
> > issue.  None of my other manytomany relationships (where models relate
> > to *other* models, not to "self") on my site suffer from this problem.
>
> > Any direction at all would be immensely appreciated.
>
> > I'm using the latest django SVN update, Python 2.5.4, MySQL.
>
> > Thanks,
> > Tim
>
> The issue is by default m2m relationships are symmetrical, you can change
> this 
> though:http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.mod...
>
> Alex
>
> --
> "I disapprove of what you say, but I will defend to the death your right to
> say it." --Voltaire
> "The people's good is the highest law."--Cicero
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



m2m trouble when referencing "self"

2009-04-25 Thread Tim Valenta

Hello all.  I tried the IRC, but it's too chaotic and not enough
people take you seriously :)

Very very abbreviated example code:

class Person(models.Model):
parents = models.ManyToManyField('self', related_name='children')

Now, the exact relationship is just an example, but it demonstrates my
problem.

Two things happen which don't seem to be normal.  By "normal", I mean
m2m relationships that relate to other models, and not "self".

1) using the admin site, I make Persons A and B.  A will be a parent,
and B will be a child.  So, I use the admin site to change B,
selecting A as a parent.  But now when I go to A's change form, it
lists B in its selected 'parents' widget.  That's completely contrary
to my previous experience with the m2m relationship.  Shouldn't A only
list B when I access "children.all()" from A?

2) But then that leads me to the second oddity.  From the shell:
>>> personA = Person.objects.get(pk=1)
>>> personA.children.all()
AttributeError: 'Person' object has no attribute 'children'

I've been practically cursing my laptop as I've been battling this
issue.  None of my other manytomany relationships (where models relate
to *other* models, not to "self") on my site suffer from this problem.

Any direction at all would be immensely appreciated.

I'm using the latest django SVN update, Python 2.5.4, MySQL.

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



django searching wrong package for 'static.serve'

2009-01-17 Thread Tim Valenta

Hello all.  Just trying to make django serve my static media files
(css is my main test case right now) during development.  I've
included the lines in my URLconf as instructed by this page:
http://docs.djangoproject.com/en/dev/howto/static-files/

My issue is that this line is causing a 500 error when my site's main
template HTML requests a URL that falls into the regex for a static
file serve.  The error says:

ViewDoesNotExist: Could not import mysite.django.views.static. Error
was: No module named django.views.static

The issue here is that it's trying to root the search for the
'static.serve' package in "mysite".  Of course, the 'serve' function
is nowhere near "mysite" --- rather, it's in the default django
stuff.  But instead of searching for the package in the main django
package, it's searching in "mysite", which of course has no subset of
packages called "mysite.django.views.static".

Every other aspect of django seems to work out just great so far.  I'm
running Windows Vista as my development platform for now, and I'm
using the most up-to-date SVN trunk.  There's nothing special about my
installation of Django,  Python, or my URLconf.  I'm using Python
2.5.2 right now (since I'm tied to MySQLdb, which currently only has a
release for Python 2.5.x).

Any ideas?  I can't seem to find any better documentation than
provided in the link I posted first thing in this message.

Thanks in advance.
Tim

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