django - 无类型对象没有属性 Django 租户
问题描述
我想在数据库中添加多对多字段,在 django 租户应用程序中出现上述错误,代码如下
@login_required()
def create_tenant(request):
subscription = Subscription.objects.get(user=request.user)
if subscription.status == "active":
if request.method == 'POST':
form = ClientForm(request.POST or None, request.FILES or None)
if form.is_valid():
logo = form.cleaned_data.get('logo')
brand = form.cleaned_data.get('brand')
seq_no = list(range(5000, 9000))
random.shuffle(seq_no)
seq_no = seq_no.pop()
schema_name = f'Domain{seq_no}'
name = f'UID-{seq_no}'
location = form.cleaned_data.get('location')
tenant = Client(schema_name=schema_name,
name=name,
user=request.user,
logo=logo,
brand=brand,
)
instance = tenant.save()
for obj in location:
print(obj)
instance.location.add(obj)
return redirect('create_domain')
else:
form = ClientForm()
return render(request, 'form.html', {'form': form})
else:
return redirect('home')
模型.py
class Client(TenantMixin):
name = models.CharField(max_length=100)
brand = models.ForeignKey(
Brand, related_name='gym_client', on_delete=models.CASCADE, blank=True, null=True
)
location = models.ManyToManyField(
Location, blank=True
)
user = models.OneToOneField(
User, related_name='clients', on_delete=models.CASCADE, blank=True, null=True
)
错误
Traceback:
File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "/home/biju/Documents/mtenant/clients/views.py" in create_tenant
71. instance.location.set(obj)
Exception Type: AttributeError at /create/tenant/
Exception Value: 'NoneType' object has no attribute 'location'
我从表单中获取选定的位置,因为我可以看到它在终端中打印,我尝试过的方法,我认为通常适用于多对多,不知道为什么它会抛出错误。求指教,谢谢
解决方案
tenant.save()
总会回来None
的。您可以tenant
直接使用该对象而不是instance
:
...
tenant = Client(...)
tenant.save()
for obj in location:
tenant.location.add(obj)
...
或使用.create()
将为您保存实例的默认管理器(.objects)的方法:
tenant = Client.objects.create(...)
for obj in location:
tenant.location.add(obj)
推荐阅读
- typescript - 需要在国家名称 typescript 或 lodash 上对具有两个字符串元素(国家)的对象数组进行排序
- python - Pyfirmata util.Iterator 导致多个 Arduino 出现串行通信问题
- pptxgenjs - 无法在浏览器中使用 pptxgenjs 将图像添加到幻灯片
- r - 将制表符分隔数据导入 R
- python - ETL 管道中的 OO 方法
- kubernetes - CronJob 没有持续运行
- apache-spark - 在 GCP 中调用云函数
- python - 如何在集群中通过 slurm 运行 python 脚本?
- string - Zapier Formatter - 字符串中的 Hashtags 单词和豁免
- c# - 如果用户关闭 displayAlert,如何停止 imagecropper 插件中的活动指示器?