Python Django - 使用OneToOneField的模型的CreateView获取错误"对象没有属性' id' "同时保存

时间:2016-05-22 09:02:47

标签: python django

class Organizer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=100)
    # ... some other fields

class EventTemplate(models.Model):
    title = models.CharField(max_length=255)    
    category = models.ForeignKey(Category)
    organizer = models.ForeignKey(Organizer)
    photo = models.ImageField(upload_to=event_directory_path)
    # ... some other fields

Organizer的主键也是与用户的OneToOne关系。 然后我使用CreateView插入一个新的EventTemplate:

class AddEventTemplateCreateView(CreateView):
    model = EventTemplate
    fields = ['title', 'category', 'organizer']
    success_url = reverse_lazy('myapp:organizer-account')

但是在保存时,AddEventTemplateCreateView上的POST操作(在urls.py中映射为" add-event")会出现此错误:

  

/ add-event /

中的AttributeError      

'组织者'对象没有属性' id'

在调试时我确认EventTemplate和属性Organizer的所有属性都已正确绑定。 类别没有错误,但类别有一个属性" id",而组织者只有一个属性" user_id"作为PK。 我认为他正试图获得一处房产" id"按照组织者的惯例。 我可以尝试修改Organizer模型,删除显式的primary_key,然后依靠自动PK' id,但在我看来,这是一个无用的重复。

是否需要设置任何属性,某些解决方案或建议才能使其正常工作?或者它无法使用CreateView完成?

谢谢!

修改 完整的追溯是:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/add-event/

Django Version: 1.9.4
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'ubivado',
 'bootstrapform']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/views/generic/edit.py" in post
  256.         return super(BaseCreateView, self).post(request, *args, **kwargs)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/views/generic/edit.py" in post
  222.             return self.form_valid(form)

File "/Users/redpelle/PycharmProjects/ubivado/ubivado_project/ubivado/views.py" in form_valid
  46.         return super(AddEventTemplateCreateView, self).form_valid(form)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/views/generic/edit.py" in form_valid
  201.         self.object = form.save()

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/forms/models.py" in save
  451.             self.instance.save()

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/base.py" in save
  700.                        force_update=force_update, update_fields=update_fields)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/base.py" in save_base
  728.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/base.py" in _save_table
  812.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/base.py" in _do_insert
  851.                                using=using, raw=raw)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/query.py" in _insert
  1039.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1059.             for sql, params in self.as_sql():

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in as_sql
  1019.                 for obj in self.query.objs

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1019.                 for obj in self.query.objs

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1018.                 [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in pre_save_val
  968.         return field.pre_save(obj, add=True)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/fields/files.py" in pre_save
  311.             file.save(file.name, file, save=False)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/fields/files.py" in save
  90.         name = self.field.generate_filename(self.instance, name)

File "/Users/redpelle/PycharmProjects/ubivado/env/lib/python3.4/site-packages/django/db/models/fields/files.py" in generate_filename
  328.             directory_name, filename = os.path.split(self.upload_to(instance, filename))

File "/Users/redpelle/PycharmProjects/ubivado/ubivado_project/ubivado/models.py" in event_directory_path
  10.     return 'events/org_{0}/{1}/{2}'.format(instance.organizer.id, time.strftime("%Y-%m-%d"), filename)

Exception Type: AttributeError at /add-event/
Exception Value: 'Organizer' object has no attribute 'id'

编辑2(已解决):

在models.py中,我有:

def event_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'events/org_{0}/{1}/{2}'.format(instance.organizer.id, time.strftime("%Y-%m-%d"), filename)

我必须更正instance.organizer.id中的instance.organizer.user_id

我没有注意到,因为PyCharm建议我一个&#34; id&#34;具有自动完成功能的字段。谢谢@Daniel Roseman

0 个答案:

没有答案