how to Pass variable in link to the django view how to Pass variable in link to the django view mongodb mongodb

how to Pass variable in link to the django view


First of all, its not advisable to use html name when you add a url. Instead of having

href="/product/product.html"

you could have just had something like

href="/product/"

so in your urls.py you should have it defined as below

url(r'^product/$', product),

where 'product ' is the corresponding view handling that request.

Now if you want to send some parameters to django from the html

render your template as below

<tbody id="table">    {% for sku, lid, stk, mrp, sp, stts in product_data %}    <tr>        <td>            <a class="btn-link" href="/product/?sku={{ sku }}">{{sku}}</a>        </td>        <td>{{lid}}</td>        .....

and in your view i.e; at products

def product(request):    if request.method=='GET':        sku = request.GET.get('sku')        if not sku:            return render(request, 'inventory/product.html')        else:            # now you have the value of sku            # so you can continue with the rest            return render(request, 'some_other.html')


It can be done in 2 ways, using get and using URL parameter.

Using get is simply and flexible, but will lead to ugly URLs:

            <a class="btn-link" href="/product/product.html?parameter={{ your_parameter_here }}" value="{{sku}}">{{sku}}</a>

And inside view, you can access it like this:

def product(request):    your_parameter = request.GET['parameter']    return render(request, 'inventory/product.html')

Using url parameters is much better way, it is also more DRY than get parameters (especially when not using {% url %} tag with get).

Your urls.py should look like this:

urlpatterns = [    url(r'^product/product-(?P<parameter>[\w-]+).html', 'views.product', name="product"),]

Getting that parameter in view:

def product(request, parameter): # it's just passed as kwarg into view    return render(request, 'inventory/product.html')

and creating URL in your template:

            <a class="btn-link" href="{% url "product" parameter=your_parameter_here %}" value="{{sku}}">{{sku}}</a>