是否可以在urls.py中使用django捕获URL参数?
我想写一些优雅的代码,不想在代码中依赖请求对象。所有的例子都是用这样的方式: (r'^hello/(?P.*)$', 'foobar.views.hello'),但看起来用表单向这样的URL发送请求并不太容易。有没有办法让这个URL能响应类似于..../hello?name=smith 这样的请求呢?
2 个回答
0
你不能在URL模式中捕捉到GET参数。就像在django.core.handlers.base.BaseHandler.get_response
中看到的,只有URL中最终进入request.path_info
的部分会被用来解析URL:
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
request.path_info
并不包含GET参数。要处理这些参数,可以参考Ninefingers的回答。
3
当然可以。如果你的网址对应一个函数,比如说 foobar.views.hello
,那么这个函数在处理GET请求时可能会是这样的:
def hello(request):
if request.method == "GET":
name_detail = request.GET.get("name", None)
if name_detail:
# got details
else:
# error handling if required.
如果你通过HTTP POST发送数据,比如说POST参数,可以通过 request.POST
来获取这些数据。
如果你想自己构造一些数据,比如在POST请求中添加查询参数,可以这样做:
PARAMS = dict()
raw_qs = request.META.get('QUERY_STRING', '') # this will be the raw query string
if raw_qs:
for line in raw_qs.split("&"):
key,arg = line.split("=")
PARAMS[key] = arg
同样的,如果是在非POST请求中处理表单编码的参数,可以这样做:
FORM_PARAMS = QueryDict(request.raw_post_data)
不过,如果你想在Django中使用表单,强烈建议你看看 django.forms。这个表单库会让你的工作变得简单很多;我从来没有手动写过Django的HTML表单,因为Django的这个部分已经帮我处理了所有的工作。简单来说,你可以这样做:
forms.py:
class FooForm(forms.Form):
name = fields.CharField(max_length=200)
# other properties
甚至可以这样:
class FooForm(forms.ModelForm):
class Meta:
model = model_name
然后在你的请求中,可以把表单传递给模板:
def pagewithforminit(request):
myform = FooForm()
return render_to_response('sometemplate.html', {'nameintemplate': myform},
context_instance=RequestContext(request))
在接收这个请求的视图中:
def pagepostingto(request):
myform = FooForm(request.POST)
if myform.is_valid(): # check the fields for you:
# do something with results. if a model form, this:
myform.save()
# creates a model for you.
另外可以看看 模型表单。总之,我非常推荐使用django.forms。