我有一个Django项目。
这是我的模特:
class Task(models.Model):
class Meta:
db_table = 'task'
title = models.CharField(max_length=64)
这是我的表格:
class TaskForm(forms.Form):
def __init__(self, *args, **kwargs):
user = None
if 'user' in kwargs:
user = kwargs.pop('user')
super(TaskForm, self).__init__(*args, **kwargs)
title = forms.CharField(max_length=64)
这是我的观点:
def create(request):
args = {}
args.update(csrf(request))
if request.POST:
form = TaskForm(request.POST)
if form.is_valid()
Task(title=form.cleaned_data['title']).save()
return redirect('/tasks/user')
else:
args = {'error': form.errors}
return render_to_response('index.html', args,
context_instance=RequestContext(request))
else:
args['form'] = TaskForm(user=request.user)
return render_to_response('create_task.html', args,
context_instance=RequestContext(request))
但如果我要添加任务,我会收到错误: 'function'对象没有属性'model' 在行
if form.is_valid():
回溯:
File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wlad031/Dropbox/Documents/Workspace/task_manager/task/views.py" in create
43. if form.is_valid() File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
184. return self.is_bound and not self.errors File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/forms.py" in errors
176. self.full_clean() File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
392. self._clean_fields() File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
407. value = field.clean(value) File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/fields.py" in clean
162. value = self.to_python(value) File "/home/wlad031/.virtualenvs/venv_task_manager/local/lib/python2.7/site-packages/django/forms/models.py" in to_python
1215. except (ValueError, TypeError, self.queryset.model.DoesNotExist):
Exception Type: AttributeError at /tasks/create/ Exception Value: 'function' object has no attribute 'model'
我哪里错了?
答案 0 :(得分:0)
我得到了同样的错误,似乎“form = TaskForm(request.POST)”不创建一个对象而是一个函数,但如果你从模型的字段创建表单它应该工作。试试这样:
class TaskForm(forms.Form):
def __init__(self, *args, **kwargs):
user = None
if 'user' in kwargs:
user = kwargs.pop('user')
super(TaskForm, self).__init__(*args, **kwargs)
class Meta:
model= Task
fields={'title',}