I am trying to create a random URL that can be accessed only once after the user logs in.
I am using django-sesame to generate different URLs each time the user logs in. To do this, I have set the SESAME_ONE_TIME setting to True in settings.py, and I am able to redirect the user to the random URL like this:
views.py:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .models import my_model
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
import sesame
@login_required()
def password_form(request):
url_extension = sesame.utils.get_query_string(request.user)
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user)
return redirect('/success/' + url_extension)
else:
form = PasswordChangeForm(request.user)
context = {'form': form}
return render(request, "form.html", context)
However, in urls.py I don't know how to add the URL to urlpatterns properly. This probably sounds weird, but, for a lack of better wording, is there any way you can add a parameter that can accept a randomly generated value in path, like:
urls.py:
from app.views import password_form
urlpatterns = [path('success/' + random_variable, password_form),]
If not, is there any way I can make the url_extension variable global, so that I can use it in urls.py, by bypassing the need for request (e.g. setting url_extension as an attribute to a function in views.py and using it as function.url_extension in urls.py)?
You should use a regular expression where you allow success at the starting and the anything after that. Your regular expression in url will be something like this - success/.*$. This check for a success and then allows *(everything) after /.