I have a website i developed with django and i want it to have 2 different front-end designs but same functionality. something very similar to django multi-language functionality. So i want a user to be able to access the two designs from different url by specifying the version ie
localhost:8000/v1
I created a middleware to check the current version and revert to a default if non is found.
middleware
class VersioningMiddleware(MiddlewareMixin):
def process_request(self, request):
path = request.get_full_path()
tokens = path.split("/")
if len(tokens) > 1:
if tokens[1] in APP_VERSIONS: # APP_VERSION is a list ['v1','v2',...]
request.app_version = tokens[1]
new_url = "v1%s" % path
return HttpResponseRedirect(new_url)
and also i mapped out all app url conf using this
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^(?P<version>[a-z][0-9])?/', include('base.all_urls','')),]
So the problem with this approach is that all my views are expected to take an optional parameter version which i dont like.
So i need a better way to achieve this without having to have different codebase for different version. If i could pass the version to the view without having to specify the optional parameter to all my views, my plan is to use that version to render the appropriate template that each view render.
thanks in advance
As you said you need different versions for a frontend only and keep the functionality same.
For the frontend, you just need to change js
and css
Add "django.core.context_processors.request"
to MIDDLEWARE
of your settings.py
so that Django template would be able to access query parameters in request across all templates in the whole project
settings.py
MIDDLEWARE = [
...
...
"django.core.context_processors.request",
]
Now in your template file, you will be able to retrieve the query parameter and evaluate directly
{% if request.GET.version == 'v2' %}
loading version two... write tags, load here css,js to be loaded if version is v2
{% elif request.GET.version == 'v1' %}
loading version two... write tags, load here css,js to be loaded if version is v1
{% else %}
loading defaults.. write tags, load default css,js to be loaded if no version queried by user
{% endif %}
your URL would be like:
for v2
localhost:8000/?version=v2
for v1
localhost:8000/?version=v1
if nothing specified - default
localhost:8000
Benefits -
No need to write about this frontend versioning in backend views or urls file
Only change in HTML template can allow changing the version of the frontend
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.