I wanted to add a many to many field to the db, in a django tenants application getting the above error, the code is as follows
@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')
models.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
)
error
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'
I am getting selected locations from form as I can see it printing in terminal, the method I tried, I think usually works for many to many, don't know why it is throwing error. Looking for an advice, thank you