Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7970017
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:19:49+00:00 2026-06-04T07:19:49+00:00

From this question I want to convert my form from regular Form to ModelForm

  • 0

From this question I want to convert my form from regular Form to ModelForm so I can take advantage of instance parameter in ModelForm.

Here is my current form code:

class OrderDetailForm(forms.Form):
    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        if can_edit_work_type:
            self.fields['work_type'] = forms.ChoiceField(choices=Order.WORK_TYPE_CHOICES)
        if can_edit_vendor:
            self.fields['vendor'] = forms.ModelChoiceField(
                queryset=Vendor.objects.all(),
                empty_label="Choose a vendor",
            )
        if can_edit_note:
            self.fields['note'] = forms.CharField(widget=forms.Textarea)

    def clean(self):
        super(OrderDetailForm, self).clean()

        if 'note' in self.cleaned_data:
            if len(self.cleaned_data['note']) < 50:
                self._errors['note'] = self.error_class([u"Please enter a longer note."])

                del self.cleaned_data['note']

        return self.cleaned_data

As you can see, I have some if statements that determine whether the fields even show you in the forms (logically it means certain users can only edit certain parts of the fields).

How would I do that in ModelForm? I understand fields to be a tuple, so it can’t be appended like I did in Form. So I want to do something like

class OrderDetailForm(forms.ModelForm):
    class Meta:
        model = Order
        # fields = ('work_type', 'vendor', 'note') I can't do that since I need to be able to control it. See below.

        # Can I control widgets even if that field doesn't exist?
        widgets = {
            'note': forms.Textarea(),
        }

    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        fields = []

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

        self.Meta.fields = tuple(fields) # Does this work?

    def clean(self):
        super(OrderDetailForm, self).clean()

        if 'note' in self.cleaned_data:
            if len(self.cleaned_data['note']) < 50:
                self._errors['note'] = self.error_class([u"Please enter a longer note."])

                del self.cleaned_data['note']

        return self.cleaned_data

Is that possible? How do you control the fields in ModelForm?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:19:50+00:00Added an answer on June 4, 2026 at 7:19 am

    Another possible way is generate a inline form class in the view to exclude fields based on the request, for example, define a normal model form for Order model, called OrderDetailForm:

    class OrderDetailForm(forms.ModelForm):
        class Meta:
            model = Order
            fields = ('work_type', 'vendor', 'note') 
            widgets = {
                'note': forms.Textarea(),
            }
    

    In the view, for example, edit order, create a customized form based on the OrderDetailForm:

    def edit(request, order_id):
        order = Order.objects.get(pk=order_id)
        can_edit_work_type = bool(request.REQUEST.get('can_edit_work_type', False))
        can_edit_vender = bool(request.REQUEST.get('can_edit_vender', False))
        can_edit_note = bool(request.REQUEST.get('can_edit_note', False))
    
        exclude_fields = []
    
        if not can_edit_work_type:
            exclude_fields.append('work_type')
    
        if not can_edit_vender:
            exclude_fields.append('vender')
    
        if not can_edit_note:
            exclude_fields.append('note')
    
        class CustomizedOrderForm(OrderDetailForm):
            class Meta:
                model = Order
                exclude = tuple(exclude_fields)
    
        if request.method == 'POST':
            form = CustomizedOrderForm(instance=order, data=request.POST)
            if form.is_valid():
                form.save()
        else:
            form = CustomizedOrderForm(instance=order)
        return render(request, 'order_form.html', {'form': form})
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I asked this question before: Generate XML from a class I want to do
As I just learned from this question , .NET regexes can access individual matches
This question has been asked here in one form or another but not quite
Like this question states - I want to convert a click (2D) into coordinates
(This question is following on from my previous problem which has been fixed (Here)
From this question I learned Double.NaN is not equal to itself. I was verifying
Continuing from this question : When I am trying to do fopen on Windows,
This question is a follow on from this one ... I am binding to
I'm gleaning from this question [ Facebook Connect Won't Validate that using Facebook Connect
Following on from this question , I am interested in finding out how you

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.