Home > Blockchain >  Django: Passing variable from view to view via url link
Django: Passing variable from view to view via url link

Time:11-07

I am learning Django and as part of a project, am trying to reference a topic from view1 called "page" (containing content) to be passed into view2 called "editpage" (where I can edit the respective topic).

I believe one way to do this is via sessions, but given I only need to reference the topic a single time when the user wants to edit view1 - is there a way to pass the topic from view1 to view2 without sessions and forget the topic once the edit has been made?

From the best answer to the question below, it seems I can do it via redirects? But I cannot find a way to use redirects with url links. Django Passing data between views

My attempted approach was to have the editpage url contain the topic from view1, but I do not know how to pass the topic between the two views.

Attempted code below for page and editpage in urls.py, views.py, page.html and editpage.html:

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("editpage/<str:topic>", views.editpage, name="editpage"),
    path("<str:topic>", views.page, name="page"),
]

views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django import forms
from . import util

def page(request, topic):
    if util.get_entry(f"{topic}"):
        return render(request, "encyclopedia/page.html", {
            "content": util.get_entry(f"{topic}"), "topic": f"{topic}"
        })
    else:
        return render(request, "encyclopedia/notfound.html")

def editpage(request, topic):
    if request.method == "POST":
        title = request.POST.get("topic")

        # need to pull the title from the previously linked page

    else:
        return render(request, "encyclopedia/editpage.html", {
            "form": NewSubmissionForm()
        })

page.html

{% extends "encyclopedia/layout.html" %}

{% block title %}
    {{ topic }}
{% endblock %}

{% block body %}
    <a href="{% url 'editpage' %}">Edit this page</a><br>
    {{ content }}

{% endblock %}

editpage.html

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Edit Page 
{% endblock %}

{% block body %}
    <h1>Edit page</h1>

    <form action="{% url 'editpage' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="submit">    
    </form>


{% endblock %}

Thanks in advance and appreciate any help!

CodePudding user response:

You have to add the parameter to your url link like this...

    <a href="{% url 'editpage' topic=topic %}">Edit this page</a><br>
  • Related