Django - redirect a user to a page based on a choice from a drop-down menu

I am trying to use the dropdown menu in django so that the user can select an option from the menu and then go to the page.

In particular. I create a small project management system as a training project (I know that I have many other problems here - I just want to get the functions first, and then worry about the style and delete the variables that are not needed). I want the user to select the project from the drop-down menu (I can fill this out), and then go to the page with detailed information about the project. I am currently working by clicking on the links, but I want to do this when users can select an existing project and see the details.

The html form should bring the user from view_existing_projects to view_project. Right now I can go to search for views, but project_id is not passing.

urls.py

url(r'^view_project/(?P<project_id>\d+)/$', views.view_project, name='view_project'),

html form

    <form method="POST" action="/view_project/{{ project.id }}"/>{% csrf_token %}
    <select name = "project_id">
    {% for project in projects %}
    <option value="{{ project.id }}" >{{ project.address1 }}</option>
    {% endfor %}
    </select>
<input type="submit"  value="View Details" />
    </form>

views.py

def view_existing_projects(request, user_id):
    context = RequestContext(request)
    user = User.objects.get(id=user_id)
    projects = ProjectSite.objects.filter(owner__id=user.id)
    args = {}
    args.update(csrf(request))
    args['users'] = user
    args['projects'] = projects
    if request.method == 'POST':
        project_id = request.POST.get('project_id')
        args['project_id']= project_id

        return redirect('/view_project/', args,context)
    else:
        args = {}
        args.update(csrf(request))
        args['users'] = user
        args['projects'] = projects
   return render_to_response('Bapp/manage_projects.html', args,context)


def view_project(request, project_id):
    context = RequestContext(request)
    user = User.objects.get(project_sites__id=project_id)
    site = ProjectSite.objects.get(id=project_id)
    args = {}
    args.update(csrf(request))
    args['Users'] = user
    args['Project'] = site
    return render_to_response('Bapp/view_project.html', args,context)
+4
source share
1 answer

This should solve your problem:

from django.shortcuts import redirect
from django.core.urlresolvers import reverse

if request.method == 'POST':
    project_id = request.POST.get('project_id')
    return redirect(reverse('view_project', args=(project_id,)))

Another suggestion, instead of hard coding the URL path, Bapp/view_project.htmluse named URL patterns , as I used.

+3
source

Source: https://habr.com/ru/post/1544685/


All Articles