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 8949025
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T13:08:34+00:00 2026-06-15T13:08:34+00:00

I’m using Django 1.4 with Python 2.7 on Ubuntu 12.10. I have a form

  • 0

I’m using Django 1.4 with Python 2.7 on Ubuntu 12.10.

I have a form where I need to populate a few drop-downs dynamically (using jQuery) but need 2 of them to be required and the 3rd to be optional.

I’m using Tastypie to help with the API to get the options. Basically the first drop-down is populated with industry level codes for schools. Once a code is selected a category drop-down is populated for all categories for that code. Once the category is chosen a subcategory drop-down is populated for all subcategories for that combination of code and category.

I’m able to require the code drop-down (it’s not dynamically populated). However, I’m having a tough time getting the category drop-down to be required. There are basically 2 routes I can take – front-end validation or back-end validation. I’m trying to go with back-end validation so I can easily create further validation if needed.

Here is the form:

class SchoolProductForm(forms.ModelForm):
    cip_category = forms.ChoiceField(required=True,
                                     choices=(('', '----------'),))

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

        self.fields['short_description'].widget = TA_WIDGET
        self.fields['salary_info'].widget = TA_WIDGET
        self.fields['job_opportunities'].widget = TA_WIDGET
        self.fields['related_careers'].widget = TA_WIDGET
        self.fields['meta_keywords'].widget = TI_WIDGET
        self.fields['meta_description'].widget = TI_WIDGET
        self.fields['cip'].queryset = models.CIP.objects.filter(
            parent_id__isnull=True)


    class Meta:
        model = models.SchoolProduct
        exclude = ('campus',)

I’ve tried to override the clean method. I’ve tried to create a field specific clean method. Neither seem to work.

Variations of the following:

def clean(self):
    super(SchoolProductForm, self).clean()
    if cip_category in self._errors:
        del self._errors['cip_category']
    if self.cleaned_data['cip_category'] == '----------':
        self._errors['cip_category'] = 'This field is required.'

    return self.cleaned_data

This gives an error that there is no cip_category in cleaned_data, which makes sense because it didn’t validate.

I’ve tried variations with the field specific clean:

def clean_cip_category(self):
    data = self.cleaned_data['cip_category']
    self.fields['cip_category'].choices = data

    return data

But get a validation error on the page stating my choice is not one of the available choices.

I’ve tried to create a dynamic field type (several variations):

class DynamicChoiceField(forms.ChoiceField):
    def valid_value(self, value):
        return True

class SchoolProductForm(forms.ModelForm):
    cip_category = DynamicChoiceField(required=True,
                                      choices=(('', '----------'),))

But it accepts ---------- as a valid option (which I don’t want) and causes an error since the ORM tries to match a value of ---------- in the database (which it won’t find).

Any ideas?

  • 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-15T13:08:35+00:00Added an answer on June 15, 2026 at 1:08 pm

    I was able to solve this with a little overriding of a method in ChoiceField.

    I added the field to the form and handled the pre-population with the self.initial:

    class SchoolProductForm(forms.ModelForm):
        cip_category = common_forms.DynamicChoiceField(
            required=True, choices=(('', '----------'),))
    
        def __init__(self, *args, **kwargs):
            super(SchoolProductForm, self).__init__(*args, **kwargs)
    
            self.fields['short_description'].widget = TA_WIDGET
            self.fields['salary_info'].widget = TA_WIDGET
            self.fields['job_opportunities'].widget = TA_WIDGET
            self.fields['related_careers'].widget = TA_WIDGET
            self.fields['meta_keywords'].widget = TI_WIDGET
            self.fields['meta_description'].widget = TI_WIDGET
            self.fields['cip'].queryset = models.CIP.objects.filter(
                parent_id__isnull=True)
    
            # Get the top parent and pre-populate
            if 'cip' in self.initial:
                self.initial['cip'] = models.CIP.objects.get(
                    pk=self.initial['cip']).top_parent()
    
        class Meta:
            model = models.SchoolProduct
            exclude = ('campus',)
    

    Where DynamicChoiceField is:

    class DynamicChoiceField(forms.ChoiceField):
        def valid_value(self, value):
            return True
    

    Then, in the view I added handling in the form_valid override:

    def form_valid(self, form):
        self.object = form.save(commit=False)
    
        # Handle the CIP code
        self.object.cip_id = self.request.POST.get('cip_subcategory')
        if self.object.cip_id == '':
            self.object.cip_id = self.request.POST.get('cip_category')
    
        self.object.save()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
This could be a duplicate question, but I have no idea what search terms
I have a text area in my form which accepts all possible characters from
I need to clean up various Word 'smart' characters in user input, including but
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has

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.