我正在尝试使用/alerta/3304557/调用从URL /alerta/rio重定向到一个redirect('/alerta/rio/')。手动键入/alerta/rio/可以正常工作。

但是重定向发出了对http://localhost:8000/alerta/3304557/alerta/rio的重定向,这显然会导致404错误,因为该URL不存在。

相关代码行:

url(r'^alerta/rio/$', AlertaPageView.as_view(), name='mrj'),

url(r'^alerta/(?P<geocodigo>\d{7})/$', AlertaPageViewMunicipio.as_view(), name='alerta_cidade'),

class AlertaPageViewMunicipio(TemplateView):
template_name = 'alerta_municipio.html'

# def dispatch(self, request, *args, **kwargs):
#     municipio_gc = kwargs['geocodigo']
#     if int(municipio_gc) == 3304557: # Rio de Janeiro
#         return redirect(AlertaPageView, permanent=True, *args, **kwargs)
#     return super(AlertaPageViewMunicipio, self).dispatch(request, *args, **kwargs)

def get_context_data(self, **kwargs):
    context = super(AlertaPageViewMunicipio, self).get_context_data(**kwargs)
    municipio_gc = context['geocodigo']
    if int(municipio_gc) == 3304557: # Rio de Janeiro
        args = tuple([])
        return redirect('/alerta/rio/', permanent=False, *args, **kwargs)
    city_info = get_city_info(municipio_gc)
    alert, SE, case_series, last_year, observed_cases, min_max_est, dia = dbdata.get_city_alert(municipio_gc)
    casos_ap = {municipio_gc: int(case_series[-1])}
    bairros = {municipio_gc: city_info['nome']}
    total_series = case_series[-12:]
    total_observed_series = observed_cases[-12:]
    context.update({
        'nome': city_info['nome'],
        'casos_por_ap': json.dumps(casos_ap),
        'alerta': {municipio_gc: alert},
        'novos_casos': case_series[-1],
        'bairros': bairros,
        'min_est': min_max_est[0],
        'max_est': min_max_est[1],
        'series_casos': {municipio_gc: case_series[-12:]},
        'SE': SE,
        'data1': (dia - datetime.timedelta(2)).strftime("%d de %B de %Y"),
        'data2': (dia + datetime.timedelta(4)).strftime("%d de %B de %Y"),
        'last_year': last_year,
        'look_back': len(total_series),
        'total_series': ', '.join(map(str, total_series)),
        'total_observed': total_observed_series[-1],
        'total_observed_series': ', '.join(map(str, total_observed_series)),
        'geocodigo': municipio_gc,
    })
    return context


我究竟做错了什么?

最佳答案

您必须在dispatch method中执行重定向:

def dispatch(self, request, *args, **kwargs):
    municipio_gc = kwargs.get('geocodigo', 0)
    if int(municipio_gc) == 3304557: # Rio de Janeiro
        args = tuple([])
        return redirect('/alerta/rio/')

    return super(AlertaPageViewMunicipio, self).dispatch(request, *args, **kwargs)


注意:您的'/alerta/rio/'视图不接受任何参数,因此请避免在执行重定向时传递* args和** kwargs。

更新:

正如@Alasdair指出的那样,最好是从** kwargs中获取geocodigo,而不要调用get_context_data来访问context['geocodigo']的值。

08-17 00:07