【问题标题】:Django `request.query_params.get("page")` returns None?Django `request.query_params.get("page")` 返回无?
【发布时间】:2021-08-05 02:39:23
【问题描述】:

当我用户在搜索框中输入并提交时,这就是我设置 url 的方式:

  const submitHandler = (event: FormEvent) => {
    event.preventDefault();
    if (keyword) {
      Router.push({ pathname: "", query: { keyword: keyword, page: 1 } });
    } else {
      Router.push(Router.router?.asPath as string);
    }
  };

这就是它在 url 上的样子:"http://localhost:4500/?keyword=ca&page=1"

我使用 Next.js 作为前端,这就是我发送查询参数的方式。

export const getServerSideProps = wrapper.getServerSideProps(
  async (context) => {
    const { store, query } = context;
    console.log("params", query);
    store.dispatch(fetchProductsStart(query));
    store.dispatch(END);
    await (store as SagaStore).sagaTask.toPromise();
    const state = store.getState();
    const productListState = state.productList ? state.productList : null;
    return { props: { productListState } };
  }
);

console.log("params", query) 返回此对象:“{关键字:'g',页面:'1'}”。这就是我要发送到后端的内容。 这里是“fetchProductsStart”

export const fetchProductsStart = (
queryParams: {keyword:string,page:string}
): actions.IFetchProductsStart => ({
  type: ProductListActionTypes.PRODUCT_LIST_START,
  payload: queryParams,
});

这就是我尝试在后端获取参数的方式:

@api_view(['GET'])
def getProducts(request):
    q=request.query_params.get("page")
    print("page query param",q)
    query = request.query_params
    print("query_params",query)

print("page query param",q) 返回“无”

print("query_params",query) 返回“

到目前为止,我正在发送一个对象。相反,我将其字符串化“

store.dispatch(fetchProductsStart(JSON.stringify(query)));

现在在后台

query = request.query_params
print("query",query)

打印:query <QueryDict: {'{"keyword":"m","page":"1"}': ['']}>

request.query_params.get("keyword") 仍然无法正常工作。它返回无

【问题讨论】:

  • 可以分享一下 fetchProductsStart 函数吗?您确定“查询”的内容是作为查询参数发送的吗?
  • q=request.query_params.get("page") 寻找页面 in<url>/?page=<your query> 看起来请求 url 中没有参数 page
  • @ItsMilann 这是浏览器上的网址:“localhost:4500/?keyword=ca&page=1
  • request.GET.get("page")
  • @acw 它返回这个:('[object Object]', '')

标签: python django redux next.js query-parameters


【解决方案1】:

尝试获取这样的请求参数request.GET.get('param_name')

【讨论】:

    【解决方案2】:

    问题在于我如何将查询参数传递到后端:

    而不是这个store.dispatch(fetchProductsStart(JSON.stringify(query)))

    store.dispatch(
      fetchProductsStart(`keyword=${query["keyword"]}&page=${query["page"]}`)
    );
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2015-01-10
      • 2019-07-03
      • 2013-09-10
      • 2014-05-14
      • 2020-08-09
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多