0

I want to add a datetime picker input field in my django project.

I found this tutorial that offers a few ways but all of them are using forms.py as following:

from django import forms

class DateForm(forms.Form):
    date = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=forms.DateTimeInput(attrs={
            'class': 'form-control datetimepicker-input',
            'data-target': '#datetimepicker1'
        })
    )

But I am not using forms in my project. I am using the function views. I can't find an example of how to implement a DateTime picker in this way?!

any help is appreciated.

Shahriar.M
  • 818
  • 1
  • 11
  • 24
  • Do you have any perticular reason that you don't want to use forms in your project? – SLDem Jan 21 '21 at 10:47
  • I'm in the middle of the project, its almost done, I don't want to switch to use forms – Shahriar.M Jan 21 '21 at 10:49
  • You can just make a simple Form subclassing the djangos `Form` class and use it, there really shouldn't be any reasons not to, 'don't want' isn't a reason its a preference which really makes 0 sense especially in the context of this question, when you have 5 different working methods to do what you need using Forms – SLDem Jan 21 '21 at 10:51
  • the template is rendered using a view function. you are saying I make a form just for the part of datetime picker? I dont know how to combine them! can you please give me an example? – Shahriar.M Jan 21 '21 at 10:55

1 Answers1

0

Alright so heres an example django form you can create and use in your view:

from django import forms

class MyForm(forms.Form):
    datetime = forms.DateField(required=False, widget=forms.SelectDateWidget(years=range(2000, current_year))) # use this widget 
    # other fields you want

then in your views.py

from .forms import MyForm

def submit_form_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home') # or somewhere else
    else:
        form = MyForm()
    return render(request, 'your_form_view.html', {'form': form})

then just render the form as you would regularly in your_form_view.html:

<form class="main-form" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button class="main-button" type="submit">Save</button>
</form>
SLDem
  • 2,065
  • 1
  • 8
  • 28
  • Ive used the first option on the tutorial, "Tempus Dominus Bootstrap 4". and implemented it just like you said, the calendar icon is added but it is not clickable, it is disabled – Shahriar.M Jan 21 '21 at 11:54
  • This is just a date picker example using only django, you should try to follow the steps from the tutorial exactly how they are described and it will work – SLDem Jan 21 '21 at 11:58