Home > Mobile >  Redirecting to next url with additional parameters using LoginView
Redirecting to next url with additional parameters using LoginView

Time:12-07

I have a detail page /spaces/<int:pk>/ where an unauthenticated user can enter form data.

Upon submitting the form, this data is appended to the url like:

/spaces/<int:pk>/?product_id=1&start_date=2022-12-23&duration=1

The user is then prompted to login or register to continue. Upon clicking login, the detail page url is appended as a next parameter to the login url.

/login/?next=/spaces/1/?product_id=14&start_date=2022-12-23&duration=1

However, after logging in and redirecting back to the detail page, the url looks like:

/spaces/1/?product_id=14

This is because the url is split with & when parsed, so the start_date and duration are considered as separate parameters.

The only solution i can think of is to override LoginView.get_redirect_url and append each parameter from self.request.GET separately, but I'm not sure that is the best approach here.

My goal is to preserve the initial input data so that the user does not have to input it again after logging in and landing back on the space detail page. For conversion reasons, I do not want to force the user to login before entering the initial form data.

EDIT: I am using javascript set the href on the Login and Register buttons:

const onClick = () => {
  let prodId = document.getElementById('productId').value;
  let startDate = document.getElementById('startDate').value;
  let duration = document.getElementById('duration').value;
  const url = new URL(window.location.href);
  url.searchParams.set('product_id', prodId);
  url.searchParams.set('start_date', startDate);
  url.searchParams.set('duration', duration);
  window.history.replaceState(null, null, url);

  const queryString = window.location.search;
  document.getElementById('login').href = `{% url 'login' %}?next={{request.path}}${queryString}`;
  document.getElementById('register').href = `{% url 'register' %}?next={{request.path}}${queryString}`
}

CodePudding user response:

You need to urlencode the querystring (and the path), properly, so:

const queryString = encodeURIComponent(window.location.search);
document.getElementById('login').href = `{% url 'login' %}?next={{ request.path|urlencode }}${queryString}`;
document.getElementById('register').href = `{% url 'register' %}?next={{ request.path|urlencode }}${queryString}
  • Related