views:

530

answers:

3

Hi everyone,

I have a model MyModel which contains a PK - locid, that is an AutoField.

I want to construct a model formset from this, with some caveats:

  • The queryset for the formset should be a custom one (say, order_by('field')) rather than all()
  • Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user.

I'm not sure how to do this. I've tried multiple approaches,

MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))

The above gives me the 3 fields, but locid is hidden.

class MyModelForm(ModelForm):

  def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    self.fields['locid'].widget.attrs["type"] = 'visible'
    locid = forms.IntegerField(min_value = 1, required=True)

  class Meta:
    model = MyModel
    fields = ('locid', 'name', 'dupof')

The above gives me a ManyToMany error.

Has anyone done something like this before?


Edit 2

I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? Is there a way to override the default behavior of hiding a PK if its an autofield?

+2  A: 

It makes no sense to show an autofield to the user, as it's an autoincremented primary key -- the user can not change it and it will not be available before saving the record to the database (where the DBMS selectes the next available id).

This is how you set a custom queryset for a formset:

from django.forms.models import BaseModelFormSet

class OrderedFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.queryset = MyModel.objects.order_by("field")
        super(OrderedFormSet, self).__init__(*args, **kwargs)

and then you use that formset in the factory function:

MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet)
uggedal
Hmm, the need for this form is that I want to be able to atleast _show_ the user the locid (even if it is hidden and can't be modified). What would you suggest as the best way to do that?
viksit
A: 

If you like cheap workarounds, why not mangle the locid into the __unicode__ method? The user is guaranteed to see it, and no special knowledge of django-admin is required.

But, to be fair, all my answers to django-admin related questions tend along the lines of "don't strain to hard to make django-admin into an all-purpose CRUD interface".

David Berger
Actually, this is independent of the django-admin interface - by which I assume you mean the server, and not the libraries?
viksit
+1  A: 

I ended up using a template side variable to do this, as I mentioned here:

http://stackoverflow.com/questions/896153/how-to-show-hidden-autofield-in-django-formset

viksit