views:

173

answers:

4

Django flatpages uses a many-to-many relationship with the django Site model

class FlatPage(Model)
    ...
    sites = ManyToManyField(Site)

You must select a site when creating a new flatpage. While I might utilize multiple sites later, right now it's unnecessary an annoying. I want to have the current (and only) Site preselected on the add form. I can't figure out how to make this happen. I've made several other successful modifications to the default flatpages behavior. But this one escapes me.

I wanted to do something like the following:

sites = ManyToManyField(Site, default=Site.objects.get_current)

But that doesn't work. Any help is appreciated.

A: 

you forgot the trailing parens after get current

Site.objects.get_current()

phillc
That's not a typo. The default option takes a callable object. Unless I'm mistaken that means you pass the actual function and it gets called upon object creation. FYI, I did try it with the parens when the above didn't work.
Marco
A: 

Did you try limit_choices_to argument?

Alternatively move away from the flatpages and create your own custom pages models if you do not need to be dependent on the site framework.

drozzy
limit_choices_to doesn't actually select the value in the widget
Marco
A: 

You can extend FlatPageAdmin, exclude sites and save flatpage with your current site. Sort of:

class ExtendedFlatPageAdmin(FlatPageAdmin):
    fieldsets = (
        (None, {
            'fields': ('url', 'title', 'content')
        }),
        ('Advanced options', {
            'classes': ('collapse',),
            'fields': ('enable_comments', 'registration_required', 'template_name')
        }),
    )

    def save_model(self, request, obj, form, change):
        obj.save()
        current_site = Site.objects.get_current()
        obj.sites.add(current_site)
A: 

I ended up just employed a little jquery to do this. It's not very portable but worked for me. The select box for sites has the id "id_sites", so:

$('#id_sites').attr('selectedIndex',0);

Just selects the first option automatically. I put this in the document load event and it works just fine.

Marco