Question

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?

Was it helpful?

Solution 2

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

How to show hidden autofield in django formset

OTHER TIPS

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)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top