You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:修改基于类的视图GET请求中的URL格式

没问题,我来帮你把URL改成更友好的localhost/reporting/run_name格式,分几步操作就搞定:

第一步:更新URL配置

首先在项目的urls.py里新增一个匹配run_name的URL规则,让Django能识别这种路径格式:

from django.urls import path
from .views import ReportView

urlpatterns = [
    # 保留原有的reporting路径(用于展示表单)
    path('reporting/', ReportView.as_view(), name='reporting'),
    # 新增带run_name的路径,用于跳转后的页面
    path('reporting/<str:run_name>/', ReportView.as_view(), name='reporting-run'),
]

这里的<str:run_name>会自动捕获URL中的字符串,作为参数传递给视图的kwargs。

第二步:修改视图的GET请求处理逻辑

现在需要让视图在收到带run主键的请求时,自动重定向到带run_name的URL,同时支持直接访问run_name路径的场景。更新你的ReportView:

from django.shortcuts import get_object_or_404, redirect, reverse
from django.views.generic import View
from django.shortcuts import render
from .models import Run
from .forms import RunSearchForm, SampleSearchForm

class ReportView(View):
    runsearchform = RunSearchForm
    samplesearchform = SampleSearchForm

    def get(self, request, *args, **kwargs):
        # 处理直接访问run_name的情况
        run_name = kwargs.get('run_name')
        if run_name:
            # 根据唯一的run_name获取Run对象(确保run_name字段设置了unique=True)
            run = get_object_or_404(Run, run_name=run_name)
            context = {
                'runsearchform': self.runsearchform(),
                'samplesearchform': self.samplesearchform(),
                'selected_run': run  # 传递选中的Run给模板展示
            }
            return render(request, 'your_template.html', context)
        
        # 处理旧的带run主键的请求,重定向到新URL
        run_id = request.GET.get('run')
        if run_id:
            run = get_object_or_404(Run, pk=run_id)
            # 生成目标URL
            target_url = reverse('reporting-run', kwargs={'run_name': run.run_name})
            return redirect(target_url)
        
        # 正常展示两个表单的场景
        context = {
            'runsearchform': self.runsearchform(),
            'samplesearchform': self.samplesearchform()
        }
        return render(request, 'your_template.html', context)

第三步:优化表单提交方式(可选但推荐)

如果你的表单当前是用GET方法提交的,URL会暴露查询参数,建议改成POST方法更规范:
在模板里修改RunSearchForm的提交方式:

<form method="post" action="{% url 'reporting' %}">
    {% csrf_token %}
    {{ runsearchform }}
    <button type="submit">Search for run</button>
</form>

然后在视图里添加POST方法的处理逻辑:

def post(self, request, *args, **kwargs):
    runsearchform = self.runsearchform(request.POST)
    samplesearchform = self.samplesearchform()

    if runsearchform.is_valid():
        # 从表单获取选中的Run对象(假设表单里有run字段)
        run = runsearchform.cleaned_data.get('run')
        if run:
            target_url = reverse('reporting-run', kwargs={'run_name': run.run_name})
            return redirect(target_url)
    
    # 表单验证失败时,返回原页面并保留错误信息
    context = {
        'runsearchform': runsearchform,
        'samplesearchform': samplesearchform
    }
    return render(request, 'your_template.html', context)

关键注意点

  • 确保Run模型的run_name字段设置了unique=True,避免查询时出现多个匹配结果:
class Run(models.Model):
    run_name = models.CharField(max_length=255, unique=True)
    # 其他模型字段...
  • 如果需要处理run_name不存在的情况,可以自定义404页面,或者跳转回表单页面提示错误。

内容的提问来源于stack exchange,提问作者trouselife

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:43:24