反向查找“ str_team”,但未找到任何参数。尝试了1个模式:['str_application \\-1 /(?P <startup_id> [^ /] +)/ $']

时间:2019-08-25 17:15:30

标签: python django

我有两种模型,一种是启动(在其中创建启动名称),第二种是团队(在其中动态创建额外的团队成员)。该过程分步进行,当创建启动名称并将其重定向到第二步时,出现以下错误:

Reverse for 'str_team' with no arguments not found. 1 pattern(s) tried: ['str_application\\-1/(?P<startup_id>[^/]+)/$']

据我所读,必须添加一个模板标记,以便通过URL将实例从一个模板传递到另一个模板。感谢您的帮助,以下是我的代码: URLS

from django.urls import path
from . import views


urlpatterns = [
    path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ) ,
    path ( 'str_application/' , views.startup, name = 'str_name' ) ,
    path ( 'str_application-1/<int:startup_id>/' , views.startup, name = 'str_team' ) ,
]

模型

from django.db import models


class Startup ( models.Model ) :
    startup_name = models.CharField ( 'Startup Name' , max_length = 100 )

    def __str__(self) :
        return self.startup_name


class Team ( models.Model ) :
    name = models.CharField ( 'Name' , max_length = 100 )
    position = models.CharField ( 'Position' , max_length = 100 )
    startup = models.ForeignKey ( Startup , on_delete = models.CASCADE )

    def __str__(self) :
        return str(self.startup)

class Req_Fund(models.Model):
    startup_2 = models.ForeignKey ( Startup , on_delete = models.CASCADE )
    funds = models.DecimalField ( 'Requested Fund' , max_digits = 14 , decimal_places = 2 , null = False , blank = False )
    product_development = models.DecimalField ( 'Product Development' ,max_digits = 14 , decimal_places = 2 , null = False , blank = False)
    marketing_sales = models.DecimalField ( 'Marketing/Sales' , max_digits = 14 , decimal_places = 2 , null = False , blank = False)
    operation_inventory = models.DecimalField ( 'Operations/Inventory' , max_digits = 14 , decimal_places = 2 , null = False , blank = False)
    legal_other = models.DecimalField ( 'Legal/Others' ,max_digits = 14 , decimal_places = 2 , null = False , blank = False)

    def __str__(self) :
        return str(self.startup_2)

表格

from .models import *
from django import forms

class StartupNameForm (forms.ModelForm):
    class Meta:
        model = Startup
        fields = ['startup_name',]

class TeamForm (forms.ModelForm):
    class Meta:
        model = Team
        fields = ['startup','name','position',]
        widgets = { 'startup' : forms.HiddenInput ( ) }

class ReqFund (forms.ModelForm):
    class Meta:
    model = Req_Fund
    fields = '__all__'
    widgets = { 'startup_2' : forms.HiddenInput ( ) }

观看次数

from django.forms import inlineformset_factory
from .decorators import str_required
from django.contrib.auth.decorators import login_required
from django.shortcuts import render , redirect
from .forms import *
from .models import *

@login_required ( login_url = 'str_login' )
@str_required
def str_dashboard(request) :
    return render ( request , 'str_dashboard.html' )


def startup(request ):
    if request.method == 'POST':
        form = StartupNameForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('str_team')
    else:
        form = StartupNameForm()
        return render(request, 'application/str_name.html', {'form': form})


def team(request, startup_id):
    startup = Startup.objects.get(id=startup_id)
    TeamFormset = inlineformset_factory(Startup, Team, fields = ('name', 'position', 'startup'))

    if request.method == 'POST':
        formset = TeamFormset(request.POST, instance = startup)
        if formset.is_valid():
            formset.save()

        return redirect ('str_dashboard')

    formset = TeamFormset ( instance = startup )
    return render ( request , 'application/str_team.html' , { 'formset' : formset } )


def reqfund (request, startup_id):
    strup = Startup.objects.get(id=startup_id)
    if request.method == 'POST':
        form = ReqFund(request.POST)
        if form.is_valid():
            i = form.save (commit = False)
            i.startup.id = strup.id
            i.save()
        return redirect('str_dashboard')
    else:
        form = ReqFund()
        return render(request, 'application/str_rfund.html', {'form': form})

HTML模板-用于状态名称

<form method='post' href="{url 'str_name' startup_id}" >
    {% csrf_token %}
    {{form|crispy}}
    <button type='submit'>Submit</button>
</form>

HTML模板-用于团队

<form id="my-form" method="post" >
    {% csrf_token %}
    {{ formset.media }}
    <div class="individual-form">
        {{ formset|crispy }}
    </div>

    <button type='submit'>Submit</button>
</form>

错误追溯

Traceback:

File "C:\Users\Lenovo\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Lenovo\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Lenovo\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Lenovo\PycharmProjects\untitled1\sourcing\startups\views.py" in startup
  20.             return redirect('str_team')

File "C:\Users\Lenovo\venv\lib\site-packages\django\shortcuts.py" in redirect
  58.     return redirect_class(resolve_url(to, *args, **kwargs))

File "C:\Users\Lenovo\venv\lib\site-packages\django\shortcuts.py" in resolve_url
  148.         return reverse(to, args=args, kwargs=kwargs)

File "C:\Users\Lenovo\venv\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Users\Lenovo\venv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  622.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /str_application/
Exception Value: Reverse for 'str_team' with no arguments not found. 1 pattern(s) tried: ['str\\-application\\-1/(?P<startup_id>[0-9]+)$']

2 个答案:

答案 0 :(得分:1)

您需要将主键作为参数传递给URL,例如:

def startup(request ):
    if request.method == 'POST':
        form = StartupNameForm(request.POST)
        if form.is_valid():
            result = form.save()
            return redirect('str_team', startup_id=result.pk)
    else:
        form = StartupNameForm()
    return render(request, 'application/str_name.html', {'form': form})

请注意,在return render(..)情况(如果表单无效)和if情况(如果它是GET请求)中都应执行else

此外,还有另一个问题,您的__str__中的Team不会返回str,而返回Startup

class Team(models.Model) :
    name = models.CharField ('Name', max_length =100)
    position = models.CharField ('Position', max_length=100)
    startup = models.ForeignKey (Startup, on_delete=models.CASCADE)

    def __str__(self) :
        return str(self.startup)

答案 1 :(得分:1)

第三个URL路径写错了。 应该这样写。

path('str-application-1/<int:startup_id>',...)