0

In my app I want to create favorite system:

  • user input url
  • some data is calculated
  • then user can add this link to favorite

After clicking add, user is redirected to other endpoint which returns all his favorites links. At this point I want to add possibility which allow user to click on one of his favourites, return to other view and calculate some data.

My views.py

def home(request):
    """this function returns form which allows user to input link"""
    if request.method =='POST'
        url = request.POST['url']
        request.session['url'] = url
        return redirect('bokeh')
    return render(request,'base.html')

After this, bokeh.html is returned and has some data like charts

def bokeh(request):
    url = request.session.get('url')
    cl = CalculationLogic()
    return cl.get_data_from_url(request,url)

In this view, there is a button which allows add to favorite. After clicking, method is called:

def favorites(request):
    url = request.session.get('url')
    repo = Repository(url=url,user=request.user)
    repo.save()
    repo.repositorys.add(request.user) #adding value to ManyToMany field
    user = User.objects.get(username=request.user.username)
    repos = user.users.all() #return all url which current user has in favorites
    return render(request,'favorites.html',{'repos':repos})

And in my favorites.html

{% extends 'bokeh.html' %}

{% block content %}

<h1>Favorites repositorys for {{ user }}</h1>
{% for r in repos %}
    <br><a href="{% url 'bokeh' %}">{{ r }}</a>
{% endfor %}

{% endblock %}

So, at this point I display all of user's favorite repos. After clicking on one of them I want to go back to bokeh view and return different data based on clicked url. Is there a easy way to solve this problem?

Frendom
  • 508
  • 6
  • 24

1 Answers1

1

You might want to pass the repo id as a GET parameter, eg:

{% for r in repos %}
    <br><a href="{% url 'bokeh' %}?repo_id={{r.id}}">{{ r }}</a>
{% endfor %}

And then in views.py, something like:

def bokeh(request):
    repo = request.GET.get('repo_id')
    ...
rsomji
  • 140
  • 7
  • to clarify, my url for bokeh looks: url(r'^bokeh/$',views.bokeh,name='bokeh') To execute redirect from this loop, should it be modified or added another one? – Frendom Feb 21 '20 at 17:01
  • No need, it should work as is. If you want your URLs to appear like: `foo.com/bokeh/?repo_id=1`, nothing needs to change. However if you want your URL to appear `foo.com/bokeh/1`, with the repo ID as part of the URL itself - not as a GET parameter - then you would need to change your urls.py. There is some more detailed discussion here (https://stackoverflow.com/questions/150505/capturing-url-parameters-in-request-get) – rsomji Feb 21 '20 at 17:06