Pavel Antspovich
Pavel Antspovich

Reputation: 1221

How to store URLs in Django right way?

I'm new in Django and sorry for such silly question. I wonder how to store URLs right way. I have in mine .html some hardcoded URLs to third party webserveces. And I know hardcode is a bad way. It's impossible to add those URLs to urlpatterns cause url() or path() requires to set certain views which I don't have. It will be great to concatinate URLs. Should I store these URLs variables in settings.py or somewhere else? Will be appriciated for any answers.

Upvotes: 1

Views: 890

Answers (1)

Borut
Borut

Reputation: 3364

My approach would probably be something like this.

  1. Create custom context processor (api_settings.py)

    def my_api_urls(request):
        api_urls = {
            'api_1': 'https://api.example.test/',
            'api_2': 'https://api.test.example/'
        }
        return api_urls
    
  2. Add it to context processors in settings.TEMPLATES

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
            ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    # here you add path to your custom context processor 
                    # directory custom_context_processors
                    # filename api_settings
                    # function my_api_urls
                    'custom_context_processors.api_settings.my_api_urls'
                ],
                'debug': False
            },
        },
    ]
    
  3. Use it in templates with {{ api_1 }} and {{ api_2 }}.

If they change often, then I'd store them in database and simply query them in views when needed.

Upvotes: 2

Related Questions