2017-09-03 47 views
0

(對不起,我英文不好)Django的 - 對象不保存日期的格式,我需要

我有一個問題,當我試圖保存日期,但只在一個模型中的所有其他機型保存日期完善。但這種特定的模式保存爲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的日期選擇這裏的日期是腳本

<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(毫米/日/年)9

我不明白爲什麼,因爲所有其他型號,我有存儲日期完美!

編輯:(時間固定)

我修復它轉換字符串我在調度功能使用這種從GET接收與所述日期DD/MM/YYY在日期對象

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

從現在開始解決了這個問題,但我仍然試圖理解爲什麼這個模型可以節省時間,因爲所有其他形式和模型都能夠完美實現。我收到想法。

回答

0

你應該重寫DATE_FORMATsettings.py

USE_L10N = False 
DATE_FORMAT = 'd/m/Y' # Your desired date format 

如文檔說:

注意,如果USE_L10N設置爲True,那麼語言環境決定的格式具有更高的優先級和將被應用。

所以這就是爲什麼你也應該設置USE_L10N = False

注意:這設置日期格式全球

+0

同樣的結果,我將L10N設置爲False並使用該日期格式d/m/Y並得到相同的結果,唯一的區別是現在Django Admin顯示09/02/2017(我嘗試保存02/09/2017),如果我使用L10N真正的管理員秀9,2017年2月...但要存儲在數據庫中的數據仍然不好 – marcosgue

+0

我在表格中添加一個打印,日期進行得很完美我得到這個 02/09/2017 並在form_valid函數中添加其他打印,並且存在日期存在的問題: 2017-02-09 – marcosgue