2
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.
Source:stackexchange.com