如何将日期变量传递给表单

时间:2013-05-09 08:10:26

标签: django django-models django-templates django-views

views.py

def when(request):
user = request.user
report = Report.objects.get(user=request.user)
reportform = ReportForm(instance=report)

settings = Settings.objects.get(user=request.user)
settingsForm = SettingsForm(instance=settings) 
settings=Settings.objects.get(user=2)
if settings.date_format == '0':
    date=datetime.datetime.strptime('10/31/2012','%m/%d/%Y').strftime('%d/%m/%Y')

else:
        date=datetime.datetime.strptime('31/10/2012','%d/%m/%Y').strftime('%m/%d/%Y')  
if request.method == 'POST':            
    reportform = ReportForm(instance=report,data=request.POST)
    if reportform.is_valid():
        report = reportform.save(commit=False) 
        report.user = request.user
        report.save()
        return redirect('/member/media/')

return render_to_response('incident/when.html',{
              'newreport_menu': True, 
              'form': reportform,
               'date':date,


               },
               context_instance=RequestContext(request))

models.py

class Report(models.Model):
    user = models.ForeignKey(User, null=False)
    manual_date = models.DateField('Another date', null=True, blank=True)

template.html

 {{ form.manual_date }}{{ form.manual_date.errors }}{{ date }}

以上视图将模板中的硬编码日期值呈现为变量。而不是硬编码,可以在模型中显示来自manual_date字段的日期。如何在reportform中传递它。

1 个答案:

答案 0 :(得分:0)

我认为你想要这个,而不是使用硬编码的日期使用report.manual_date

if settings.date_format == '0':
    date = report.manual_date.strftime('%d/%m/%Y')
else:
    date = report.manual_date.strftime('%m/%d/%Y')