Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data format value changes in database

forms.py

DATE_INPUT_FORMAT = (
    ('%d/%m/%Y','%m/%d/%Y')
)

class ReportForm(forms.ModelForm):
    manual_date = forms.DateField(input_formats = DATE_INPUT_FORMAT,
                      widget=forms.DateInput(format = '%d/%m/%Y'))  

1.Date format should change depend upon the value in database,if value is in db,it shows the 1st format and for none ,else part is executing.

2.Formats are changing depends upon the condition.

3.I am facing problem here,if the input format is of this (%m/%d/%Y),on form post the value of date gets interchange and saved in database.If the given date is 07/06/2013 -->7th june 2013,after form post it is viewed in the field as 06/07/2013 -->6th july 2013.It is not working properly.

Need help to solve this issue.

Thanks

like image 527
user2086641 Avatar asked Dec 08 '22 14:12

user2086641


1 Answers

Simplest solution is create factory for presenting form:

def ReportFormFactory(date_format):
    class ReportForm(forms.ModelForm):
       manual_date = forms.DateField(
          input_formats=[date_format],
          widget=forms.DateInput(format=date_format)
       )
    return ReturnForm

and then in view:

if int(dateformat):
    ReportForm = ReportFormFactory('%m/%d/%Y')
else:
    ReportForm = ReportFormFactory('%d/%m/%Y')

dates should be changed to strings only at presention stage in widget, in other places left them as datetime or date objects

like image 193
dswistowski Avatar answered Dec 11 '22 07:12

dswistowski