Giter Site home page Giter Site logo

monim67 / django-bootstrap-datepicker-plus Goto Github PK

View Code? Open in Web Editor NEW
220.0 10.0 57.0 377 KB

Bootstrap3/Bootstrap4/Bootstrap5 DatePickerInput, TimePickerInput, DateTimePickerInput, MonthPickerInput, YearPickerInput with date-range-picker functionality for django >= 2.0

Home Page: https://pypi.python.org/pypi/django-bootstrap-datepicker-plus

License: MIT License

Python 52.05% HTML 31.30% CSS 2.62% JavaScript 14.03%
django date-picker bootstrap-datepicker django-widget datetimepicker daterangepicker timepicker django-forms

django-bootstrap-datepicker-plus's People

Contributors

amethystdeceiver avatar cclauss avatar claudep avatar dzhuang avatar flipperpa avatar lauri-openscop avatar monim67 avatar morenoh149 avatar mthuurne avatar pbucher avatar sterliakov avatar thecthulhukid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-bootstrap-datepicker-plus's Issues

widget breaks submit button

Hi - not sure if this is an issue or not - probably my implemenation (I'm a beginner).

When I include the widget in my forms.py the submit button on my template no longer works - works fine when I remove datetimepicker. I wondered if there's a clash with the javascript somewhere? Could you take a look? I've added you as a colab for the project

Also, is there any way of making todays date autopopulate the field?

Thank you - it's a great app

David

Event handling

I would truly appreciate a good advice in my problem. I want to handle events of the datepicker, but events aren't covered in the documentation.

I only need a simple JS function call for HTML DOM events, so I expected this code to work:

self.fields['my_calendar'].widget.attrs['onchange'] = 'checkDate();'

It renders correctly in HTML, but the onchange event is never generated! Same with onselect. Is there anything I can do?

date-picker button is not clickable and the calendar does not open

The widget is working in one of my Model Form in one page. But in another of my Model form in another page it is not working. The button is not clickable and the calendar does not open.

Here is my template

{% extends 'base.html' %}
{% block body %}
{% load bootstrap3 %}
{% block extrahead %}       {# Extra Resources Start #}
{{ form.media }}            {# Form required JS and CSS #}
{% endblock %}              {# Extra Resources End #}


<h2>Complete | Edit your profile </h2>
{{ fielderrors }}
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% bootstrap_form user_form %}
    {% bootstrap_form profile_form %}
    <input style="float:right" type="submit" value="Save Changes" class="btn btn-success"/>

</form><br/><br/><br/><br/>

{% endblock %}

forms.py

class ProfileEditForm(forms.ModelForm): #UserProfileForm or ProfileEdit
    bio = forms.TextInput()

    class Meta:
        model = Profile
        fields = ('city', 'state', 'country', 'street_address', 'zip_code', 'phone_number', 'age', 'profile_image',
                  'bio', 'bio_images')
        widgets = {
            'age': DatePickerInput(),
        }

Add support for themes

Is your feature request related to a problem? Please describe.
This is a nice tool and easy to use, however it doesn't seem to work with bootstrap themes. For example, with a dark theme, the picker's background is white and the theme I'm using makes the text white, so nothing shows up.

Describe the solution you'd like
I can add to my app's CSS something like this:

.bootstrap-datetimepicker-widget {
    background-color: #222 !important;
}

This works for the project I'm working on now, but this is a bit clumsy and it would be nice for themes to be supported without needing to write custom CSS.

Describe alternatives you've considered
See above.

Additional context
Themes are a pretty important part of bootstrap and I'm surprised they're not better supported. Maybe they are and I'm just overlooking it?

This is the theme I'm using: https://bootswatch.com/darkly/

Button not working

I can see template with field date but the button on the right side with the calendar is not working...
Thanks for help

needed for using bootstrap_datepicker_plus

BOOTSTRAP3 = {
'include_jquery': True,
}
and add 'bootstrap_datepicker_plus', in installed apps

html file:

 {%  extends 'imports/base.html' %}
{%  load bootstrap3 %}
<!-- necessaire pour date picker -->
{% block extra_css %}
{{ form.media.css }}
{% endblock %}

{% block extra_js %}
{{ form.media.js }}
{% endblock %}
<!-- Fin date picker -->
{%  block title %}Imports Company{%  endblock %}
{%  block heading %}<h3 class="page-header-center">Creation Company</h3> {%  endblock %}
<hr>
<hr>
{% block page %}
   <form method="POST">
       {%  csrf_token %}
       <div class="col-lg-4 col-md-4 col-sm-4 content">
       {% bootstrap_form company_form %}
       <button type="submit" class="btn btn-pink pull-right">Create</button>
       </div>
   </form>
{% endblock %}

imports/base.html:

{%  load staticfiles %}
{% load bootstrap3 %} {# import bootstrap4/bootstrap3 #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<!-- Necessaire pour bootstrap datepicker -->
{% bootstrap_css %} {# Embed Bootstrap CSS #}
{% block extra_css %}
{{ form.media.css }}
{% endblock %}
<!-- fin du code boots trap datepicker -->
    <title>{% block title %}{% endblock %}</title>


    <link rel="stylesheet" href="{%  static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{%  static 'css/style.css' %}">
    <script src="{%  static 'js/bootstrap.min.js' %}"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>
<body>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-2 col-md-2 col-sm-2 sidebar">
             {%  block sidebar %}{%  endblock %}
        </div>
        <div class="col-lg-10 col-lg-offset-2 col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 content">
                {% block heading %}{% endblock %}
                {%  block page %}{% endblock %}
        </div>
    </div>

</div>


<!-- Necessaire pour bootstrap datepicker -->
{% bootstrap_javascript jquery='full' %} {# Embed Bootstrap JS+jQuery #}
{% block extra_js %}
{{ form.media.js }}
{% endblock %}
<!-- fin du code boots trap datepicker -->


</body>
</html>

and forms.py:

class CompanyForm(forms.ModelForm):
    class Meta:
        model = Company
        fields = ("company_name", "fiscal_end_of_year")
        widgets = {
            'fiscal_end_of_year': DatePickerInput(),  # default date-format %m/%d/%Y will be used
        }

models.py:

class Company(models.Model):
    company_id = models.IntegerField(default=170)
    company_name = models.CharField(max_length=100, null=False)
    fiscal_end_of_year = models.DateField()

Can't get an alert whenever the date on a datepicker changes

Hello. I am trying to do an action whenever a date is picked on the datepicker.

Currently, my date picker portion of the html file looks like this (generated automatically by using the widget on a DateField)

<div class="input-group date">
    <input type="text" name="primeira_emissao_dia" required class="form-control form-control" id="id_primeira_emissao_dia" dp_config="{&quot;linked_to&quot;: null, &quot;options&quot;: {&quot;showTodayButton&quot;: true, &quot;showClear&quot;: true, &quot;showClose&quot;: true, &quot;format&quot;: &quot;YYYY-MM-DD&quot;}, &quot;picker_type&quot;: &quot;DATE&quot;, &quot;id&quot;: &quot;dp_1&quot;}"/>
    <div class="input-group-addon input-group-append" data-target="#datetimepicker1" data-toggle="datetimepickerv">
        <div class="input-group-text"><i class="glyphicon glyphicon-calendar"></i></div>
    </div>
</div>

For now, I would just like to be able to print in the console (or get an alert) whenever a date is chosen.

I attempted to add this after the body:

<script>
$("div.input-group.date").on('dp.change', function(e) {
      alert("Hello there.");
  });
</script>

And changing the date had no effect. I also tried to do it like this:

<script>
  $(document).ready(function () {
          (...)
          $("div.input-group.date").on('dp.change', function(e) {
            alert("Hello there.");
          });
      });
</script>

Again, with no effects.

The only thing that I noticed is that an event tag appears (on Inspect element, with Firefox on Linux) on the div, with a dp element on it, referencing my website:

example_event_change

What am I doing wrong? If there is more information needed, I'll be more than glad to offer it.

Datepicker rendering

I have followed all the instructions but was unable to make the datepicker show up.
After some research I've found your answer in https://stackoverflow.com/questions/48576784/django-form-django-bootstrap-datepicker-plus-is-not-rendering-datepicker

In this answer there is a slightly different instruction:

To include this at the form template made it work:

{% block extrahead %}   {# Extra Resources Start #}
{{ form.media }}        {# Form required JS and CSS #}
{% endblock %}          {# Extra Resources End #}

For me it worked. I would suggest to include this as part of the instructions in the readme file.
Otherwise, thanks for the excelent package.

Date Picker not showing

Describe the problem
A clear and concise description of what the scenario is.
I am unable to see the datepicker in my model form.
To Reproduce
Steps to reproduce the behavior:
my forms.py is as under**
{%extends 'mis/base.html'%}

{% load bootstrap4 %} {# import bootstrap4/bootstrap3 #}
{% bootstrap_css %} {# Embed Bootstrap CSS #}
{% bootstrap_javascript jquery='full' %} {# Embed Bootstrap JS+jQuery #}
{{ form.media }} {# Adds date-picker required JS and CSS #} -->

{% block content%}

Add / Modify Customer

{% csrf_token %}
{% bootstrap_form form %}
BACK CANCEL


{% endblock content%}

***my view.py is as under
def add_service_view(request):
template_name = 'mis/Add-service.html'
form = create_service_form()
if request.method == 'POST':
form = create_service_form(request.POST)
if form.is_valid():
form.save()
return redirect ('customer')
return render(request, template_name, {'form':form})

******my models.py is as under
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

Create your models here.

cust_type = [('CF','Confidential'),('OMR', 'OMR based'),('OTH', 'Any other')]
class customer_model(models.Model):
name = models.CharField("Name",max_length = 100, null= True)
address = models.CharField("Address",max_length = 200, null = True)
cust_type = models.CharField("Customer Type",max_length= 100, null = True, choices = cust_type)
start_date = models.DateField("Date",auto_now= False, auto_now_add = False)
cust_email = models.EmailField("Email Address",max_length = 100, null = True)
cust_phone = models.IntegerField("Phone Number",null = True)
cust_description = models.TextField("Customer Description",blank = True)
timestamp = models.DateTimeField(auto_now_add =True, auto_now =False)
Updated = models.DateTimeField(auto_now=True, auto_now_add = False)

Expected behavior
A clear and concise description of what you expected to happen.

Console errors

  • No error on django console.
  • No error on JavaScript console.

Paste-bin
The page is showing up but the date-picker calendar is not. The paste-bin link
of the HTML source of the page is http://...

Setup Information (please complete the following information):

  • OS: [e.g. Windows 10]
  • Browser [e.g. chrome, safari]
  • Browser version [e.g. 22]
  • Python version [e.g. 3.7]
  • Django version [e.g. 2.1]
  • Bootstrap version [e.g. 3/4]
  • jQuery version [e.g. 1.7.1]

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Icons about the calendar not showing correctly

Describe the problem
A clear and concise description of what the scenario is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Console errors

  • No error on django console.
  • No error on JavaScript console.

Paste-bin
The page is showing up but the date-picker calendar is not. The paste-bin link
of the HTML source of the page is http://...

Setup Information (please complete the following information):

  • OS: [e.g. Windows 10]
  • Browser [e.g. chrome, safari]
  • Browser version [e.g. 22]
  • Python version [e.g. 3.7]
  • Django version [e.g. 2.1]
  • Bootstrap version [e.g. 3/4]
  • jQuery version [e.g. 1.7.1]

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Setting 'locale' dynamically

Describe the problem
My users can have different locales. Therefore I need to set the locale of each widget dynamically on form creation. I couldn't find a solution to this in the documentation. If possible I'd like to get some input on my approach.

Setup Information (please complete the following information):

  • OS: Windows 10
  • Browser chrome, firefox
  • Python version 3.7
  • Django version 2.1
  • Bootstrap version 4

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Approach

forms.py

from django import forms
from bootstrap_datepicker_plus import DatePickerInput
from example.models import ExampleModel


class ExampleForm(forms.ModelForm):
    class Meta:
        model = ExampleModel
        fields = [
            'date',
        ]
        widgets = {
            'date': DatePickerInput(),
        }

    def __init__(self, *args, request=None, **kwargs):
        super().__init__(*args, **kwargs)
        if request:
            self.fields['date'].widget = DatePickerInput(options={'locale': request.LANGUAGE_CODE})

views.py

[...]
    form = ExampleForm(request=request)

Validation feedback doesn't appear when using django-bootstrap4

When a validation message is produced server-side by Django on a field that has been set to use DatePickerInput, the validation message will not appear even though it is present in the DOM. This is because of Bootstrap's CSS rule that requires the .invalid-feedback element to have the same parent as the .form-control.is-invalid element (the input element usually), but when using this widget the input element gets wrapped in a div and they no longer share the same parent.

Here's what the current HTML output (simplified, removing dp-config and such) looks like:

<div class="form-group end-timing is-invalid">
  <label for="id_account-end">End Date</label>
  <div class="input-group date">
    <input type="text" name="account-end" id="id_account-end" class="form-control is-invalid">
    <div class="input-group-addon input-group-append">
        <div class="input-group-text"><i class="glyphicon glyphicon-calendar"></i></div>
    </div>
  </div>
  <!-- Note the following div does not appear -->
  <div class="invalid-feedback">End date cannot be before the start date</div>
</div>

And here's how I can make it work when manually modifying the DOM. Note that the .invalid-feedback div gets moved to the end of the .input-group div:

<div class="form-group end-timing is-invalid">
  <label for="id_account-end">End Date</label>
  <div class="input-group date">
    <input type="text" name="account-end" id="id_account-end" class="form-control is-invalid">
    <div class="input-group-addon input-group-append">
        <div class="input-group-text"><i class="glyphicon glyphicon-calendar"></i></div>
    </div>
    <div class="invalid-feedback">End date cannot be before the start date</div>
  </div>
</div>

This may be due to a conflict with the django-bootstrap4 library as well, as there was an issue there with a similar cause that was merged to fix it, but I think that the fix for this problem probably lies here because of the way the datepicker template is outputting the relevant code blocks.

I'm just not familiar enough yet with Django templates and apps to propose a PR, just to be able to diagnose the underlying issue. Thanks for the help!

To Reproduce

  1. Create a form with a DatePickerInput widget.
  2. Cause the form to throw a ValidationError exception to create an .invalid-feedback message to appear after submitting the form.
  3. Observe that the datepicker widget does have the red border around it indicating an error, but the error message itself does not display.

Expected behavior
Validation messages (.valid-feedback or '.invalid-feedback) would appear if the field also has the corresponding .is-[in]valid` class applied.

Screenshots
Current behavior:
current

Expected behavior:
expected

Setup Information:

  • OS: macOS 10.14.4
  • Browser: All
  • Python: 3.7
  • Django: 2.2
  • Bootstrap: 4 (using django-bootstrap4)
  • jQuery: 3.31

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

How to Disable Past Dates and Time

Hi,

Any how I can do the following?

class ClientForm(forms.Form):
start_date = forms.DateField(widget=DatePickerInput) --> permanent disable past dates
start_time = forms.DateField(widget=TimePickerInput) --> permanent disable some hours and temporarily disable past hours

Thanks,
Chester

Unable to change options of datetimepicker within javascript

I'm attempting to change an option within the datetimepicker as a result of some user action, but I can't access the datetimepicker in javascript in the way that essentially 100% of sites recommend, which is the following:

 $(document).ready(function() {
    $('.input-group').datetimepicker({    
          console.log('I can now change options');
    });
 });

With the code above, the console.log statement never gets written. Is '.datetimepicker' the correct object to reference within django-bootstrap-datepicker-plus?

Thanks for your help!

Initial value of field not used

Describe the bug
When attempting to update a form where a date field already has a value the DatePickerInput widget doesn't display the previous value. The value is correctly passed to the widget and appears inside the input.

Once you select the widget it sets the date to today rather than the value.

Expected behavior
The initial value should be displayed when the form loads

Screenshots
Screenshot 2019-06-25 at 13 51 55

Screenshot 2019-06-25 at 13 52 26

Localization of DatePickerInput button titles missing or not applied

Describe the bug
When setting the locale, almost everything is translated. Months, Days, the week day order. But the interactive buttons titles aren't. Trying this out with de locale.

To Reproduce
Steps to reproduce the behavior:

  1. Localize a DatePickerInput Field 'date': DatePickerInput(options={'locale': 'de'}),
  2. Click on the field
  3. Hover over the interactive buttons
  4. See error

Expected behavior
I expect to see german as the tooltip.

Screenshots

image

Setup Information (please complete the following information):

  • OS: Windows 10
  • Browser firefox
  • Python version 3.7
  • Django version 2.1
  • Bootstrap version 4

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Consider using a data attribute rather than dp_config

Hi,

Describe the bug

It seems this Django widget is using the dp_config attribute to pass the datepicker configuration to the JS side (

).

It seems this is coming from the Django wrapper and not the underlying Bootstrap DatePicker library (as far as I know).

This is not a big deal but such an attribute (dp_config) is not a valid HTML attribute. Therefore, it makes automatic testing of the HTML validity of pages more difficult as one has to ignore all these false positives.

The standard way of doing this now seems to be using data- attributes (https://developer.mozilla.org/fr/docs/Web/HTML/Attributs_universels/data-*). What about moving to something like data-dp-config?

To Reproduce
Steps to reproduce the behavior:

  1. Create a template calling this widget.
  2. Run W3C validator (https://validator.w3.org/nu/) on the resulting HTML.

Expected behavior
HTML should be valid.

Thanks!

Changing width doesn't move calendar icon

I set the width of the datepicker using

DatePickerInput(format='%m/%d/%Y',attrs={"style": "width:12.5em"})

To match the size of other items in my form, however the calendar icon is still all the way over on the other side of the screen (I shrunk the screen to take the image otherwise it would be a tonne of white space):

image

If I don't use attrs={"style": "width:12.5em"} it takes up the entire width of the page, so what's the best way to set the width of the datepicker but one that also moves the calendar icon (or is there some way to hide that icon instead?)

Calendar not showing up in a MODAL Form

Calendar not showing up in a Modal form for the first time. If I close the modal and open it again, calendar starts working.

Here is an error in console log I get:

jquery.min.js:2 Uncaught TypeError: $element.datetimepicker is not a function
    at HTMLInputElement.<anonymous> (<anonymous>:14:38)
    at Function.each (jquery.min.js:2)
    at w.fn.init.each (jquery.min.js:2)
    at HTMLDocument.<anonymous> (<anonymous>:7:38)
    at l (jquery.min.js:2)
    at c (jquery.min.js:2)

Add Rich Text to same form

Not really a datepicker issue but hoping someone can help me. After I integrated django-tinymce the datepicker widget breaks and doesn't show. If I remove the field for the rich text from my form, datepicker works completely. Any suggestions??

Possible bug: options={'maxDate': foo} changing the initial/default value for field

Thank you for the great widget.

I am using the minDate and maxDate options in the widgets. The minDate option works as expected. The maxDate option correctly sets the max date, but then also populates the date field as the initial value or default value every time the form is called, instead of using the value from the initial dictionary passed from Views. When only using the minDate option, the correct initial value from the initial dictionary is set.

I also tried another option by not passing the initial dictionary from Views, but setting the defaultDate under options. As before, this works fine alongside the minDate option but gets overridden by the maxDate option so that the default date shown is maxDate.

See my script below. The initial (default) value of date_y is always set to maxDate.
Note that in both cases I am defining the widgets in form __init__ because I am passing the minDate and maxDate from Views as these will change each time the form is called.

Thank you
Gerhard


class DatePickerPlusPage(View):
	""" Show a form for entering dates date_x and date_y using 
                django_bootstrap_datepicker_plus.
		date_x range cannot be below date_x_range_min
		date_y range cannot be above date_y_range_max
		As intial values for these fields use today's date, or if available the previously entered 
                values 
	"""
	form_class = DatePickerPlusForm
	template_name = 'date_picker_plus_page.html'
	
	def get(self, request):
	
		if self.request.GET.get('date_x', default=None) is None:
			# first call 
			initial_form_dict={'date_x':datetime.now().date,'date_y': datetime.now().date}
		else:
			# calls with form filled in
			date_picker_form = self.form_class(data=request.GET)
			date_picker_form.is_valid()
			date_x = date_picker_form.cleaned_data['date_x']
			date_y = date_picker_form.cleaned_data['date_y']
			
			print('This is what the form contains:', date_x, date_y)
			initial_form_dict = {'date_x': date_x,'date_y': date_y}
		
		context = {}
		context['date_picker_form'] = self.form_class(initial=initial_form_dict,
				date_x_range_min=datetime(2000, 1, 1).date(), 
                                date_y_range_max=datetime(2010, 12, 31).date())
			
		template = loader.get_template(self.template_name)
		output = template.render(context, request)
		return HttpResponse(output)


class DatePickerPlusForm(forms.Form):
	
	date_x = forms.CharField()  # needs to be CharField since we are using MonthPicker
	date_y = forms.CharField()
	
	def __init__(self, *args, date_x_range_min=None, date_y_range_max=None,**kwargs):		
		super().__init__(*args, **kwargs)
		
		# convert date_x_range_min to json date
		if date_x_range_min is not None:
			date_x_range_min = date_x_range_min.strftime('%b %Y')	
		# convert date_y_range_max to json date
		if date_y_range_max is not None:
			date_y_range_max = date_y_range_max.strftime('%b %Y')
		
		# set up DatePicker widgets
		self.fields['date_x'].widget=MonthPickerInput(format='%b %Y',options={'minDate': 
                                                                                  date_x_range_min})
		self.fields['date_y'].widget=MonthPickerInput(format='%b %Y',options={'maxDate': 
                                                                                  date_y_range_max})
		return
	
	def clean_date_x(self):
		""" Convert str to date type"""		
		updated_date = self.cleaned_data['date_x']
		updated_date =  datetime.strptime('1 ' + updated_date ,'%d %b %Y').date()
		return updated_date
		
	def clean_date_y(self):
		""" Convert str to date type"""		
		updated_date = self.cleaned_data['date_y']
		updated_date = datetime.strptime('15 ' + updated_date,'%d %b %Y').date()
		return updated_date

Month not showing as a table

Describe the bug
The calendar works as expected, it's just that the month view is not in table form. Clicking on the month and year work as expected.

To Reproduce
Followed all the steps in the documents. Click on the calendar button to change the date and the month view appears as a list rather than a table.

Expected behavior
I have used Django-bootstrap-datepicker-plus in another Django application, V 2.2.1 with no issues.

Screenshots
If applicable, add screenshots to help explain your problem.
image

Setup Information (please complete the following information):
OS: macOS High Sierra v10.13.6
Chrome Version 81.0.4044.138
Python 3.7.3
Django~=2.2.4
Pillow==6.0.0
django-crispy-forms==1.7.2
django-bootstrap4==0.0.8
django-bootstrap-datepicker-plus==3.0.5

Calendar doesn't show up when Debug=False

Hello,

thank you for this great work. Everything works fine for me, when I have Debug=True in my settings.py.
But when I change it to False the calender does not show up.

Thanks in advance.

Date-time Picker not open but after reopen modal it runs smooth

When I run my app there's no error, but when I press button to open form with modal it opens and I get an error Uncaught TypeError: $element.datetimepicker is not a function, then I close modal and open it again now there's no error and its running, I can choose date and time too with no problem, I can use datetime picker. I should able to pick date time, anytime I open that modal.

I dont have any error on my Django console, I got a JS error in browser console:

    Uncaught TypeError: $element.datetimepicker is not a function
    at HTMLInputElement.<anonymous> (<anonymous>:14:38)
    at Function.each (VM2470 jquery.js:354)
    at jQuery.fn.init.each (VM2470 jquery.js:189)
    at HTMLDocument.<anonymous> (<anonymous>:7:38)
    at mightThrow (VM2470 jquery.js:3534)
    at process (VM2470 jquery.js:3602)

settings.py

INSTALLED_APPS = [
    'bootstrap4',
    'bootstrap_datepicker_plus',

BOOTSTRAP4 = {
    'include_jquery': True,
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_DIR, "/dysporject/dysapp/static"),
)

view.py

@login_required()
def appcal_create(request):
    if request.method == 'POST':
        form = EventForm(request.POST)
    else:
        form = EventForm()
    return save_event_form(request, form,  'appointmentcal_create_partial.html')


@login_required()
def save_event_form(request, form, template_name):
    data = dict()
    if request.method == 'POST':
        if form.is_valid():
            obj = form.save(commit=False)
            obj.tenantid = request.user.tenantid
            form.save()
            data['form_is_valid'] = True
            events = CalanderEvents.objects.filter(
                tenantid=request.user.tenantid).values()
            data['html_appointmentcal_list'] = render_to_string('appointmentcal_list_partial.html', {
                'events': events
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render_to_string(
        template_name, context, request=request)
    return JsonResponse(data)

forms.py

from bootstrap_datepicker_plus import DatePickerInput, DateTimePickerInput
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Customer, User, CalanderEvents

class EventForm(forms.ModelForm):
    class Meta:
        model = CalanderEvents
        fields = ('id', 'customer', 'title', 'start', 'end')
        widgets = {
            'start': DateTimePickerInput(),
            'end': DateTimePickerInput(),
        }

list.html

{% extends 'ltebase.html' %}

{% load staticfiles  %}
{% block title %}Cutomer Appointments{% endblock %}

{% block content %}
    <section class="content-header">

    </section>
    <button type="button" class="btn btn-primary js-create-events" data-url="{% url 'appcal_create' %}">
      <span class="glyphicon glyphicon-plus"></span>
New    </button>

list_partial_form

{% load widget_tweaks %}

{% load staticfiles  %}

{% for field in form %}
  <div class="form-group{% if field.errors %} has-error{% endif %}">
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
    {% render_field field class="form-control" %}
    {% for error in field.errors %}
      <p class="help-block">{{ error }}</p>
    {% endfor %}
  </div>
{% endfor %}

list_partial_create.html

{% load widget_tweaks %}

{% load staticfiles  %}

<form method="post" action="{% url 'appcal_create' %}" class="js-event-create-form">
  {% csrf_token %}
   {{ form.media }}
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    <h4 class="modal-title">Create a new Event</h4>
  </div>
  <div class="modal-body">
    {% for field in form %}
      <div class="form-group{% if field.errors %} has-error{% endif %}">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <p class="help-block">{{ error }}</p>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create Event</button>
  </div>
</form>

ltebase.html: JS library order:

  <script src="{% static 'bower_components/jquery/dist/jquery.js' %}"></script>

  <script src="{% static 'bower_components/jquery-ui/jquery-ui.js' %}"></script>

  <script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>

  <script src="{% static 'bower_components/moment/moment.js' %}"></script>

  <script src="{% static 'bower_components/jquery-slimscroll/jquery.slimscroll.min.js' %}">/script>

  <script src="{% static 'bower_components/fastclick/lib/fastclick.js' %}"></script>

  <script src="{% static 'dist/js/adminlte.min.js' %}"></script>

  <script src="{% static 'bower_components/fullcalendar/dist/fullcalendar.js' %}"></script>

  <script src="{% static 'bower_components/fullcalendar/dist/locale/tr.js' %}"></script>

  <script src="{% static 'js/customer.js' %}"></script>

  <script src="{% static 'js/appointmentcal.js' %}"></script>

Setup Information

  • OS: [Windows 10]
  • Browser [ chrome]
  • Browser version [ 73.036]
  • Python version [3.7]
  • Django version [2.1.1]
  • Bootstrap version [4]
  • jQuery version [3.1.1]

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Calendar rendered partly behind another container

Describe the problem
When I open the calendar, it is partly rendered behind another container. I don't know much CSS, so I have no idea how to make the calendar to display on top of everything.

Additionally:

  1. would it be possible to reduce the size of the calendar?
  2. is it be possible to hide the icon in the text input?

Thanks in advance.

Expected behavior
Display the calendar on top of everything.

Console errors

  • No error on django console.
  • No error on JavaScript console.

Setup Information (please complete the following information):

  • OS: Ubuntu Linux
  • Browser Chrome and Firefox
  • Browser version latest
  • Python version 3.7
  • Django version 2.2
  • Bootstrap version 4
  • jQuery version 3.4.1

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

is it compatible with django 3.0? or did i do something wrong?

hello all

Describe the bug
Apparently it is not compatible with django 3.0
It gives an error: TypeError: render() got an unexpected keyword argument 'renderer'

To Reproduce
Expected behavior
I was hoping that it would work with django 3.0 like it does with django 2.0.5

Screenshots

Setup Information (please complete the following information):

  • OS: Win 8.1 32-bit
  • Browser Firefox Brave
  • Browser version Firefox 75.0 / Brave 1.8.95
  • Python version 3.7.3
  • Django version 3.0.5
  • Bootstrap version 4
  • jQuery version django-jquery 3.1.0

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

could you / someone please help me?
perhaps I do something wrong?
right now in dev, i use a workaround: i comment out line 96 of django/forms/boundfield.py
(renderer=self.form.renderer,)
but when using heroku, i can't access the installed site-packages

or perhaps you could release an update to work with django 3.0?

thank you so much

jud

How to exploit the range picker

Hi!
Thanks for this amazing widget!
I was just gessing if the start_of end_off could be set to a specific date. From documentation it only appears code such as: .end_of('event days') . Is it possible to set it up something like .end_of('2019-01-01') ?

I'm using form.Forms not ModelForms

Compatibility issue with Django-form-wizard

I am working on Django form wizard with some steps. I have managed to install the Django-bootstrap-datepicker-plus. However, instead of launching on the given field as expected, it is being loaded outside the form container, specifically at the top, when I click the button appended to the date field. I have tried checking the console but there is no error at all. What could be the problem? Let me know if I should post any code, but generally, the code is as stated in the README file.

Documentation Improvement

Recently a ReadTheDocs documentation has been published for the project. I tried to make the documentation as detailed as I can but it still needs improvements which is not a task of a single man. Developers new to django may get over-whelmed by the instructions if the documentation is not well-written or not easily conceivable.

I can use some community help in this scenario and would gladly appreciate any improvements in the form of suggestions, opinions and pull-requests even to improve a little bit of it.

The documentation files are in .rst format inside the docs directory and are built with sphinx by ReadTheDocs to static html files upon push to GitHub.

How to use additional date-time formats e.g "%d/%m/%Y"

Hi,

I am currently trying to use your datetime picker and first of all i want to thank you about this useful component.

Secondly, i am here because i am french and i want to format the datetimepicker according to my locale. For that, i add to my DateTimePickerInput a format so that i have :

DateTimePickerInput(format="%d/%m/%Y %H:%M")

Basically i just wanted to invert month and day.

Also, in that case that does not work well but when i do not use a format option such as mentionned previously, your component works well (the datetime i wanted to save in my db is saved successfully).

Thanks in advance for your time,

Maxime

Date invalid with django class view

The picker appears correctly and posts the value correctly. However, the validation from a class based django view says the value is not valid.

class CreateProfileView(LoginRequiredMixin, CreateView):
    form_class = CreateProfileForm
    template_name = 'fnf/create_profile.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)
class CreateProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['gender', 'birthdate']
        widgets = {
            'birthdate': DatePickerInput(format='%Y/%m/%d', options={
                "maxDate": (date.today() - relativedelta(years=18)).strftime('%Y-%m-%d'),
                "minDate": (date.today() - relativedelta(years=99)).strftime('%Y-%m-%d'),
                # "defaultDate": ().strftime('%Y-%m-%d')
            }),
        }

The breakpoints in form_valid does not trigger, so I'm not sure where the validation fails before that?

Dimensions of the Date & Time Picker

I have a very simple question.

Is it possible to redimension the size of the Date and Time Picker?

image

For example, I would like that the Date Picker could have a shorter width. The same would apply for the Time Picker.

Thanks!

Bootstrap CDN or download?

I am attempting to use this in a Django 2.0+ project. I am new to web development in Django.

The demo for this project looks great! Thank you for posting this.

I cannot get Django tags to resolve. I have only this Bootstrap link in a base.html template //maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css. Do I need to actually download Bootstrap 3? The instructions are clear except for this detail about Bootstrap files.

Setup Information (please complete the following information):

  • OS: [Mac]
  • Browser [chrome]
  • Python version [3.6.4]
  • Django version [2.0.4]
  • Bootstrap version [3 via CDN]
  • jQuery version [?]

The component is broken when no internet connection available

Describe the bug
I need to host the website in a local network without internet access. Since bootstrap-datetimepicker-plus loads resources from CDN, the component can't be rendered. I can introduce a quick and dirty fix by monkeypatching the BasePickerInput early enough e.g.:

import bootstrap_datepicker_plus as bdp


bdp.BasePickerInput.Media.js = (
    'assets/js/moment-with-locales.min.js',
    'assets/js/bootstrap-datetimepicker.min.js',
    'bootstrap_datepicker_plus/js/datepicker-widget.js'
)
bdp.BasePickerInput.Media.css = {
    'all': (
	'assets/css/bootstrap-datetimepicker.css',
        'assets/css/bootstrap-datetimepicker-plus-override.css',
        'bootstrap_datepicker_plus/css/datepicker-widget.css',
    ),
}

and replacing bootstrap-datetimepicker-plus.css with a copy with modified font paths, but this is no solution and will break immediately once the library changes.

To Reproduce
Steps to reproduce the behavior:

$ echo -e "127.0.0.1	cdnjs.cloudflare.com" >> /etc/hosts
$ echo -e "127.0.0.1	maxcdn.bootstrapcdn.com" >> /etc/hosts
  1. The component is not loaded correctly (missing icons, button not clickable), network errors in browser logs:
GET https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css net::ERR_CONNECTION_REFUSED
localhost/:70 GET https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js net::ERR_CONNECTION_REFUSED
localhost/:71 GET https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js net::ERR_CONNECTION_REFUSED
localhost/:1 GET http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff2 net::ERR_CONNECTION_REFUSED
jquery-3.3.1.min.js:2 jQuery.Deferred exception: $element.datetimepicker is not a function TypeError: $element.datetimepicker is not a function
    at HTMLInputElement.<anonymous> (http://localhost:8000/static/bootstrap_datepicker_plus/js/datepicker-widget.js:14:38)
    at Function.each (http://localhost:8000/static/assets/js/jquery-3.3.1.min.js:2:2573)
    at w.fn.init.each (http://localhost:8000/static/assets/js/jquery-3.3.1.min.js:2:1240)
    at HTMLDocument.<anonymous> (http://localhost:8000/static/bootstrap_datepicker_plus/js/datepicker-widget.js:7:38)
    at l (http://localhost:8000/static/assets/js/jquery-3.3.1.min.js:2:29375)
    at c (http://localhost:8000/static/assets/js/jquery-3.3.1.min.js:2:29677) undefined

Expected behavior
The component must be functional when on internet access available

Setup Information (please complete the following information):

  • OS: Fedora 29
  • Browser chrome
  • Browser version 72
  • Python version 3.6
  • Django version 2.1.5
  • Bootstrap version 4
  • jQuery version 3.3.1

The Datepicker & Timepicker is not working with ModelForms

I have done a pip install. I have done pip install django-bootstrap-datepicker-plus. I have added this in my settings

`INSTALLED_APPS = [    
    'bootstrap_datepicker_plus',
]`

also added

`BOOTSTRAP3 = {
    'include_jquery': True,
}`

However it is not working. I have attached image links of how it should display and how it is displaying at the very end. What am I doing wrong here

Forms.py

    from django import forms
    from .models import Event
    from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput

    class EventForm(forms.ModelForm):    
        class Meta:
            model = Event
            fields = ('price', 'stock', 'date', 'time_from', 'time_to')
            widgets = {
                'price': forms.NumberInput(), 
                'stock': forms.NumberInput(), 
                'date': DatePickerInput(attrs={'class': 'datepicker'}),# This datepicker is not working 
                'time_from': TimePickerInput(), # These are not working either 
                'time_to': TimePickerInput(),


        def __init__(self, *args, **kwargs):
           super().__init__(*args, **kwargs)
           self.fields['stock'].label = "How many people can attend your event"
           self.fields['price'].label = "How much do members have to pay to attend"
           self.fields['date'].label = "When do you plan to host your event"
           self.fields['time_from'].label = "What time does the event start"
           self.fields['time_to'].label = "What time does the event end"

Template.html

{% load staticfiles %}
        {% load bootstrap3 %}
        {% bootstrap_css %}         {# Embed Bootstrap CSS #}
        {% bootstrap_javascript jquery='full' %}  {# Embed Bootstrap JS+jQuery #}
        {% block extrahead %}       {# Extra Resources Start #}
        {{ form.media }}            {# Form required JS and CSS #}
        {% endblock %}              {# Extra Resources End #}
        {% block body %}
    
       
    
     
    
    <div class="form-group row">
         {{field.errors}}
         <form action="{% url 'event:new_event' slug=post.slug %}" method="post" >
             {% csrf_token %}
             {% bootstrap_form form %} 
             <input type="submit" value="Save" class="btn btn-success btn-sm" />
         </form>
    </div>
    {% endblock  %}

Models.py

       class Event(models.Model):
             user = models.ForeignKey(User, related_name='seller')
             post = models.ForeignKey(Post, related_name='course')
             price = models.DecimalField(max_digits=6, decimal_places=2)
             stock = models.PositiveIntegerField()
             date = models.DateField()
             time_from = models.TimeField()
             time_to = models.TimeField()

Base.html

<head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1">[![enter image description here][1]][1]
       {% load staticfiles %}
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
       <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
   </head>

This is how it should work
https://i.stack.imgur.com/YjSb5.png

This is how it is now
https://i.stack.imgur.com/ojmlr.png

What am I doing wrong

how to customize...

hello I would like to know how to disable holidays (like Christmas or New Years). And restrict the minutes to 00 and 30.
Example:
12.00
12.30

Thank u!

class Form(forms.ModelForm):

class Meta:
    model = Reserva
    fields = ["end_date", "start_time", "comensales"]
    widgets = {
        'comensales' : forms.NumberInput(
            attrs={
                'class': 'form-control',
            }
        ),
        'end_date': DatePickerInput(
            format='%d/%m/%Y',
            options={
                "locale": "es", 
            }
        )
        'start_time': TimePickerInput(
            options={
                'enabledHours': [12, 13, 14, 19, 20 , 21, 22]
            }
        ),
    }

How to use your datepicker

Hi Munim:
Thank you for the great work you have done for the community. I saw the demo for bootstrap 4 and that is exactly what I want to implement to my own site. First, I am just learning django with basic grasp of model, view, forms and template. I am able to input info (CharField) and display info on my site. I wanna add date and time input and that is when I came across your post on stackoverflow.
I was able to follow through most of your instruction. What I don't understand is that you have codes for forms.py, but not models.py. The 'custom form usage' section looks like models.py setup but can you import forms class and uses it in models.py? Can I create class with forms.Form and pass it as foreignkey into class IssueTracking? Please see my models.py and forms.pybelow. I greatly appreciate you expertise. Thank you.

models.py
`from django.db import models
from bootstrap_datepicker_plus import DatePickerInput

class IssueTracking(models.Model):
po = models.CharField(max_length = 50, blank = False)

def __str__(self):
    return self.po`

forms.py
`from bootstrap_datepicker_plus import DatePickerInput
from django import forms

class IssueInput(forms.ModelForm):
class Meta:
model = IssueTracking
fields = 'all'
widgets = {
'start_date': DatePickerInput(
options={
"format": "MM/DD/YYYY", # moment date-time format
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
), # default date-format %m/%d/%Y will be used
}`

datepicker-plus button not launching

Describe the problem
it looks like the js is not launching on the datepicker

Console errors

  • No error on django console.
  • No error on JavaScript console.

HTML page:
`{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}

{{ order_form.media }}

{% csrf_token %}
{{ order_form.order_location|as_crispy_field }}
{{ order_form.collection_date|as_crispy_field }}

{% endblock %}

**forms.py**from bootstrap_datepicker_plus import DateTimePickerInput

class ORDERForm(forms.Form):
collection_date = forms.DateField(widget=DateTimePickerInput())
`

scripts from base.html
<!-- Latest compiled and minified jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

end_of() field doesn't respect locale on first appearance

I set up a pair of date range fields using start_of() and end_of(). The start field is OK, but the end field shows the picker in English the first time I click on the input. Only if I close and reopen it, it uses the specified locale.

Here's the code excerpt (w/ django-filters):

datepicker_args = {
    'format': '%d.%m.%Y',
    'options': { 'showClose': False, 'minDate': '2013-01-01', 'locale': 'ru' }
}
publishedFrom = django_filters.DateFilter(field_name='notification__published', lookup_expr='gte',
                                           widget=DatePickerInput(**datepicker_args).start_of('published'))
publishedTo = django_filters.DateFilter(field_name='notification__published', lookup_expr='lte',
                                           widget=DatePickerInput(**datepicker_args, attrs={'placeholder': 'по'}).end_of('published'))

AttributeError: 'list' object has no attribute 'replace'

I'm trying to use a custom form but I see this error:

File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/devenv/lib/python3.7/site-packages/bootstrap_datepicker_plus/_base.py", line 91, in init
super().init(attrs, self._calculate_format())
File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/devenv/lib/python3.7/site-packages/bootstrap_datepicker_plus/_base.py", line 107, in _calculate_format
self.config['options']['format'] = self.format_py2js(_format)
File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/devenv/lib/python3.7/site-packages/bootstrap_datepicker_plus/_base.py", line 70, in format_py2js
datetime_format = datetime_format.replace(py_format, js_format)
AttributeError: 'list' object has no attribute 'replace'

This happen when I add format as option of DateTimePickerInput. Below a part of my code:
forms.py

    publishing_date = forms.DateTimeField(
        widget=DateTimePickerInput(
            format=['%d/%m/%Y %H:%M'],
        ),
        required=False,
    )

mytemplate.html

  <form method="POST" enctype="multipart/form-data" novalidate>
    {% csrf_token %}
    {{ form.as_p }}
    <hr>
    <div class="row justify-content-md-center">
      <div class="col-md-auto">
        <input type="submit" class="btn btn-info shadow" value="Pubblica">
      </div>
    </div>
  </form>

How I can put date and time as dd/mm/yyy hh:mm precisely?

Translation and internalization

Hi, it seems like django-bootstrap-datepicker-plus supports translation and internalization (because it uses moment.js with locales) but it is not mentioned in the documentation. How can I choose the language of the calendar? How can I translate the names of the months in the calendar widget?

Trigger change event on DatePickerInput

I would like to catch the change event of a DatePickerInput.
The classical jQuery $("#id_inputdate").change(function(){console.log('YESSS'});
does not work.
I've checked and try https://stackoverflow.com/questions/6471959/jquery-datepicker-onchange-event-issue without any success.
Would you please tell me how to do it??? Please note that I'm also using the linked range date feature with .start_of and end_of.
Many thanks for this great widget anyway! It works fine and it is very nice.

datepicker not working in a formsets

Datepickers do not show up in dynamically added empty formsets.
They do show up only in formsets that are loaded with the page.

To Reproduce
Create a django form with a date field:
my_date = forms.DateField(widget=DatePickerInput())
Use it in a formset.

Expected behavior
Statically and dynamically loaded date fields should make a JS calendar appear.

What's seen instead
Only the statically loaded datepickers show the JS calendar. Nothing shows up on dynamically added formsets.

Setup Information:

  • OS: [ubuntu 18]
  • Browser: Chrome
  • Browser version [Version 71.0.3578.80]
  • Python version [3.6]
  • Django version [2.1]
  • Bootstrap version [4]
  • jQuery version [1.7.1]

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

MEDIA is called twice

Hi,
I load manually load CSS and JS in my template for my ModelForm DateTime field. I dont load in {{ form.media.js }} as this is already loaded.

The form works fine. But I get this error
Uncaught TypeError: Cannot read property 'Constructor' of undefined

Examination of html reveals that this JS and CSS is called, in MEDIA:

. Manually deleting that CSS and JS removes the console error. Note that the form still works (as I manually add ncessary css and js).

Is there a setting for me to prevent MEDIA js and css being loaded? I've failed to google on this.

With many thanks,
Andy.

DatePicker not showing in modal form

Describe the problem
When I try to use the datepicker in a modal form, the calendar doesn´t show, but if I go to a commom form the widget shows.

Console errors

  • No error on django console.
  • No error on JavaScript console.

Paste-bin

forms.py
class EtapasForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm):
class Meta:
model = etapas
fields = ['etapa','responsavel', 'data_in', 'data_fim', 'horas',
'Obs', ]
data_in = forms.DateField(
widget=DatePickerInput(format='%d/%m/%Y')
)

view.py
class EtapaCreateView(PassRequestMixin, SuccessMessageMixin,
generic.CreateView):
template_name = 'etapas/create_etapa.html'
form_class = EtapasForm
success_message = 'Etapa criada!'

def get_form(self):
    form = super().get_form()
    form.fields['data_in'].widget = DatePickerInput()
    return form
def form_valid(self, form):
    #widgets = {'data_in': form.DateInput(attrs={'class': 'datepicker'})}
    #form.instance.sequencia = etapas.objects.get(id = self.kwargs['pk_proc']).aggregate(Max('sequencia')).sequencia + 1
    try:
        etapa_temp= etapas.objects.filter(pai = self.kwargs['pk_proc']).order_by('-sequencia')[0]
        form.instance.sequencia = etapa_temp.sequencia + 1
    except:
        form.instance.sequencia = 1
    form.instance.pai = processos.objects.get(id = self.kwargs['pk_proc'])
    return super(EtapaCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
    context = super(EtapaCreateView,self).get_context_data(**kwargs)
    context['pai'] = self.kwargs['pk_proc']
    return context
def get_success_url(self):
    return reverse_lazy('etapas' , kwargs={'pk': self.kwargs['pk_proc']})

create_etapa.html
{% load widget_tweaks %}

{% load bootstrap3 %} {# import bootstrap4/bootstrap3 #}
{% bootstrap_css %} {# Embed Bootstrap CSS #}
{% bootstrap_javascript jquery='full' %} {# Embed Bootstrap JS+jQuery #}

{% csrf_token %} {{ form.as_p }} {{ form.media }}
Salvar

Setup Information (please complete the following information):

  • OS: . Windows 10
  • Browser chrome
  • Browser version
  • Python version 3.7
  • Django version 2
  • Bootstrap version 4
  • jQuery version 1.7.1

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

I am trying to install django-bootstrap-datepicker-plus using pip.

Describe the problem
A clear and concise description of what the scenario is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Console errors

  • No error on django console.
  • No error on JavaScript console.

Paste-bin
The page is showing up but the date-picker calendar is not. The paste-bin link
of the HTML source of the page is http://...

Setup Information (please complete the following information):

  • OS: [e.g. Windows 10]
  • Browser [e.g. chrome, safari]
  • Browser version [e.g. 22]
  • Python version [e.g. 3.7]
  • Django version [e.g. 2.1]
  • Bootstrap version [e.g. 3/4]
  • jQuery version [e.g. 1.7.1]

[x] I have followed the configuration instructions and checked out the
common error troubleshooting page.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.