Creating a model model from a model form

I have a MyModel that contains a PK-locid i.e. AutoField.

I want to build a model set of forms from this with some caveats:

  • The set of queries for the formset should be normal (e.g. order_by ('field')), not all ()
  • Since the locid for MyModel is AutoField and thus hidden by default, I want to show it to the user.

I'm not sure how to do this. I have tried several approaches,

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

      

The above gives me 3 fields, but the 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 is giving me a ManyToMany error.

Has anyone done something like this before?


Edit 2

Now I can 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 to use the application. How can I do it? Is there a way to override the default behavior for hiding the PC if it's auto-field?

0


a source to share


3 answers


As a result, I used the template side variable as I mentioned here:



How to show hidden autofield in django formet

+1


a source


It makes no sense to show the user autofield, as it is an auto-incrementing primary key - the user cannot change it and it will not be available until the record is saved in the database (where the DBMS chooses the next available ID).

This is how you set up 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 this set of forms in a factory function:

MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet)

      

+2


a source


If you like cheap workarounds, why not use method locid

in method __unicode__

? The user should be convinced of this, and no special knowledge of django-admin is required.

But to be honest, all of my answers to django-admin related questions tend to "don't strain to make django-admin in a generic CRUD" interface.

0


a source







All Articles