简体   繁体   中英

Set up subdomains for tenants in a Django web app?

I have installed django-tenant-schemas for a multitenancy SaaS app I'm trying to build. So far I have managed to create schemas in postgres so each tenant has isolated tables.

If a user goes to my website, eg www.mydomain.com, and registers by providing a username, password and company (eg "Joeys Company") - how would I dynamically create a new subdomain for that user, in this case joeyscompany.mydomain.com?

People have mentioned wildcard domains, but not sure how to practically set that up

Your question can be broken down into two smaller sub-questions.

  1. How do you specify the domain name for a tenant?

As described in the docs , when you create a tenant you use the domain_url parameter to associate a domain name with a tenant. So if you make a tenant with domain_url='tenant.mysite.com' , and a request comes to your server with the hostname tenant.mysite.com , django-tenant-schemas will automatically use the correct database schema for this tenant. This brings us to question two:

  1. How do you use DNS to point that subdomain to your application?

You are correct that the easiest way would be to set up a wildcard subdomain. Without going too deep into a DNS lesson, you would have a DNS entry like *.mysite.com , where * means "anything". This wildcard subdomain would be pointed to the IP address of the server where your application is running. As a result, anything.mysite.com will resolve to your server.

The process of setting up a wildcard subdomain will be different depending on your DNS provider. You should consult their documentation for specifics.

I actually figured it out. For anyone interested, here's the code that automatically creates a tenant upon user registration.

class SignupView(View):
    def get(self, request):
        form = RegistrationForm()
        return render(request, "accounts/signup.html", {"form": form})

    def post(self, request, *args, **kwargs):
        form = RegistrationForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            tenant = Client(domain_url=company + ".my-domain.com", schema_name=company, name=company)
            tenant.save()

            with schema_context(tenant.schema_name):
                instance.save()
                redirect = 'http://' + company + '.my-domain.com:8000/accounts/login'
                return HttpResponseRedirect(redirect)
        return render(request, "accounts/signup.html", {"form": form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM