Home > other >  Django - How to pass current url parameters if any to a new url after pressing a button
Django - How to pass current url parameters if any to a new url after pressing a button

Time:04-28

My current page has a filter that the user can fill if wanted.

def charts_wallet_view(request):

 result = {}
 filtered_date1 = request.GET.get('fecha_inicio', '')
 filtered_date2 = request.GET.get('fecha_fin', '')
 context = {
    'mes_inicio' : mes_inicio,
    'mes_fin' : mes_fin,
    }
 return render(request, 'wallet.html', context)

In wallet.html there is a button that redirects the user to a new url that downloads a file:

<a  href="{% url "export_wallet" %}">

My question is: How I can pass the parameters (fecha_inicio and fecha_fin) to the new url/view? First i thought on doing something like that:

<a  href="{% url "export_wallet" mes_inicio mes_fin %}">

But it does not work. Then I though that i also need to add the two parameters in the url.py too:

path('export_wallet/<str:mes_inicio>/<str:fecha_fin >', views.export_wallet_view, name='export_wallet')

And in the export_wallet view:

def charts_wallet_view(request, mes_inicio,mes_fin):
  #view logic

But this does not work when no value is passed in the parameters.

CodePudding user response:

EDIT since the question changed: It makes more sense to do a POST here probably instead of a GET.

path('export_wallet/', views.export_wallet_view, name='export_wallet'), 

.inline {
  display: inline;
}

.link-button {
  background: none;
  border: none;
  color: blue;
  text-decoration: underline;
  cursor: pointer;
  font-size: 1em;
  font-family: serif;
}
.link-button:focus {
  outline: none;
}
.link-button:active {
  color:red;
}
<form method="post" action="{% url 'export_wallet' %}" >
  <input type="hidden" name="fecha_inicio" value="{{ fecha_inicio }}">
<input type="hidden" name="fecha_fin" value="{{ fecha_fin }}">
  <button type="submit" name="submit_param" value="submit_value" >
    This is a link that sends a POST request
  </button>
</form>

then in your export_wallet_view:

fecha_fin = request.POST.get("fecha_fin")
  • Related