My models.py:
class fields(models.Model):
name = models.CharField(max_length=18)
link = models.TextField()
The link contains the hyperlink of the related name.
My views.py:
def index(request):
listing = fields.objects.all()
context ={'listing':'listing'}
return render(request,'index.html',context)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',index,name="index"),
]
template:
{% for i in listing %}
<tr>
<td data-label="name">{{ i.name }}</td>
<td data-label="Quote"><button><a href ="{{ i.link}} " target="_blank">{{ i.link }}</a></button></td>
<tr>
{% endfor %}
This redirects to the hyperlink that is displayed in the template but I want to do some automation after it redirects into this link.
Now, I want to pass the context of this function which only includes the link
to the other view function so that another view function will be:
def bypass_link(request):
# get the link from above function
# execute some selenium scripts in the link
The simple template to illustrate this will be:
{% for i in listing %}
<tr>
<td data-label="name">{{ i.name }}</td>
<td data-label="Quote"><button><a href ="{ % url 'bypass_link' %} " target="_blank">{{ i.link }}</a></button></td>
<tr>
{% endfor %}
CodePudding user response:
You can pass the id
of the object into the url by altering the following:
template
<td data-label="Quote">
<a href="{% url 'bypass_link' i.id %}" target="_blank">{{ i.link }}</a>
</td>
urls.py
from django.conf.urls import url
url(r'^bypass_link/(?P<pk>\d )/$', views.bypass_link, name="bypass_link"),
Then in your function you need to find the same model instance and then extract the link.
def bypass_link(request, pk=None):
instance = fields.objects.get(pk=pk)
print(instance.link) # now you have your link
Now you have access to the link via instance.link
CodePudding user response:
You can pass variable to different views in Django using session
My example is using Django 3.2, be sure that sessions requirement are set in settings.py
. But by the default config, the following example should work.
def index(request):
listing = fields.objects.all()
# The session object must be json serializable, pay attention
listing_list = [[list.name, list.i] for list in listing]
# set the session variable
request.session['listing_list'] = listing_list
context ={'listing':listing}
return render(request,'index.html',context)
def bypass_link(request):
# get the link from above function
# execute some selenium scripts in the link
# Got the session variable
listing_list = request.session.get('listing_list')
# Do what you want with it here