How do I set fields in ModelForm externally in Django?

岁酱吖の 提交于 2019-12-08 07:45:28

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/10660994/how-do-i-set-fields-in-modelform-externally-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!