How to set Django model date field default value to future date?

Indika Rajapaksha

I'm trying to set the default value for a Date field to a future date with respect to today. However, it gives me the following warning when I set it as below.

return_date = models.DateField(default=(timezone.now() + timedelta(days=1)))

booking.Booking.return_date: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for 
this field. This may not be what you want. If you want to have the 
current date as default, use `django.utils.timezone.now`

Same warning with the following code.

return_date = models.DateField(default=(date.today() + timedelta(days=1)))

What is the correct way to do this?

Thanks.

Ehsan Nouri

You are giving it a fixed time(cause you are calling the timezone.now() so its returned value will be the default) you should pass the function to the default without calling it, like this

def return_date_time():
    now = timezone.now()
    return now + timedelta(days=1)

and in your field:

return_date = models.DateField(default=return_date_time) 
### dont call it, so it will be evaluated by djanog when creating an instance

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How to show default today date and future date disable in jquery

How to set default date in DateField?

How to set default value to None for Django choices form field

How to pass django model field value as an argument to callable which is default of field in the same model?

how to set django model field value based on value of other field in the different model

Set default value for date selector in phoenix framework to current date

What is the default value of django's model field options ``blank`` and ``null`` when they're not set?

How to set default current date in jpa for mysql

How to set default date in datetimepicker with ngmodel?

how to set the default date of the day in vue js

How to set a field constant in a django model

Invalid default value for 'create_date' timestamp field

Using mongo-kafka as sink connector, how do I set a field's value to be of Date type?

How to set the value of date input field using data binding in Angular 5?

Define schema with default date 12 months in the future

How to Compare the future date with current date in angular?

Bootstrap date field input value set using jquery

Django Admin Form: Set the default value of a readonly field

Django ModelForm Custom Date Field

How to set a specific default time for a date picker in Swift

How to set a default date and time to PrimeNG p-calendar

How can I set the default date in input portion?

Laravel: how to set date format on model attribute casting?

I want to set date into my html date field. I have used mutator in Laravel, Now how can I set date in the date field to edit a record?

Django - how do I override default date formats per locale?

How can I retrieve only the value of a field in model A as the field value in model B in django

Django date field derived from timestamp field

How to make button enable, when there is value in input date field

how to get field value in django admin form save_model

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo