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

  • Home
  • SEARCH
  • 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 7010065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T21:56:35+00:00 2026-05-27T21:56:35+00:00

I have a model, Director with two DateFields, and two subclasses (code below). I

  • 0

I have a model, Director with two DateFields, and two subclasses (code below). I am trying to create an admin page for each Director which shows the corresponding subclass instance, and not the Director instance; this part is mostly easy (I create an inline for each subclass, give the main ModelAdmin a form with all fields excluded, and have the main ModelAdmin only request formsets from the inlines which have a corresponding instance – the code; there is an unresolved issue with this approach, which I note below, but is not the focus of this question).

The problem I have is that I want to massage the values displayed to the user, one of which is shown in a readonly field, one of which is not. The processing is that I want to change a magic value (date(1,1,1)) to the string "On incorporation".

Dates in readonly fields aren’t rendered in a format very friendly to parsing, and I would like to reduce unnecessary dependence on javascript, so I would very much prefer a server-side solution.

The code below displays the forms as I want them, except that date values are not massaged at all, and when saving, there is a spurious “Please correct the error below” message, even though there are no errors, and all fields are saved correctly.

My question is: how do I intercept the values to be rendered on the page, both in readonly fields, and in forms fields, and alter them to display a string of my choosing?

The models (so far as material):

class Director(models.Model, Specializable):
    date_of_appointment = models.DateField()
    date_ceased_to_act = models.DateField(blank=True,null=True)

class DirectorsIndividual(Director):
     pass

class DirectorsCorporate(Director):
     pass

The admin code:

class DirectorAdmin(EnhancedAdmin):

    fields = ()

##    def formfield_for_dbfield(self, db_field, **kwargs):
##        return None

    def queryset(self, request):
        """ Directors for all companies which are incorporated by the current user's organisation """
        individual = Individual.for_user(request.user)
        return Director.objects.filter(company__incorporation_ticket__ordered_by__in = Organisation.all_organisations_for_which_individual_authorised_to_incorporate(individual))

    class form(forms.ModelForm):
        # have this return no html - that way only inlines are shown
        class Meta:
            fields = ()
            pass

        def is_valid(self):
            self._errors = {}
            return True

    class DirectorsIndividualInline(admin.StackedInline):
        model = DirectorsIndividual
        fk_name = 'director_ptr'
        extra = 0
        readonly_fields = ('deferred_on','company','date_of_appointment',)
        can_delete = False

        def get_readonly_fields(self, request, obj=None):
            if obj and obj.company and not obj.company.is_submitted(): return self.readonly_fields # allow editing of fields listed in else
            else:
                return itertools.chain(self.readonly_fields, ('individual', 'is_secretary'))

        def has_delete_permission(self, request, obj=None):
            return obj and ((obj.company and not obj.company.is_submitted()) or not obj.company)

        class form(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(forms.ModelForm, self).__init__(*args, **kwargs)
                self.fields['surrogate_for'].required = False
                self.fields['representative_for'].required = False
                if self.instance:
                    obj = self.instance
                    for field in (f for f in type(obj)._meta.fields if type(f) == fields.DateField):
                        val = field.value_from_object(obj)
                        assert (type(val) in (datetime.date, type(None),))
                        # assert field.name != 'date_of_appointment'
                        if val == inc_consts.EARLIEST_DATE:
                            self.initial[field.name] = "On incorporation"

            def is_valid(self):
                self._errors = {}
                return True

    class DirectorsCorporateInline(admin.StackedInline):

        model = DirectorsCorporate
        fk_name = 'director_ptr'
        extra = 0
        can_delete = False

        class form(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(forms.ModelForm, self).__init__(*args, **kwargs)
                if True:
                    for k in self.fields:
                        self.fields[k].required = False

            def is_valid(self):
                self._errors = {}
                return True


    inlines = (DirectorsIndividualInline,DirectorsCorporateInline)

    def get_inlines(self, request, obj=None):
        return (inline for inline in (self.inline_instances)
                if inline.model.objects.filter(**{(inline.fk_name or self.model._meta.object_name.lower()) : obj }))

    def get_formsets(self, request, obj=None):
        """ only return formset for inlines for which there exists an object """
        return (inline.get_formset(request, obj) for inline in self.get_inlines(request, obj))

I realise that there is an asymmetry between DirectorsCorporateInline and DirectorsIndividualInline; that is because I am testing on an instance with a DirectorsIndividual instance. The code above refers to model fields not shown in the models, because they are not material to the dates issue; it should be possible to render them immaterial for the spurious error issue without altering those fields (although I realise it is less helpful for that issue, I want to keep this question mostly focused on one issue). EnhancedAdmin is a ModelAdmin subclass with some minor alterations which shouldn’t be of consequence. Extra code can be shown on reasoned request, but I don’t want to confuse with irrelevant code.

For completeness: I am using django 1.3.1 on python 2.7.2.

  • 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-05-27T21:56:35+00:00Added an answer on May 27, 2026 at 9:56 pm

    Define a member function of your Director class that renders the readonly_field as you want.

    class Director(models.Model, Specializable):
        date_of_appointment = models.DateField()
        date_ceased_to_act = models.DateField(blank=True,null=True)
        def date_of_appointment_str(self):
            if self.date_of_appointment == datetime.date(1,1,1):
                return "On incorporation"
            else:
                return "%s" % (self.date_of_appointment) # format as you wish
    

    and then just add 'date_of_appointment_str' to your list of readonly_fields in the admin.

    EDIT: I should add that this is one quick solution. A more robust solution is to subclass models.DateField into a MyCustomDateField that acts like a DateField except that when the value is date(1,1,1) it renders as “On incorporation” or when a user saves “On incorporation” it saves the value as date(1,1,1). This would ensure that you can reuse this functionality everywhere this field type shows up. However, if it only shows up in one place; this may be overkill.

    You’d need something like (this is untested; you may need to additionally alter your the forms DateField and/or other things; e.g., if you use django-south you’ll have to add custom introspection rules).

    class MyCustomDateField(models.DateField):
        date_111_str = 'On incorporation'
        def value_to_string(self, obj):
            val = self._get_val_from_obj(obj)
            if val is None:
                data = ''
            elif val.year == val.day == val.month == 1:
                data = date_111_str
            else:
                data = datetime_safe.new_date(val).strftime("%Y-%m-%d")
            return data
        def get_prep_value(self, value):
            if value == date_111_str:
                value = datetime.date(1,1,1)
            return super(MyCustomDateField,self).get_prep_value(self, value)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two Model/Controllers which are essentially duplicating data (just on different pages). When
I have model Foo which has field bar. The bar field should be unique,
Lets say I have model inheritance set up in the way defined below. class
I'm setting up a directory application for which I need to have two separate
How can you have model declarations at two different directories in Django? I have
I have multiple models which relate back to a single model. On save of
The two apps have the same sharedUserId. When I use this code in app1
I have a Django project which has two apps (one created as debug test).
I am creating a WPF/MVVM framework which generates the code for the model classes.
I have a model with three classes: PendingAuthorisation , Director , and Member .

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.