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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T01:03:10+00:00 2026-06-11T01:03:10+00:00

Off of this question , I have an Action model that has a foreign

  • 0

Off of this question, I have an Action model that has a foreign key which specifies how often an action reoccurs:

class Reoccurance(models.Model):
    label = models.CharField("Label", max_length=50, unique = True)
    days = models.IntegerField("Days")

    def __unicode__(self):
        return self.label

    class Meta:
        ordering = ['days']

class Action(models.Model):
    name = models.CharField("Action Name", max_length=200, unique = True)
    complete = models.BooleanField(default=False, verbose_name="Complete?")
    reoccurance = models.ForeignKey(Reoccurance, blank=True, null=True, verbose_name="Reoccurance")

I’m making a modelForm of Action that results in HTML code for reoccurance (based on the database values that exist for the Reoccurance table):

<select id="id_reoccurance" class="selectwithtitles" name="reoccurance">
    <option value="" title="" >---------</option>
    <option value="12" title="2" >2 Days</option>
    <option value="1" title="3" >3 Days</option>
    <option value="2" title="5" >5 Days</option>
    <option value="10" title="6" >6 Days</option>
    <option value="9" title="7" >1 Week</option>
    <option value="3" title="10" >10 Days</option>
    <option value="4" title="14" >2 Weeks</option>
    <option value="11" title="21" >3 Weeks</option>
    <option value="5" title="30" >1 Month</option>
    <option value="13" title="42" >6 Weeks</option>
    <option value="6" title="90" >1 Quarter</option>
    <option value="7" title="180" >6 Months</option>
    <option value="8" title="365" >1 Year</option>
</select>

I generate the titles by a subclassed field:

from django.utils.html import conditional_escape, escape
from django.utils.encoding import force_unicode

class SelectWithTitles(forms.Select):
    def __init__(self, *args, **kwargs):
        super(SelectWithTitles, self).__init__(*args, **kwargs)
        # Ensure the titles dict exists
        self.titles = {}

    def render_option(self, selected_choices, option_value, option_label):
        title_html = (option_label in self.titles) and \
            u' title="%s" ' % escape(force_unicode(self.titles[option_label])) or ''
        option_value = force_unicode(option_value)
        selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
        return u'<option value="%s"%s%s>%s</option>' % (
            escape(option_value), title_html, selected_html,
            conditional_escape(force_unicode(option_label)))

class ChoiceFieldWithTitles(forms.ChoiceField):
    widget = SelectWithTitles

    def __init__(self, choices=(), *args, **kwargs):
        choice_pairs = [(c[0], c[1]) for c in choices]
        super(ChoiceFieldWithTitles, self).__init__(choices=choice_pairs, *args, **kwargs)
        self.widget.titles = dict([(c[1], c[2]) for c in choices])

    def clean(self, value):
        self.required = False
        if not value and not self.required:
            return value
        return super(ChoiceFieldWithTitles, self).clean(value)

class ActionForm(forms.ModelForm):
    reoccurance = ChoiceFieldWithTitles()

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

        choices = []
        for pt in Reoccurance.objects.all():
            choices.append((pt.id, pt.label, pt.days))
        self.fields['reoccurance'] = ChoiceFieldWithTitles(choices = choices)

    def clean(self):
        cleaned_data = super(ActionForm, self).clean()
        if cleaned_data.get("reoccurance") != '':
            rec = Reoccurance.objects.get(pk=cleaned_data.get("reoccurance"))
            self.cleaned_data['reoccurance'] = rec
        return super(ActionForm, self).clean()

I had to add the clean method to ActionForm because I had to return the database Reoccurance object, not simply it’s id.

I also had to add a clean method to the ChoiceFieldWithTitles because I could not get it to allow a blank value for reoccurance. It also saw it as required, even when I used reoccurance = ChoiceFieldWithTitles(required=False).

My issue now is that I can’t seem to allow a blank value. If the user selects the first option of the drop down:

<option value="" title="" >---------</option>

The form returns this error:

ValueError at /next_actions/test-action-9712,778/edit/
Cannot assign "u''": "Action.reoccurance" must be a "Reoccurance" instance.

What do I need to do to the ActionForm’s clean method to allow a blank value for the reoccurance field?

  • 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-11T01:03:11+00:00Added an answer on June 11, 2026 at 1:03 am

    No, all you need to do is use the proper base field type. If you’re dealing with a foreign key or an M2M relationship, the field should be a ModelChoiceField type, not ChoiceField.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is a forked problem off of this question: flac: "ERROR: input file has
This question has developed off an answer here . My question therefore is what
First off, let me preface this question by stating that I'm really a pretty
I have two questions, actaully... First off, Why cant I do this: List<Object> object
This question stems off another post I had. (see Search through column in excel
So, my second question based off of this application I'm teaching myself Objective C
First off, sorry if this is a stupid question. I installed code::blocks to try
First off - hello, this is my first Stack Overflow question so I'll try
Is there a way to turn off this mode? I must have clicked it
This question is a bit rhetorical. At some point i got a feeling that

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.