Issue with FORCE_SCRIPT_NAME Configuration in Django

I have to use FORCE_SCRIPT_NAME to set the app name. The problem is when I go from one page to another it set the script name behind de url. Below is the code

#setting.py FORCE_SCRIPT_NAME = "/myapp/"

#urls.py(myapp)
    urlpatterns = [
        path('', views.index, name='index'),
        path('another-page/', views.another_page, name='another_page'),
    ]

#urls.py(project
    urlpatterns = [
        path("admin/", admin.site.urls),
        path('myapp/', include('myapp.urls')),
    ]

#views.py
    def index(request):
        return render(request, 'home.html')

    def another_page(request):
        return render(request, 'another_page.html')


As a result when I go from home to another_page the url is: http://127.0.0.1:8000/myapp/myapp/another-page/

How do I fix this?

This is the code for the home page

    <body>
        <h1>Welcome to the Home Page!</h1>
        <a href="{% url 'another_page' %}">
            <button type="button">Go to Another Page</button>
        </a>
    </body>

Try replacing {% url 'another_page' %} with {{ request.script_name }}another-page/ directly in the template or you can create a custom template tag:

from django import template
from django.urls import reverse
from django.conf import settings

register = template.Library()

@register.simple_tag
def url_with_prefix(view_name, *args, **kwargs):
    return settings.FORCE_SCRIPT_NAME + reverse(view_name, args=args, kwargs=kwargs)

In your template:

{% load custom_tags %}
<a href="{% url_with_prefix 'another_page' %}">
    <button type="button">Go to Another Page</button>
</a>

Also you can pass the URL in the view context:

from django.urls import reverse

def index(request):
    another_page_url = request.script_name + reverse('another_page')
    return render(request, 'home.html', {'another_page_url': another_page_url})
Back to Top