2014-06-16 75 views
0

我正在嘗試使用Django中的下拉菜單創建導航系統。我目前已經啓動並運行,以便用戶可以選擇一個鏈接並進入視圖。我面臨的挑戰是如何將view和Project.id傳遞給視圖,然後使用這兩個變量重定向到正確的視圖。僅供參考 - 這是一個學習項目 - 所以我知道我的代碼是不是很大根據下拉菜單選擇渲染不同的視圖

<a href="/add_new_job/{{ Project.id }}">Add A New Job At This Site</a> 
<a href="/manage_jobs/{{ Project.id }}/">Manage Ongoing Jobs At This Site</a> 
<a href="/manage_site_equipment/{{ Project.id }}/">Manage Site Equipment Rentals</a> 
<a href="/manage_site_services/{{ Project.id }}/">Manage Site Services</a> 
</html> 

我知道我應該把這個信息到一個下拉菜單相似,哪裏有需要的視圖下方和project.id提交到視圖。

<form method="POST" action=""/>{% 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> 

urls.py:

url(r'^add_new_job/(?P<project_id>\d+)/$', views.add_new_job,name="add_new_job"), 
url(r'^manage_jobs/(?P<project_id>\d+)/$', views.manage_jobs,name="manage_jobs"), 
url(r'^manage_site_equipment/(?P<project_id>\d+)/$', views.manage_site_equipment,name="manage_site_equipment"), 
url(r'^manage_site_services/(?P<project_id>\d+)/$', views.manage_site_services,name="manage_site_services"), 

我知道我爲這個views.py看起來應該像下面的 - 我的挑戰是試圖找出如何更改視圖和專案編號提交重定向

views.py

def view_project(request, project_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 
    print request.POST.get('project_id') 

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


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

回答

1

想通了這一點對我自己

經由柱值

<form method="POST" action=""/>{% csrf_token %} <select name = "view_wanted"> <option value="add_new_job" >Add A New Job At This Site</option> <option value="manage_jobs" >Manage Ongoing Jobs At This Site</option> <option value="manage_site_equipment" >Manage Site Equipment Rentals</option> <option value="manage_site_services" >Manage Site Services</option> </select> <input type="submit" value="View Details" /> </form>

和相關視圖提交所需的視圖(view_wanted)

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 = {} 
    #print request.POST.get('view_wanted') 

    if request.method == 'POST': 
     view_wanted = request.POST.get('view_wanted') 
     return redirect(reverse(view_wanted, args=(project_id,))) 
相關問題