我有一个应用程序,我需要在该数据库中查询某个特定日期,以检查用户y的日期x是否已有条目。
我的模型包含以下字段:
class MyModel(models.Model):
user = models.ForeignKey(User)
day = models.DateField()
info = models.CharField(max_length=100)
在forms.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>
编辑:我澄清了代码并放了堆栈跟踪。
答案 0 :(得分:0)
我让这个工作。解决方案很简单。在我需要获取POSTed day值的行中,我只使用:
day = form.cleaned_data['day']
而不是我以前拥有的东西:
day = date(form.day) #WRONG CODE
然后将其作为普通的days.objects.filter(user = request.user,day = day)行传递给数据库。