我正在尝试编写一些优雅的东西,在代码中我不依赖 Request 对象。所有示例都使用: (r'^hello/(?P.*)$', 'foobar.views.hello') 但似乎您无法使用表单轻松发布到这样的 URL。有没有办法让该 URL 响应 ..../hello?name=smith
最佳答案
绝对是的。如果您的 url 映射到一个函数(在本例中为 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.
如果您从 request.POST
进行 HTTP POST,则可以使用编码形式的数据,即 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))
在接收它的 View 中:
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.
另请参阅model forms 。简而言之,我强烈推荐 django.forms。
关于python - 有没有办法在 urls.py 中使用 django 捕获 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479916/