Firkamon
Firkamon

Reputation: 807

DateTime object is none -- Python

I'm doing this inside Django. The DateTime string is passed into POST successfully. This is my code:

vk = Vk()
day1 = request.POST['day1']
vk.day1 = datetime.datetime.strptime(day1, '%m/%d/%Y %I:%M %p')
vk.save()

This is the format of the POST info:

'day1': 'MM/DD/YYYY HH:MM AM/PM' # AM/PM meaning either AM or PM

The problem is that the DateTimeField on the vk instance is None.

class Vk(models.Model):
    day1 = models.DateTimeField(null=True, blank=True)

I see that it is None in my HTML file:

{% for vk in vk %}
{{ vk.day1 }}
{% endfor %}

which amounts to None.

This is the view that is responsible for rendering the template:

def list_verkefni(request):
    vk = Vk.objects.all()
    vm = Vm.objects.all()

    return render(request, 'list_verkefni.html', 
    {'vk': vk, 'vm': vm}
    )

Upvotes: 1

Views: 331

Answers (1)

Bruce
Bruce

Reputation: 1380

Why don't you use ModelForm?

someapp/forms.py:

class VkForm(forms.ModelForm):
    class Meta:
        model = Vk
        fields = ('day1', )

    def __init__(self, *args, **kwargs):
        super(VkForm, self).__init__(*args, **kwargs)
        self.fields['day1'].input_formats = ['%m/%d/%Y %I:%M %p', ]

someapp/views.py:

def myview(request):
    form = VkForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        obj = form.save()
        return HttpResponseRedirect('/somewhere/')
    return render(
        request, 'template.html',
        {'form': form}
    )

Yes, you write a little bit more code, but:

  • you get full validation with nice error messages
  • whenever you extend your model in future, you don't need to rewrite the code, just add the field name into ModelForm
  • you don't need to do low level conversion to Python data types

This is considered a bad practise:

{% for vk in vk %}
{{ vk.day1 }}
{% endfor %}

Although this works in Django template engine, it is very confusing. If you would write the same in Python, vk will be overwritten. Whenever you work with a list of items, append _list to the variable name, e.g.: object_list or vk_list to distinguish between a single object and a list.

To better debug a code, I would suggest to pip install pudb and do something like this:

vk = Vk()
day1 = request.POST['day1']
import pudb; pudb.set_trace()
vk.day1 = datetime.datetime.strptime(day1, '%m/%d/%Y %I:%M %p')
vk.save()

Run the local dev server, do the POST request and check your terminal. Check if request.POST['day1'] is really what you expect to be and if it the datetime instance was set on your day atribute.

Upvotes: 2

Related Questions