我有一个应用程序,我需要查询数据库的某个日期,检查是否有一个条目已经为日期x为用户y。
我有一个模型,它有以下字段:
class MyModel(models.Model):
user = models.ForeignKey(User)
day = models.DateField()
info = models.CharField(max_length=100)
在form .py中我有:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
在views.py代码中,我想检查这一天是否存在于数据库中,所以我运行:
from datetime import date
from myapp.models import MyModel
from myapp.forms import MyForm
...
#inside the view function
form = MyForm(request.POST)
day = date(form.day)
if days.objects.filter(user=request.user, day=bookday).exists():
... do stuff
它给了我:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/test_url/
Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'south',
'myapp')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/django/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/django/env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/django/env/myproject/myapp/views.py" in test_url
26. bookday = date(form.day)
Exception Type: AttributeError at /test_url/
Exception Value: 'MyForm' object has no attribute 'day'
虽然它显然有日期表单作为DateField。在这种情况下,我该怎么做?
POST数据:
POST
Variable Value
csrfmiddlewaretoken = u'blahblah'
day = u'03/27/2013'
user = u'2'
HTML模板表单:
<form method="post" action="." >
{{ form.user }}
{{ form.day}}
<input type="submit" value="Submit" />
{% csrf_token %}
</form>
编辑:我澄清了代码,并把堆栈跟踪。
我让这个工作。解决办法很简单。在需要获取post日值的行中,我只需使用:
day = form.cleaned_data['day']
而不是我之前的:
day = date(form.day) #WRONG CODE
,然后将其作为正常的days.objects.filter(user=request)传递给数据库。User, day=day) line.