2017-10-14 129 views
0

我正在創建一個使用ModelForm的編輯視圖,並且希望表單的日期字段以下列格式顯示:「%d /%m /%Y「。使用ModelForm格式化來自DateField的數據 - Django 1.11

但是,不管我做什麼,當調用編輯頁面時,日期以格式「%m-%d-%Y」顯示。

models.py

class Pessoa(models.Model): 
    nome = models.CharField(max_length=255, null=False) 
    sobrenome = models.CharField(max_length=255, null=False) 
    cpf = models.CharField(max_length=14) 
    data_nascimento = models.DateField() 
    rg = models.CharField(max_length=15, null=False) 
    responsavel = models.ForeignKey('Pessoa', related_name='dependentes', blank=True, null=True) 
    foto = models.ImageField(upload_to='pessoas') 

    usuario_alteracao = models.CharField(max_length=255, blank=True, null=True) 

    data_criacao = models.DateTimeField(auto_now_add=True) 
    data_alteracao = models.DateTimeField(auto_now=True) 

settings.py(DATETIME_INPUT_FORMATS和DATE_INPUT_FORMATS)

DATE_INPUT_FORMATS = ['%d/%m/%Y'] 

DATETIME_INPUT_FORMATS = ['%d/%m/%Y'] 

pessoas_forms.py

class PessoaForm(ModelForm): 

    data_nascimento = DateField(
     input_formats=settings.DATE_INPUT_FORMATS, 
     widget=DateInput(attrs={'class': "input", 'placeholder': "Ex.: dd/mm/aaaa", "OnKeyPress":"mask('##/##/####', this)"})) 

    class Meta: 
     model = Pessoa 
     fields = ['nome', 'sobrenome', 'cpf', 'data_nascimento', 'rg', 'foto'] 
     exclude = ['usuario', 'usuario_alteracao', 'data_criacao', 'data_alteracao', 'responsavel'] 
     widgets = { 
      'nome': TextInput(attrs={'class': "input"}), 
      'sobrenome': TextInput(attrs={'class': "input"}), 
      'cpf': TextInput(attrs={'class': "input", 'placeholder': "Ex.: 000.000.000-00", "OnKeyPress":"mask('###.###.###-##', this)"}), 
      'rg': TextInput(attrs={'class': "input"}), 
     } 

views.py

def get(self, request, id): 

     try: 
      pessoa = Pessoa.objects.get(id=id) 

     except ObjectDoesNotExist: 
      messages.warning(request, 'Not Found.') 
      return redirect('pessoas') 

     pessoa_form = PessoaForm(instance=pessoa) 

     context = { 
      'pessoa_form': pessoa_form, 
      'id': pessoa.id 
     } 

     return render(request, 'sagasystem/configuracoes/pessoas/editar_pessoa.html', context) 
+0

您是否嘗試過使用DateInput小部件爲您的日期字段? https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#timeinput – Ben

+0

是的,我試過了。你可以在上面的'people_forms.py'中看到。 – mdcg

+0

您的設置和表單看起來不錯,最有可能的是您的模板中有一些錯誤,如果您可以發佈它,也許我可以幫助調試 – codeadict

回答

1

你需要告訴控件如何顯示日期,使用format說法。

data_nascimento = DateField(
    widget=DateInput(format='%d/%m/%Y', attrs={'class': "input", 'placeholder': "Ex.: dd/mm/aaaa", "OnKeyPress":"mask('##/##/####', this)"}))