Search code examples
djangodjango-formsdjango-urlsdjango-tables2

Django use the current url parameters to pass it to a form


I need to use the current url parameters and pass it to a form. The thing is that I'm displaying the results in a table using Dango-tables2 so I want to add a payemnt to that specific results using the 'Agregar Pago' button

enter image description here

I have tried with no luck to get the values '1' and '2020-W08' so I can initialize the form with the fields:

  • carro = 1
  • semana = 2020-W08

and the other fields ready for the user to type the values. So the user only enters the values and are applied to that specifica carro and semana.

in my html tag I have tried:

<a href={% url 'pagoaexistente' request.get_full_path %}><button type="button" class="btn btn-primary" >

but it gives me the complete path in 1 argument which is not what I want.

I have not found a way to get those two values from the table, let's say from the firs row get carro and semana, but I feel that is not correct to do it that way.


Solution

  • I found the answer here:

    How to get parameters from current url

    and this is how it worked for me:

    <a href={% url 'pagoaexistente' request.resolver_match.kwargs.carro request.resolver_match.kwargs.semana %}><button type="button" class="btn btn-primary" >
    

    with that I get the 2 parameters.

    Cheers!

    UPDATE

    I made another change in the HTML tag:

    <a href={% url 'pago_existente' carro=request.resolver_match.kwargs.carro semana=request.resolver_match.kwargs.semana %}><button type="button" class="btn btn-primary" >
    

    And also my view is like this:

    views.py

    class AgregarPagoSemana(CreateView):
    
        template_name = "AC/add_paymentexistingweek.html"
        model = Pagos
        form_class = AgregarPagoTransaccionExistente
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context.update({
                'semana': self.kwargs['semana'],
                'carro': self.kwargs['carro'],
            })
            return context
    
        def get_form_kwargs(self):
            kwargs = super(AgregarPagoSemana, self).get_form_kwargs()
            kwargs['carro'] = self.kwargs.get('carro')
            kwargs['semana'] = self.kwargs.get('semana')
            return kwargs