Django:防止 Form 在使用 akward 日期格式时崩溃

Django: prevent Form to crash when akward date format is used

提问人:Skratt 提问时间:8/17/2023 最后编辑:Skratt 更新时间:8/23/2023 访问量:14

问:

我有一个表格:

class EditProfileForm(forms.ModelForm):
    template_name = 'users/edit_profile.html'

    def __init__(self, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.fields['email'].help_text = _(
            'Providing your email would enable you to recover your lost password')


    class Meta:
        model = get_user_model()
        fields = (
            'first_name',
            'last_name',
            'email',
            'birthday',
            'language',
            'headshot',
        )

使用用户模型:

class CustomUser(AbstractUser):

    birth_year = models.PositiveIntegerField(
        verbose_name=_('Birth year'), default=0)
    birthday = models.DateField(verbose_name=_(
        "birthday"), null=True, blank=True)
    headshot = models.ImageField(verbose_name=_('Avatar'),
                                 null=True, blank=True, default='user_headshots/user.png', upload_to="user_headshots/")

    language = models.CharField(verbose_name=_('Language'),
                                max_length=10,
                                choices=settings.LANGUAGES,
                               default=settings.LANGUAGE_CODE)

并查看:

@login_required(login_url='/accounts/login/')
def edit_user_profile(request):
    if request.method == 'POST':

        form = EditProfileForm(
            request.POST, request.FILES, instance=request.user)

        if form.is_valid():
            # delete the cached value from self.__dict__:
            request.user.refresh_cached_profile_attributes()

            form.save()

            messages.success(request, _(
                "Your profile was succesfully modified"), extra_tags='text-center')

            return redirect(request.GET.get('next'), 
                            extra_query= {'first_play': True} if 'first_play' in request.GET else {}
                            )
    else:
        context = {}
        
        
        form = EditProfileForm(instance=request.user)
        context.update({'form': form})

        return render(request, 'users/edit_profile.html', context)

我有一个用户使用了一种奇怪的生日格式,这导致 django 应用程序崩溃:"25,2,96"

The view users.views.edit_user_profile didn't return an HttpResponse object. It returned None instead.

回溯?!中没有太多信息

查看 django 代码和互联网,我很惊讶它没有附带嵌入式验证器DateFieldformfields

互联网上有很多关于为特定日期设置特定日期格式的信息,但我无法找到一种适用于所有本地化日期格式的最佳实践。DateField

对于这样一个微不足道的问题,我发现的一切都非常复杂,我很确定有一个简洁且易于实施的解决方案。

有什么建议吗?

django 日期 验证 django-forms

评论

0赞 Sumithran 8/17/2023
显示相关视图

答: 暂无答案