Django UpdateForm DateInput小部件不显示日期

时间:2019-12-27 09:15:19

标签: django django-forms django-widget

我正在使用DateInput小部件在输入日期字段时提供日期选择器。但是在我的更新表单上,该表单会提取记录的所有数据,但日期除外,日期显示为:

dd/mm/yyy

如何获取已显示的输入日期” models.py

class Project(models.Model):
    '''
    Main Project, serves the default Projects Portal window.
    '''
    published = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    area = models.ForeignKey(
        Area,
        related_name="project",
        on_delete=models.PROTECT
        )
    title = models.CharField(max_length=128, unique=True)
    slug = models.SlugField(max_length=64)
    summary = models.CharField(max_length=256)
    others = models.CharField(max_length=128, blank=True)
    staff_trials = models.DateField(null=True, blank=True)
    deadline = models.DateField()
    slip = models.BooleanField(default=False)

    class Meta:
        ordering = ["-slip", "deadline"]

    def __str__(self):
        return self.title

forms.py

class DateInput(forms.DateInput):
    input_type = 'date'

class ProjectModelForm(forms.ModelForm):
    """
    Form used for creating and editing projects. Authenticated User
    required to be signed in.
    """
    title = forms.CharField(widget=forms.Textarea)
    summary = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Project
        fields = (
            'title',
            'summary',
            'others',
            'staff_trials',
            'deadline',
            'area',
        )
        widgets = {
            'staff_trials': DateInput(),
            'deadline': DateInput(),
        }

veiws.py

class ProjectEditView(UpdateView):
    template_name = 'project_portal/project_detail.html'
    form_class = ProjectModelForm
    queryset = Project.objects.all()

    def form_valid(self, form):
        user = self.request.user
        form.instance.user = user
        print(form.cleaned_data)
        return super().form_valid(form)

    def get_object(self):
        slug_ = self.kwargs.get("slug")
        return get_object_or_404(Project, slug=slug_)

1 个答案:

答案 0 :(得分:0)

您不应再次定义titlesummary。如果要使用文本区域小部件,只需在表单的Meta部分中指定它,它会更清洁。在您的情况下,覆盖默认的forms.DateInput并不有用。

class ProjectModelForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = (
            'title',
            'summary',
            'others',
            'staff_trials',
            'deadline',
            'area',
        )
        widgets = {
            'title': forms.Textarea(),
            'summary': forms.Textarea(),
            'staff_trials': forms.DateInput(),
            'deadline': forms.DateInput(),
        }

最后,您确定好对象正在用于更新视图吗?字段titlesummary等是预期的吗?


EDIT :另一种解决方案,带有django-tempus-dominus软件包,非常有用,并且带有漂亮的小部件。

安装小部件

pip install django-tempus-dominus

然后,将应用程序tempus_dominus添加到您的INSTALLED_APPS设置中。

使用表单中的小部件

# forms.py

from tempus_dominus.widgets import DatePicker
class ProjectModelForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = [
            'title',
            'summary',
            'others',
            'staff_trials',
            'deadline',
            'area',
        ]
        widgets = {
            'deadline': DatePicker(
                options={
                    'format': 'DD/MM/YYYY'
                },
                attrs={
                    'prepend': 'fa fa-calendar',
                },
            )
        }

您可以在DatePicker小部件中添加很多选项,例如查看herehere

更新您的模板

只需在用于显示日期的模板中添加{{ form.media }}。要显示日期,无需更改任何内容:{{ form.deadline }}

注意:请不要忘记添加必要的资源!像jQuery一样,Bootstrap4 ...只需查看文档<head></head>中指定的资源即可。

实际示例(我自己的配置)

例如,这是我的操作方式,因此只能通过单击来设置任何日期(用户不能在输入的日期内键入内容):

# forms.py

import datetime
from allauth.account.forms import SignupForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from tempus_dominus.widgets import DatePicker

sixteen_years_ago = datetime.date.today() - datetime.timedelta(days=16*365.24)
common_options_for_datetimepicker = {
    'icons': {
        'time': 'far fa-clock',
        'date': 'far calendar-alt',
        'up': 'fas fa-arrow-circle-up',
        'down': 'fas fa-arrow-circle-down',
        'previous': 'far fa-arrow-alt-circle-left fa-lg',
        'next': 'far fa-arrow-alt-circle-right fa-lg',
    },
    'widgetPositioning': {
        'vertical': 'bottom',
        'horizontal': 'left'
    },
    'ignoreReadonly': True,
}

class Signup_MixinForm(SignupForm):
    class Meta:
        abstract = True

class SignupRegular_Form(Signup_MixinForm):
    birth_date = forms.DateField(
        required=True,
        initial=sixteen_years_ago,
        widget=DatePicker(
            options={
                **common_options_for_datetimepicker,
                'format': 'D/MM/YYYY',
                'maxDate': sixteen_years_ago.strftime('%Y-%m-%d')
            },
            attrs={
                'prepend': 'fa fa-calendar',
                'size': 'large',
                'placeholder': _("Your birth date"),
                'readonly': 'readonly'
            },
        ),
    )