【问题标题】:django python: missing 1 required positional argumentdjango python:缺少1个必需的位置参数
【发布时间】:2017-10-20 15:08:36
【问题描述】:

我正在尝试定义一个有 4 个参数的函数,但我的第四个参数遇到了问题,而且我很确定这很愚蠢。这是我的代码:

views.py:

def create_recording(request, slug, inspection_id, component_id):
    inspection = get_object_or_404(Inspection, pk=inspection_id)
    plant = get_object_or_404(Plant, slug=slug)
    component=get_object_or_404(Component, pk=component_id)
    if request.method == "POST":
        form = RecordingForm(request.POST)
        if form.is_valid():
            recording = form.save(commit=False)
            recording.plant = plant
            recording.inspection=inspection
            recording.component=component
            recording.save()
            return redirect('data:inspection_detail', slug=plant.slug, inspection_id=inspection.id)
    else:
        form = RecordingForm()
    context = {'form': form, 'plant':plant,'inspection':inspection}
    template = 'data/create_recording.html'
    return render(request, template, context)

这是我的 html 文件:

<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=1 %}">
   <button type="button" class="btn btn-success">
        <span class="glyphicon glyphicon-plus"></span> Chaiir
   </button> 
</a>
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=2 %}">
   <button type="button" class="btn btn-success">
        <span class="glyphicon glyphicon-plus"></span> Table
   </button> 
</a>

网址:

url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording$', views.create_recording, name='create_recording'),

我收到以下错误:

Exception Type: TypeError
Exception Value:create_recording() missing 1 required positional argument: 'component_id'                  

【问题讨论】:

  • HTML 模板将关键字样式的参数传递给create_recording(),而函数本身则接受普通的位置参数。您可能应该更改其中一个或另一个,以便它们都使用相同的样式。
  • id=1 有什么问题?传递 id=1 时显示什么错误?

标签: python django


【解决方案1】:

你的问题在这里

<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=2 %}">

您没有发送视图所期望的component_id。

编辑: 您的网址有问题:

url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording/(?P<component_id>[\d]+)$', views.create_recording, name='create_recording'),

【讨论】:

  • 你是对的!但这只是我的问题中的一个错字,我更正了!现在是正确的
  • 所以您的问题仍未解决?如果是这样,则可能是您的 URL 模式存在问题。您可以编辑问题以显示 url 模式吗?
  • 您是否注意到您没有在 url 模式中捕获 component_id?如果您不捕获它,视图将不会接收它。因此例外。检查编辑。
  • 它可以工作,但它不需要 component_id=1 我必须添加它!
  • 我希望你不要仅仅说它不工作就指望别人来帮助修复你的代码?
猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多