user4979733
user4979733

Reputation: 3411

How to use work week in DateField in Django admin

In my model, I say:

class Foo(models.Model):
   start = models.DateField(help_text='Start Date')

In the django admin, when adding a new Foo object, I see a text field with a calendar attached allowing me to select the date. I want to customize this a little bit so that I can either select the date from the calendar or enter something like WW12'22 in the textfield and during Save, this gets converted into a DateField. I am not sure how to do implement this in the django admin. Any ideas would be helpful.

I try something like this, but I get an invalid date when I enter '05 22' (i.e, WW05'22).

class FooForm(forms.ModelForm):
     start_date = forms.DateField(widget=forms.DateInput(format='%W %y'), localize=True)

Upvotes: 0

Views: 587

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You could create your own DateField subclass and when the provided value isn't parsed as a date you implement your own parsing.

Since you need to provide the day of the week to use week number when parsing, replace the "WW" part of your input with 1 and parse this as the day of the week (1 is Monday)

admin.py

import re
import datetime

from django.contrib import admin
from django import forms

from .models import Foo
from django.contrib.admin.widgets import AdminDateWidget

class MyDateField(forms.DateField):
    def to_python(self, value):
        try:
            return super().to_python(value)
        except forms.ValidationError:
            if re.match(r'WW\d+\'\d+', value):
                return datetime.datetime.strptime(value.replace('WW', '1-'), '%w-%W\'%y')
            raise


class FooForm(forms.ModelForm):

    start_date = MyDateField(widget = AdminDateWidget)

    class Meta:
        model = Foo
        fields = '__all__'


class FooAdmin(admin.ModelAdmin):
    form = FooForm


admin.site.register(Foo, FooAdmin)

Upvotes: 1

Related Questions