Search code examples
pythondjangodjango-generic-views

django update view not showing date input (previous) values


when I go to the update page, all previous values are shown except date inputs (deadline and reminder).
how can I fix it?

At first I didnt use TaskCreationForm for TaskUpdateView considering django will handle it automatically, but then the date inputs became normal text inputs and therefore no datepicker would appear when clicking on the textbox.
I thought it was for the widgets that I had used so I decided to use TaskCreationForm for both creation and update.

models.py

class Task(models.Model):
    deadline_date = models.DateTimeField(verbose_name='Deadline')
    status = models.BooleanField(verbose_name='Task Status', default=False)
    reminder = models.DateTimeField(verbose_name='reminder')
    class Meta:
        verbose_name_plural = 'Tasks'
        ordering = ('-deadline_date',)
        db_table = 'task'

forms.py

class DateInput(forms.DateInput):
    input_type = 'datetime-local'


class TaskCreationForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ('title', 'deadline_date', 'description', 'reminder')
        labels = {
            'reminder': 'remind me'
        }

        widgets = {
            'deadline_date': DateInput(),
            'reminder': DateInput(),
            'description': forms.Textarea(attrs={'cols': 80, 'rows': 5})
        }

views.py

class TaskCreateView(CreateView):
    model = Task
    form_class = TaskCreationForm
    template_name = 'mysite/add_task.html'
    success_url = reverse_lazy('mysite:home')

    def post(self, request, *args, **kwargs):
        task_form = TaskCreationForm(request.POST)
        if task_form.is_valid():
            cd = task_form.cleaned_data
            current_user = request.user
            task = Task(title=cd['title'], description=cd['description'],
                        user=current_user, deadline_date=cd['deadline_date'],
                        reminder=cd['reminder']
                        )
            task.save()
        return redirect('mysite:home')


class TaskUpdateView(UpdateView):
    model = Task
    form_class = TaskCreationForm
    # fields = ('title', 'deadline_date', 'reminder', 'status', 'description',)
    template_name = 'mysite/edit_task.html'

Solution

  • After weeks of searching and struggling, I found that in order to show the previous date, I have to send the date in a specific format to Django template: "year-month-dayThour:minute" for example: "2018-06-12T07:30". But Django by default, sends dates to template in another format(in the given example: June 11, 2018, 7:30 a.m.) So in order to fix this problem, I used Django date filter
    I changed value to this:value="{{form.deadline_date.value | date:'c'}}"(in template)