Using Django with a bootstrap datetimepicker

I am having some trouble implementing the datepicker using the Django Bootstrap Datepicker widget. The datepicker is not appearing on the webpage ("welcome.html"). I have passed the form to the views and called the form in the webpage. Any assistance with this issue would be greatly appreciated.

forms.py

class DateForm(forms.Form):
todo = forms.CharField(
    widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=DatePicker(
    options={"format": "mm/dd/yyyy",
    "autoclose": True }))

def cleandate(self):
    c_date=self.cleaned_data['date_1']
    if c_date < datetime.date.today():
        raise ValidationError(_('date entered has passed'))
    elif c_date > datetime.date.today():
        return date_1
def itamdate(self):
    date_check=calendar.setfirstweekday(calendar.SUNDAY)
    if c_date:
        if date_1==date_check:
            pass
        elif date_1!=date_check:
            raise ValidationError('The Market will not hold today')
        for days in list(range(0,32)):
            for months in list(range(0,13)):
                for years in list(range(2005,2108)):
                    continue

views.py

def imarket(request):
    #CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER

    if request.method=='POST':
        form = DateForm(request.POST or None)
    #checks validity of the form
        if form.is_valid():
            itamdate=form.cleaned_data['date_1']
            return HttpResponseRedirect(reverse('welcome.html'))
    return render(request, 'welcome.html', {'form':form})

welcome.html

 {%  extends 'base.html' %}
{% load bootstrap %}
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script>
{% block content  %}
<title>Welcome</title>

    <form action = "{% url "imarket"}" method = "POST" role="form">
        {% csrf_token %}
        <table>
            {{form|bootstrap_horizontal}}
        </table>
        <div class = "form-group">
            <input type ="submit" value= "CHECK" class="form control"/>
        </div>
    </form>

{% endblock %}

Answer №1

After encountering issues with the Bootstrap datepicker, I decided to integrate the jQuery datepicker directly into my forms.py file. I found a helpful solution that guided me through the process.

class DateForm(forms.Form):
todo = forms.CharField(
    widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}))

Subsequently, I made changes to my welcome.html file:

{%  extends 'base.html' %}
{% load bootstrap %}


{% block content  %}
<title>welcome</title>

    <form action = "{% url "imarket"}" method = "POST" role = "form">
        {% csrf_token %}
        <table>
            {{form|bootstrap}}
            <script>
    $(document).ready(function() {
        $('.datepicker').datepicker();
    });
</script>
        </table>
        <div class = "form-group">
            <input type ="submit" value= "CHECK" class="form control"/>
        </div>
    </form>

{% endblock %}

Answer №2

It is important to initialize the datepicker in the HTML page for proper functionality.

Answer №3

For anyone utilizing bootstrap, the datepicker can be obtained by downloading it from Datetimepicker for Bootstrap 4.

Next, in the head section of your code, make sure to include:

  1. font awesome css
  2. boostrap4 css
  3. bootstrap-datetimepicker.min.css

In the body section, ensure you have included:

  1. moment.min.js
  2. bootstrap.min.js
  3. bootstrap-datetimepicker.min.js

Define your form as follows:

from django import forms

class DateRangeForm(forms.Form):
    start_date = forms.DateTimeField(required=True)
    end_date = forms.DateTimeField(required=True)

In your template, render the form like this:

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ dt_range_form }}
    <input class="btn btn-primary btn-sm" type="submit" value="Refresh">
</form>

Add the following script snippet to enable the datetimepicker:

$("#id_start_date").datetimepicker();

You should now have your datetimepicker up and running! If you encounter any issues with the Time icon not displaying correctly, don't forget to debug it.

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

The npm script encounters an error, yet fails to provide any helpful information

When I try to execute the jest command to run my tests, I am encountering a very obscure error message. Is there a way to extract something meaningful from node error messages or am I just misinterpreting the output? 0 info it worked if it ends with ok ...

Employing featherlightGallery.js without the need for anchor tags

I've been experimenting with the FeatherlightGallery plugin for a lightboxing feature on an image slider. The slider contains images directly, without anchor tags wrapping them. However, I'm facing an issue where clicking next/prev doesn't l ...

Storing data in JSON format and retrieving it using Javascript

My challenge involves plotting a chart using values from an object's list in my view with High Chart. However, I face the issue of accessing my model from JavaScript. public class MortgageCalculator { public List<double> interest_month = new ...

In Django 1.8, there is the capability to include regular expressions for URLs within the urls

I am struggling to pass the current URL to my view so that I can redirect back to the original page I came from. When sending parameters, I include "pk," which is the key number for my operation, and "uri," which represents the current URL. In my urls.py ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Delete an <li> element upon clicking a span tag

I've been attempting to fadeOut some <li> elements, however I haven't had any success. Here's my code below: <li class="lclass" id="1"> First Li <span class="removeit" id="1" style="color:#C00;">Remove</span> ...

Has the Field Validity Been Verified and Are all Fields Completed Prior to Submitting?

I have made changes to this question and am seeking clarification. In my project, I have a form with multiple fields, some of which require regex validation. Currently, I have a function that checks if all fields are filled before enabling the submit butto ...

What are some creative ways to customize the aesthetics of Angular UI pagination?

Currently, I am utilizing Angular UI 2.5.0 for pagination on my website. I am interested in customizing the look of the pagination bar to resemble the design shown in the image below. Current Pagination Style: https://i.sstatic.net/Z6D0Y.png Desired Cus ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Local copies of the Javascript game will have objects spawn in the game, but when uploaded the objects

I'm currently developing a simple Javascript game where the objective is to avoid falling objects using GameQuery. The game features frequent enemy spawns and occasional power-ups. I noticed that the power up spawn function is essentially a duplicate ...

Learn how to assign unique IDs to each input radio field in a Grails GSP radiogroup

Is there a way to assign a unique id for each input attribute in a GSP Grails application? <g:radioGroup id="x"> ${it.label} ${it.radio} </g:radioGroup> It seems that using id="x" is not functioning as expected. ...

Is there a way to combine properties from two different objects?

I am working with several JavaScript objects: { x: 5, y: 10, z: 3 } and { x: 7, y: 2, z: 9 } My task is to add these two objects together based on their keys. The resulting object should look like this: { x: 12, y: 12, z: 12 } Do you ...

Initialize an array containing five zero elements

How can I initialize an array with 5 zero elements in JavaScript without using the classic var arr = [0, 0, 0, 0, 0] method? I've tried a few variations: var arr = new Array(5).map(() => 0); var arr = new Array(5).map(function () {return 0;}); va ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Do Material-UI pickers only validate on blur, not on change events?

When you type inside the DatePicker component, validation is triggered immediately. Is there a way to trigger validation on blur instead of onChange when using @material-ui/pickers with material-ui v4 Passing the value to the blur function should work a ...

Modify appearance of text depending on input (HTML & JS)

I am currently working on building an HTML table using Django. My goal is to dynamically change the color of numbers in the table to red when they are negative and green when they are positive. I understand that JavaScript is required for this functionalit ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Utilizing Django to dynamically show fields based on the selected option in a list box

I am looking to only display the web checkboxes (days) when the user selects the weekly option in a form. Should this conditional logic be implemented in the view, template, or form? Can anyone provide an example to illustrate how this can be achieved? ...

In Swift version 2.1, the DatePicker's setDate function does not accurately set the date to the current day and

Having trouble setting the minimum date to the current day on the date picker and then setting the time to 7pm or 19:00 for better user experience. Despite setting the minimum date, the time doesn't seem to be updating correctly. If I remove the minim ...