Django - 对象不以我需要的格式保存日期

时间:2017-09-03 16:23:16

标签: django django-models datepicker django-forms

(抱歉我的英语不好)

我在尝试保存日期时出现问题但只在一个模型中,所有其他模型都保存完美日期。但是这个特定的型号可以节省mm / dd / yyyy,我需要dd / mm / yyyy

这是模型

class CashClosing(models.Model):
    # Relations
    # Attributes - Mandatory
    date = models.DateField(
        verbose_name=_('date'),
    )
    cash_incomes = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name=_('cash incomes'),
    )
    cash_expenses = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name=_('cash expenses'),
    )
    cash_diff = models.DecimalField(
        max_digits=7,
        decimal_places=2,
        default=0,
        verbose_name=_('cash difference'),
    )
    real_cash = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name=_('real cash'),
    )
    next_initial_cash = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name=_('next initial cash'),
        help_text='Ingrese aquí el monto con el que abrirá la próxima caja'
    )
    balance = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name=_('balance'),
    )
    # Attributes - Optional
    # Object Manager
    objects = managers.CashClosingManager()
    # Custom Properties

    # Methods
    def get_absolute_url(self):
        return reverse(
            'cash_closings:detail',
            kwargs={'id': self.id}
        )

    # Meta and String
    class Meta:
        verbose_name = _("Cash Closing")
        verbose_name_plural = _("Cash Closings")
        ordering = ('date',)

这是表格

class CashClosingForm(forms.ModelForm):

class Meta:
    model = CashClosing
    fields = [
        'date',
        'cash_diff',
        'next_initial_cash',
    ]

def __init__(self, *args, **kwargs):
    date = kwargs.pop('date')
    super(CashClosingForm, self).__init__(*args, **kwargs)

    self.helper = FormHelper()
    self.helper.layout = Layout(Field('date', type='hidden', value=date))
    self.helper.add_input(Submit(
        'submit',
        'Cerrar Caja',
        css_class="btn btn-primary btn-block")
    )

这里是视图

class CashClosingCreateView(CreateView):
model = CashClosing
form_class = CashClosingForm
template_name = "cash_closings/cashclose.html"

def dispatch(self, request, *args, **kwargs):

    d = self.request.GET['date']
    # Tomamos los gastos e ingresos del día
    self.today_incomes = Income.objects.today_incomes(day=d).aggregate(
        sum=Sum('amount')
    )['sum']
    self.today_expenses = Expense.objects.today_expenses(day=d).aggregate(
        sum=Sum('amount')
    )['sum']
    # Si no hay ingresos en el día se asigna 0
    if self.today_incomes is None:
        self.today_incomes = 0
    if self.today_expenses is None:
        self.today_expenses = 0

    self.today_balance = self.today_incomes - self.today_expenses

    # Tomamos la caja inicial si existe y sino seteamos 0
    try:
        last_cash_close = CashClosing.objects.latest('id')
        self.initial_cash = last_cash_close.next_initial_cash
    except ObjectDoesNotExist:
        self.initial_cash = 0

    if request.method.lower() in self.http_method_names:
        handler = getattr(
            self,
            request.method.lower(),
            self.http_method_not_allowed
        )
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get_form_kwargs(self):

    kwargs = super(CashClosingCreateView, self).get_form_kwargs()
    kwargs.update({'date': self.request.GET['date']})
    return kwargs

def get_context_data(self, **kwargs):

    context = super(CashClosingCreateView, self).get_context_data(**kwargs)

    context['today_incomes'] = self.today_incomes
    context['today_expenses'] = self.today_expenses
    context['today_balance'] = self.today_balance
    context['initial_cash'] = self.initial_cash
    context['cash'] = self.today_balance + self.initial_cash

    return context

def form_valid(self, form, **kwargs):
    cc = form.instance
    # Asignamos los valores que no vienen con el formulario
    cc.cash_incomes = self.today_incomes
    cc.cash_expenses = self.today_expenses
    cc.real_cash = self.today_incomes - self.today_expenses + cc.cash_diff + self.initial_cash - cc.next_initial_cash
    cc.balance = self.today_incomes - self.today_expenses + cc.cash_diff

    return super(CashClosingCreateView, self).form_valid(form)

问题是这样,例如我发送使用获取所选日期

  

现金倒闭/创建/?日期= 03%2F09%2F2017

我使用JQueryUI选择日期datepicker这里是脚本

<script>
  $( function() {
    $( "#id_date" ).datepicker({
      dateFormat: 'dd/mm/yy'
    }).datepicker("setDate", new Date());
  } );
</script>

并将其放入隐藏的输入HTML中使用此值

<input type="hidden" name="date" value="03/09/2017" id="id_date">

但是当我在DB Django商店保存2017年3月9日(mm / dd / yyyy)时

我不明白为什么,因为我所有的其他模型都存储日期完美!

编辑:(暂时修复)

我修复了在调度函数中使用此函数将日期对象中的日期dd / mm / yyy从GET接收的字符串转换为

d_string = self.request.GET['date']
d = datetime.datetime.strptime(d_string, '%d/%m/%Y').date()
self.d = d

从现在开始解决了这个问题,但我仍然试图理解为什么这个模型可以节省日期,因为所有其他形式和模型都很完美。我收到了想法。

1 个答案:

答案 0 :(得分:0)

您应该覆盖fatal error: runtime: out of memory

中的DATE_FORMAT
settings.py

正如文档中所述:

  

请注意,如果USE_L10N = False DATE_FORMAT = 'd/m/Y' # Your desired date format 设置为USE_L10N,那么区域设置指定的格式具有更高的优先级,而是将应用。

因此,您应该设置True

注意:这会将日期格式设置为全局