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

The Archive Base Latest Questions

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

I created a Field to save the weekdays, used in a model like that

  • 0

I created a Field to save the weekdays, used in a model like that (models.py):

from myfields import *
from django.db import models

class MyModel(models.Model):
    weekdays = WeekdayField()

The file in which i have stored the form declaration is myfields.py and is this one:

from django.db import models
from django import forms

class Weekdays(object):
    CHOICES = (
        (1, "Monday"),
        (2, "Tuesday"),
        (4, "Wednesday"),
        (8, "Thursday"),
        (16, "Friday"),
        (32, "Saturday"),
        (64, "Sunday"),
        )
    MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY = [2**i for i in range(0,7)]
    del i

    def __init__(self, value=0):
        self.raw = value

    def __add__(self, other):
        return Weekdays(self.raw | other)

    def __sub__(self, other):
        return Weekdays(self.raw & (-1 ^ other))

    def __unicode__(self):
        ret = []
        for ele in Weekdays.CHOICES:
            if (self.raw & ele[0]) >> ele[0] == 1:
                ret.append(ele[1])
        return ",".join(ret)

    def __iter__(self):
        ret = []
        for ele in Weekdays.CHOICES:
            if (self.raw & ele[0]) >> ele[0] == 1:
                ret.append(ele)
        return iter(ret)

    def __len__(self):
        i = 0
        for n in range(7):
            if (self.raw & n) >> n == 1:
                i += 1
        return i



class WeekdayField(models.Field):
    description = "Multiple select of weekdays"

    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 3
        super(WeekdayField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if isinstance(value, int):
            return [ wd for wd in Weekdays(value) ]
        if isinstance(value, Weekdays):
            return value
        if isinstance(value, list): #list of weekstay
            wd = Weekdays()
            for val in value:
                wd += int(val)
            return wd

    # PY to DB
    def get_prep_value(self, value):
        return value.raw

    def formfield(self, **kwargs):
        defaults = {'form_class': WeekdayFormField}
        defaults.update(kwargs)
        return super(WeekdayField, self).formfield(**defaults)

    def get_internal_type(self):
        return "IntegerField"


class WeekdayFormField(forms.MultipleChoiceField):
    def __init__(self, *args, **kwargs):
        if 'choices' not in kwargs:
            kwargs['choices'] = Weekdays.CHOICES
        kwargs.pop('max_length', None)
        if 'widget' not in kwargs:
            kwargs['widget'] = forms.widgets.CheckboxSelectMultiple
        super(WeekdayFormField, self).__init__(*args, **kwargs)


    def clean(self, value):
        super(WeekdayFormField, self).clean(value)
        possible_values = [ str(x[0]) for x in Weekdays.CHOICES ]
        for v in value:
            if not v in possible_values:
                raise forms.ValidationError("Day not valid")
        return value

Using this i can create and remove the elements through Django Admin, but when i modify a value i don’t see the value that i stored before. I looked into the database and the value are stored right.

Any ideas on how to make me see what is the current value on Django Admin, during the modification?

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

    I’ve the solution! it was a wrong the implementation of the methods Weekdays.__unicode__() and Weekdays.__iter__().

    Finally i had also changed the two methods reported below, in WeekdayField.

    #Class-type
    class Weekdays(object):
        ...
    
        def __unicode__(self): # Request for the matching
            ret = []
            for i,ele in enumerate(Weekdays.CHOICES):
                if (self.raw & ele[0]) >> i == 1:
                    ret.append(unicode(ele[0]))
            return ','.join(ret)
    
        def __iter__(self):
            for i,ele in enumerate(Weekdays.CHOICES):
                if (self.raw & ele[0]) >> i == 1:
                    yield Weekdays(ele[0])
    
    
    #Field to include in the model
    class WeekdayField(models.Field):
        ...
    
        # DB to PY
        def to_python(self, value):
            if isinstance(value, int):
                return [ wd for wd in Weekdays(value) ]
            if isinstance(value, unicode):
                return [ wd for wd in Weekdays(int(value)) ]
            if isinstance(value, Weekdays):
                return value
            if isinstance(value, list): #list of Weekdays
                wd = []
                for val in value:
                    wd += self.to_python(val)
                return wd
    
        #PY to DB
        def get_prep_value(self, value):
            if isinstance(value, Weekdays):
                return value.raw
            if isinstance(value, list):
                sum_raw = 0
                for val in value:
                    sum_raw += self.get_prep_value(val)
                return sum_raw
    

    I hope this will be helpful to someone!

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

Sidebar

Related Questions

I have a model with SlugField . Value of that field is created when
Assume a django model with two fields: - created - modified Each field are
We have created a table with a trigger that updates a ModifiedDate field in
I have two models, a MainModel and a related InlineModel that i'd like to
I have a model with a field that is required but not entered by
I've created an app that has several models (say A, B) that are polymorphically
I have created on2many field in class A and other field nombre (integer): 'Inventaire'
I understand that Django won't let you save a incomplete fields in a single
I'm trying to create a custom timestamp field. class TimestampKey(models.CharField): __metaclass__ = models.SubfieldBase def
I have a before_save in my Message model defined like this: class Message <

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.