hobbes3
hobbes3

Reputation: 30218

How do I set fields in ModelForm externally in Django?

My current setup in views.py looks like this

def order_detail(request, pk):
    order = Order.objects.get(pk=pk)

    # Define the can_something variables here.

    include_fields = []

    if can_edit_work_type:
        include_fields.append('work_type')
    if can_edit_vendor:
        include_fields.append('vendor')
    if can_edit_note:
        include_fields.append('note')

    class OrderDetailForm(forms.ModelForm):
        class Meta:
            model = Order
            fields = tuple(include_fields)

    form = OrderDetailForm(instance=order, data=request.POST)

    return render(request, 'doors/order/detail.html', {'order': order, 'form': form})    

Obviously I think it's best practice to define OrderDetailForm inside forms.py instead of views.py. So how do I move OrderDetailForm to forms.py and still pass include_fields?

I tried something like this but it didn't work

views.py

def order_detail(request, pk):
    order = Order.objects.get(pk=pk)

    # Define the can_something variables here.

    include_fields = []

    if can_edit_work_type:
        include_fields.append('work_type')
    if can_edit_vendor:
        include_fields.append('vendor')
    if can_edit_note:
        include_fields.append('note')

    form = OrderDetailForm(instance=order, data=request.POST, include_fields=include_fields)

    return render(request, 'doors/order/detail.html', {'order': order, 'form': form})    

forms.py

class OrderDetailForm(forms.ModelForm):
    class Meta:
        model = Order

    def __init__(self, include_fields, *args, **kwargs):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        self.Meta.fields = tuple(include_fields)

But that didn't work; it included all the fields on the model. I'm assuming the problem is in the object orientation.

Any tips or suggestions are welcomed. Thanks in advance!

Upvotes: 1

Views: 407

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

You have to modify self.fields in the initializer, removing keys in the mapping not found in the sequence.

Upvotes: 1

Daniel Watkins
Daniel Watkins

Reputation: 1686

Looking at the Django code, you might want to try using self._meta.fields = tuple(include_fields).

Upvotes: 1

Related Questions