Django表单-DateInput未从实例填充

时间:2019-10-08 22:23:53

标签: python django django-forms

我正在尝试为包含DateField的Django模型设置编辑表单。我已经将此字段设置为forms.py中的forms.DateInput。这对于创建模型的新实例效果很好,但是当我尝试使用现有实例填充表单时,即使所有其他字段均已正确填充,DateInput字段仍为空白。

如果我恢复为默认的TextField输入,则可以正确地调用数据。我还尝试在DateInput小部件中设置格式。

models.py

class Rider(models.Model):
    first_name = models.CharField(max_length=40)
    surname = models.CharField(max_length=40)
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES = [
        (MALE, 'Male'),
        (FEMALE, 'Female'),
    ]
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    dob = models.DateField("Date of Birth", auto_now = False, auto_now_add = False)
    club = models.CharField(max_length=50,blank=True, null=True)
    bc_number = models.IntegerField("British Cycling Membership Number", blank=True, null=True)
    linked_account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)

views.py

def rider_edit(request, pk):
    rider = get_object_or_404(Rider, pk=pk)
    if request.method == "POST":
        form = RiderForm(request.POST, prefix='rider', instance=rider)
        if form.is_valid():
            rider = form.save(commit=False)
            rider.linked_account = request.user
            rider.save()

            return redirect('rider_list')
    else:
        form = RiderForm(prefix='rider', instance=rider)
    return render(request, 'riders/rider_new.html', {'riderform': form})

form.py

from django import forms
from .models import Rider, MedicalInfo


class RiderForm(forms.ModelForm):

    class Meta:
        model = Rider
        fields = ('first_name', 'surname', 'gender', 'dob', 'club', 'bc_number')
        widgets= {
            'dob': forms.DateInput(attrs={'type': 'date'}, format='%d/%m/%Y')
        }

rider_new.html

<h2>New Rider</h2>
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ riderform.as_p }}
        <button type="submit" class="save btn btn-default">Add Rider</button>
    </form>

dob字段是唯一未从数据库正确填充的字段,它应以dd / mm / YYYY格式显示日期,例如“ 2010年10月9日”。实际上是显示默认的“ dd / mm / YYYY”。

1 个答案:

答案 0 :(得分:0)

我找到了解决该问题的方法,数据库中的日期以“%d /%m /%Y”格式返回,但是表单上的输入为“ date”类型,期望在格式更改为“%Y-%m-%d”,

widgets= {
            'dob': forms.DateInput(format=('%d/%m/%Y'), attrs={'class':'form-control', 'placeholder':'Select Date','type': 'date'})
        }

收件人:

widgets= {
            'dob': forms.DateInput(format=('%Y-%m-%d'), attrs={'class':'form-control', 'placeholder':'Select Date','type': 'date'})
        }

因此,生成的HTML表单从:

<input type="date" name="rider-dob" value="10/09/2010" class="form-control" placeholder="Select Date" required="" id="id_rider-dob">

收件人:

<input type="date" name="rider-dob" value="2010-09-10" class="form-control" placeholder="Select Date" required="" id="id_rider-dob">