我创建了视图MyView(CreateView)以及模型和表单并收到错误:
AttributeError: type object 'MyModel' has no attribute '_meta'
以下是我的观点:
class MyView(CreateView):
model = MyModel
template_name = "myapp/template1.html"
这是我的模特:
class MyModel(models.Model):
free_day = models.CharField(max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
verbose_name = _('MyModel')
verbose_name_plural = _('MyModels')
def __unicode__(self):
return self.free_day
我的表格:
class MyInputForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('user', 'free_day', )
这是我的追溯
Internal Server Error: /freedays/addvacation/
Traceback (most recent call last):
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/db/transaction.py", line 394, in inner
return func(*args, **kwargs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 203, in get
return super(BaseCreateView, self).get(request, *args, **kwargs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 161, in get
form_class = self.get_form_class()
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 119, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/forms/models.py", line 539, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/forms/models.py", line 284, in __new__
opts.help_texts, opts.error_messages)
File "/home/mariusz/.virtualenvs/urlop/local/lib/python2.7/site-packages/django/forms/models.py", line 184, in fields_for_model
opts = model._meta
AttributeError: type object 'MyModel' has no attribute '_meta'
答案 0 :(得分:1)
我无法确切地知道它为什么会出现这个错误(看起来MyModel实际上并不是你的模型类 - 你有没有在其他地方重新定义它?),但是有一个明显的问题:你的观点应该是引用您定义的表单,而不是直接引用模型。
class MyView(CreateView):
form_class = MyInputForm
答案 1 :(得分:0)
而不是以下内容:
def get(request,self):
您可以使用以下内容:
def get(self,request):
其他一切都应该没问题!
答案 2 :(得分:-1)
您是否尝试过将meta作为一个函数,看起来像这样;
class MyModel(models.Model):
free_day = models.CharField(max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
def Meta():
verbose_name = _('MyModel')
verbose_name_plural = _('MyModels')
def __unicode__(self):
return self.free_day