简体   繁体   中英

Django - Pass Object ID after redirect

Apologies if the question title is wrong but I am unsure of exactly what I need to do. I am building a scrum app where users can create user stories and add them to sprints. I want to have two separate ways of creating stories. If the user is creating a story from the backlog, the story that has been created will not be assigned to a sprint, but the user can also add a story from a sprint's detail screen. I want to make it so that if they add a story from a specific sprint's page, that story's sprint field is populated with that sprint.

The way I have tried to go about this is by creating two different functions in my views.py file and two separate templates. I am able to create the story without relating to a sprint as intended, but I cannot think of a way to get the id of the sprint where I navigated from to get to the new template.

For reference I have included my function for creating stories without relating to a sprint:

def create_story(response, id=None):
    user = response.user
    if response.method == "POST":
        form = CreateNewUserStory(response.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]
            description = form.cleaned_data["description"]
            status = form.cleaned_data["status"]
            assignee = form.cleaned_data["assignee"]
            estimate = form.cleaned_data["estimate"]
            userstory = UserStory(name=name, description=description, status=status, assignee=assignee, estimate=estimate)
            userstory.save()
            response.user.userstories.add(userstory)
            return HttpResponseRedirect("/backlog")
    else:
        form = CreateNewUserStory()
    return render(response, "main/create_story.html", {"form": form})

If any more information or code is required please let me know, thank you!

You can define 2 URLs, one with an optional sprint ID:

urls.py :

path('story/<int:sprint_id>/add/', views.create_story, name='create_story_for_sprint'),
path('story/add/', views.create_story, name='create_story_for_backlog'),

views.py :

def create_story(request, sprint_id=None):
   ...
   form = CreateNewUserStory(response.POST, initial={"sprint_id": sprint_id})
   if form.is_valid():
       ...
       sprint_id = form.cleaned_data["sprint_id"]

create_story.html :

<form action="..." method="POST">
    <input type="hidden" name="sprint_id" value="{{ sprint_id|default_if_none:'' }}">
    ...

Then, in your sprint page, use

<a href="{% url 'create_story_for_sprint' sprint.id %}">Add Story</a>

and in your backlog page:

<a href="{% url 'create_story_for_backlog' %}">Add Story</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM