0

When I am using reverse() to redirect to a different view with some optional kwargs, as a response from the view I want to display an alert message on load of a template if a key is passed in context dictionary based on that kwarg arg which came in. This is happening fine. But as the url contains the optional path parameter any call to same view with filters is displaying the alert again and again.I want to remove that optional path parameter on display of that alert.

This is my view to calling reverse -

return HttpResponseRedirect(reverse('data_asset_formats_msg', kwargs={'msg':"Unauthorized to delete DAF-%s"%data_asset_format.data_asset_format_id}))

This is my urls -

url(r'^data_asset_format/(?P<msg>.*)/', views.data_asset_formats, name='data_asset_formats_msg'),

This is the implementation of the view data_asset_formats -

def data_asset_formats(request, **kwargs):

    logr.info(kwargs)
    msg = kwargs.get('msg', '')
    logr.info(msg)
    data_asset_format_list = EdfDataAssetFormat.objects.order_by('data_asset_format_name')
    field_filter = DataAssetFormatFilter(request.GET, queryset=data_asset_format_list)

    context = {'data_asset_format_list': data_asset_format_list, 'filter': field_filter, 'msg':msg}
    return render(request, 'edf/data_asset_formats.html', context)

In the template - edf/data_asset_formats.html

<script>
    {% if msg %}
        var msg = '{{msg}}';
        alert(msg);    
    {% endif %}

</script>

As the url path param contains the optional argument whenever the filters are filtering on this form , the param is passed along and the alter is shown on any search.

I want the template to not display the alert again and again on every filter search.

gagana
  • 73
  • 1
  • 1
  • 6
  • 3
    I advice to use the [Django *message framework*](https://docs.djangoproject.com/en/2.2/ref/contrib/messages/) instead of implementing your own solution. Not only is this simpler, it is already tested by a lot of Django users, and therefore will likely be less error prone than your own implementation. – Willem Van Onsem Aug 06 '19 at 10:13
  • Adding it in the URL itself is really not the right way to do this. As @WillemVanOnsem mentioned, there is already a built-in way for exactly this purpose. – dirkgroten Aug 06 '19 at 10:27
  • https://docs.djangoproject.com/en/2.2/ref/contrib/messages/ – bruno desthuilliers Aug 06 '19 at 11:44
  • @WillemVanOnsem Thanks. I used Django messages framework. I was able to display messages in template passed from View but not pass the messages while redirecting or using HttpResponseRedirect() .I could find a solution to my problem following the below answer - https://stackoverflow.com/questions/44784936/redirect-while-passing-message-in-django. Please let me if there is a better way to do it. – gagana Aug 06 '19 at 15:31

0 Answers0