如何使用查询字符串django重定向到URL

时间:2013-11-05 08:44:43

标签: python django

的AoA,   如何使用参数(如果我有视图

)转到特定URL
def search(request):

和urls.py

^search/$ 

我需要做的是重定向search/?item=4

c = {}
render_to_response("search.html",c) 

工作正常,但

render_to_response("search.html/?item=" + itemID, c )

它说找不到模板(我知道没有像search.html /?item =这样的模板)但是如何传递参数或使用查询字符串进行重定向?

4 个答案:

答案 0 :(得分:22)

答案很简单。使用反向和传递url的名称可以使用查询字符串

重定向到url

urls.py

url(r'^search/$', views.search, name='search_view')

views.py

from django.shortcuts import redirect, reverse

# in method
return redirect(reverse('search_view') + '?item=4')

答案 1 :(得分:7)

我知道这个问题有点陈旧,但有人会在搜索重定向查询字符串时偶然发现这个问题,所以这是我的解决方案:

override func viewDidLoad() {
    super.viewDidLoad()

    let myDefaults = UserDefaults(suiteName: "group.com.iOSApp")!
    let eventData = myDefaults.object(forKey: "events")

    if eventData != nil {
        shownEvents = NSKeyedUnarchiver.unarchiveObject(with: eventData as! Data) as! [Event]
    }

    eventTable = UITableView()
    eventTable.register(TodayViewCell.self, forCellReuseIdentifier: "cell")
    eventTable.separatorColor = UIColor.primary()
    view.addSubview(eventTable)
    eventTable.translatesAutoresizingMaskIntoConstraints = false

    var tempX = NSLayoutConstraint(item: eventTable, attribute: .leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    var tempY = NSLayoutConstraint(item: eventTable, attribute: .top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .top, multiplier: 1, constant: 0) 
    NSLayoutConstraint.activate([tempX, tempY])

    tempX = NSLayoutConstraint(item: eventTable, attribute: .trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    tempY = NSLayoutConstraint(item: eventTable, attribute: .bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)   
    NSLayoutConstraint.activate([tempX, tempY])


    eventTable.delegate = self
    eventTable.dataSource = self

    eventTable.reloadData()

    preferredContentSize.height = 200


}

答案 2 :(得分:1)

一个更通用的选项;

from urllib.parse import urlencode
from django.shortcuts import redirect as django_redirect


def redirect(url, *args, params=None, **kwargs):
    query_params = ""
    if params:
        query_params += '?' + urlencode(params)
    return django_redirect(url+query_params, *args, **kwargs)

答案 3 :(得分:-1)

要在携带当前查询字符串的同时重定向到另一页:

<uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_CALL_LOG" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_CALL_LOG" />

views.py