1

I am a Django newbie and am stuck on a small problem.

I am trying to build a view where the user enters a from and to date and I need to pull records from my database according to these dates. I have worked out how to pull records without the user input dates(I tested using system dates, used deltas according to the documentation listed on the official website and i understood it) however am stuck now on how to get them as a user input.

Here are a few relevant details of my project:

models.py contains a lot of fields but here is the date field entry:

date = models.DateField(auto_now_add=True) 

This entry defines the date the record is created.

forms.py:

I am using an unbound form(not linked to the model created in models.py) and am using the Jquery plugin listed here in a simple HTML page to show the from and to date.

As a result the dates are passed as plain text in the form according to the documentation listed.

The only way I know on how to get a user input is through a form(bound or unbound) which usually ends up as a POST request passing data into the db either through insert record or update record. I do not know of and could not find any other way of getting a user input where it does not need to passed to the db.

Can someone kindly advise how to get the user input dates using this plugin and :

  • How to extract the from and to dates from the user input from the POST request in the views.py view?

  • How to convert it to a DateField (or if the form taking these dates should have the dates set as a Datefield)?

Thanks in advance..

djangonewuser
  • 11
  • 1
  • 3

5 Answers5

2

This is exactly what Django forms do. There is no requirement for a form to save to a database. The main responsibility of a form is validating and cleaning data, which is exactly what you are asking for. So, given a form like this:

class MyForm(forms.Form):
   date = forms.DateField()

you can access the date object in the view:

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            date = form.cleaned_data['date'] # this will be a datetime.date object
     ....
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

1) How to extract the from and to dates from the user input form's after the post request in the views.py view?

When you submit your form from Django template form, i assume you would have used django template forms, like input fields and datetime fields using widgets. When you submit your form you can check it in

request.POST

2) How to convert it to a Datefield(or if the form taking these dates should have the dates set as a Datefield)?

When you getting result in request.POST it either string or datetime object, i am not sure not used django forms lately. You can use datetime library to convert string to datetime object. Or if it is datetime object you can save it directly in model datetime field.

Like This

datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')

According to your example it will come in string and you have to convert it to date time object and then save it in your model.

jahmed31
  • 3,456
  • 3
  • 23
  • 23
  • What about timezone data? Assuming the user is submitting the time from their browser, their timezone is may be different from the server. – KillerKode Oct 17 '19 at 13:13
1

your databasese should be something like that, in oder to register the from and to

mdoels.py

class ClassModel(models.Model):
    xfrom = models.DateField(blank=True,null=True)
    to = models.DateField(blank=True,null=True)

forms.py

from django import forms.

class DateForm(forms.Form):
     xfrom = forms.DateField(input_formats = ['%m/%d/%Y'])
     to = forms.DateField(input_formats = ['%m/%d/%Y'])

views.py

from .forms import DateForm
from .models import ClassModel

def dateView(request):
    form = DateForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            xfrom = form.cleaned_data.get('xfrom')
            to = form.cleaned_data.get('to')

        cl = ClassModel.objects.create(xfrom=xfrom,to=to)

    context = ( { 'form':form } )
    return render(request,'template_name.html',context)

template_name.html

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<form action="" method="post">{% csrf_token %}
    <label for="id_xfrom">From</label>
    {{form.xfrom}}

    <label for="id_to">to</label>
    {{form.to}}
    <button type='submit'>Submit</button>
</form>

js

  $( function() {
var dateFormat = "mm/dd/yy",
  from = $( "#id_from" )
    .datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 3
    })
    .on( "change", function() {
      to.datepicker( "option", "minDate", getDate( this ) );
    }),
  to = $( "#id_to" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3
  })
  .on( "change", function() {
    from.datepicker( "option", "maxDate", getDate( this ) );
  });

function getDate( element ) {
  var date;
  try {
    date = $.datepicker.parseDate( dateFormat, element.value );
  } catch( error ) {
    date = null;
  }

  return date;
}

} );

Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
0

Try:

from datetime import datetime

date_converted = datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')


More info here

Chiefir
  • 2,561
  • 1
  • 27
  • 46
0

I think Daniel's answer solved the problem. I was following the same approach but not using the DateField. I was using CharField as the date type.

djangonewuser
  • 11
  • 1
  • 3