Enhancing Django Model Form: Setting a Default Value for Date Picker

My Django model form currently has a date picker that functions perfectly. However, I am looking to set an initial (default) value for it. Below is my current code:

class DatePickerInput(forms.DateInput):
        input_type = 'date'
        
class PDFClassificationForm(forms.ModelForm):  
    
    class Meta:  
        model = Documents
        fields = [
                  'id_documenttype',
                  'dateenvoi',,
                  'comment']
        widgets = {
            'dateenvoi' : DatePickerInput(),
        }

I attempted to add 'initial' as a parameter to DatePickerInput() like this:

widgets = {
            'dateenvoi' : DatePickerInput(initial= datetime.now().strftime('%d/%m/%y %H:%M:%S')),
        }

Unfortunately, this method was unsuccessful. Any suggestions on how to achieve this?

Answer №1

Here is a helpful code snippet for you to try out:

import datetime
    
class PDFForm(forms.ModelForm):  
    
    class Meta:  
        model = Document
        fields = [
              'document_type',
              'date_sent',
              'comment',
               ]
        widgets = {
            'date_sent' : DatePickerInput(widget=forms.TextInput(attrs={'value': datetime.now().strftime('%d/%m/%y %H:%M:%S')})),
        }
        

Answer №2

Make sure to include your desired initial value within the form in the view (views.py)

import datetime
from django.views.generic import TemplateView

from .forms import PDFClassificationForm

class CustomView(TemplateView):
    template_name = 'your_directory/your_template_name.html'
    form_class  = PDFClassificationForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        return render(request, self.template_name, {'form': form})

     def get_context_data(self, *args, **kwargs): 
        context = super(CustomView, self).get_context_data(*args, **kwargs)
        request = self.request
        context["form"] = PDFClassificationForm(request.POST or None, initial={ "dateenvoi": datetime.today) 
        return context

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic templates for table rows in AngularJS directives

Is it possible to dynamically load an AngularJS Directive templateUrl while working within a table? In my scenario, I have the following HTML structure where I am repeating a tr element with a fw-rule directive: <tbody> <tr ng-repeat="rule in ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Organize Python dictionaries by the equal key in Django/Python

I am currently in the process of organizing two Python dictionaries into an HTML array like this: #Headers DictA = {'value': 'valeur', 'name': 'nom' } #Data DictB = {'value': '456', 'name&a ...

Hide Panels on amcharts

Is there a way to toggle the visibility of panels without having to delete and recreate them each time? I haven't been able to find any examples online. A big thank you to @Robbert for the helpful reply! I found a way to hide a panel using this code ...

Temporarily withhold the execution of useEffect until useSelector successfully fetches data from the Redux store within a React

I have a functional React component called Tasks_1. Initially, I retrieve the userId from the Redux store, which is working successfully. After obtaining the userId from the Redux store, I want to use it in a useEffect hook to fetch data from the backend. ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Invalid regular expression error encountered in Django

I am encountering an issue with my urlpatterns as seen below. Whenever I attempt to run the program, I receive the following error... ImproperlyConfigured at / "^product/(?p<product_slug> [-\w]+)/$" is not a valid regular expression: unexpecte ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

I'm facing an issue in React where using onChange is causing all DOM elements to be cleared. The input form functions correctly when used with a button, but for some reason, the onChange event does not

Currently, I'm working on a grid that can be resized using two input fields in the application. The setup involves an input for cells across, an input for cells down, and a button to set the grid, which is functioning well. However, I would like to ma ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

The challenge with handling matrix arrays in Javascript

In my simplified drag and drop shopping cart project using jqueryui, I am encountering an issue with adding data (id, name, price) to an array. Despite trying various methods to add the data array to the main container, I consistently encounter the error ...

Failure occurs when attempting to compare multidimensional arrays to locate the correct index for use in another multidimensional array

Hey there! I'm reaching out because I need assistance with a Javascript function: Basically, I have an input array that I want to compare to another array and based on the result, return something. However, for some reason my comparison is not yieldi ...

How can I retrieve the current active filters when using the DataGrid component from @material-ui/lab?

I'm currently working on integrating material-ui's data grid into one of my pages. The main objective is to capture the state of filters and sorts for all columns, and save them as a link at the top of the page. This way, users won't have to ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Resize a division to fill the window while maintaining original proportions

Is there a way to resize a div so that it fills the entire browser viewport while maintaining its aspect ratio? How can I achieve this using CSS, JQuery, or both? ...

Tips on implementing href with "javascript:window.open..." in AngularJS

I've been trying to utilize an anchor tag in my HTML code to open a new modal browser window with a URL retrieved through an Angular value like this: <a href="javascript:OpenPopUpPage('{{listing.Linktest}}');">Test Link</a> Alt ...

Encountering the issue of "unable to retrieve" when attempting to create an API in Express.js

I am currently developing a REST API using express js, but I encountered an issue with the error message "Cannot GET /api/bears". Here is my code snippet: server.js var express = require('express'); var app = express(); var bodyParser = require ...