Django:只需给出月份和日期即可设置生日

问题描述 投票:0回答:1

我对 Django 完全陌生

我想在管理面板中创建一个字段,我们只需提供月份和日期即可设置用户的生日。现在,我们只能给出日期,但这不是我想要的。例如,我想要 2 个下拉列表,一个用于当天,一个用于月份

我的用户模型看起来像这样

型号:

from django.contrib.auth.models import User



# Create your models here.
class Profile(models.Model):

    birthday = models.DateField(blank=True, null=True)

    def __str__(self):
        return f'{self.user.get_full_name()}'
python django django-models django-admin
1个回答
0
投票

我尝试根据您的要求用

DateField()
解决这个问题

模型.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birthday = models.DateField(blank=True, null=True)

    def __str__(self):
        return f'{self.user.username}'

管理员.py

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import Profile
import datetime

class ProfileAdminForm(forms.ModelForm):
    # Custom form to separate month and day fields
    birthday_month = forms.IntegerField(label='Birthday Month', widget=forms.Select(choices=[(i, i) for i in range(1, 13)]))
    birthday_day = forms.IntegerField(label='Birthday Day', widget=forms.Select(choices=[(i, i) for i in range(1, 32)]))

    class Meta:
        model = Profile
        fields = ['user', 'birthday_month', 'birthday_day']

class ProfileAdmin(admin.ModelAdmin):
    form = ProfileAdminForm
    list_display = ['user', 'birthday']

    def save_model(self, request, obj, form, change):
        # Combine the selected month and day into the birthday field
        month = form.cleaned_data['birthday_month']
        day = form.cleaned_data['birthday_day']
        
        # Use the current year as a placeholder
        year = datetime.datetime.now().year

        # Format the date as YYYY-MM-DD
        obj.birthday = f'{year}-{month:02d}-{day:02d}'
        super().save_model(request, obj, form, change)

admin.site.register(Profile, ProfileAdmin)

# Extend the UserAdmin to include the Profile model
class CustomUserAdmin(UserAdmin):
    pass

# Replace the default UserAdmin with the custom one
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

浏览器预览

© www.soinside.com 2019 - 2024. All rights reserved.