如何修复NoReverseMatch

时间:2019-08-27 14:55:36

标签: django

我正在尝试更新菜单项以添加和编辑菜单项,但是我无法移至下一页。尽管菜单项已更新或被添加。

views.py

def addMenu(request, id):
    if request.method == 'POST':
        form = menuForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('menu')
    else:
        form = menuForm()
        context = {'form': form}
    return render(request, 'addMenu.html', context)


def editMenu(request, id):
    menu = get_object_or_404(Menu, pk=id)
    if request.method == 'POST':
        form = menuForm(request.POST, instance=menu)
        if form.is_valid():
            form.save()
            return redirect('menu')
    else:
        form = menuForm(instance=menu)
        context = {'form': form}
        return render(request, 'editMenu.html', context)

models.py

class Restaurants(models.Model):
    restaurant_name = models.CharField(max_length=250, null=True, blank=True)

    def __str__(self):
        return self.restaurant_name


class Menu(models.Model):
    restaurant_name = models.ForeignKey(Restaurants, on_delete=models.CASCADE, related_name='restaurants', null=True)
    name = models.CharField(max_length=250, blank=True, null=True)
    description = models.TextField(max_length=250)
    price = models.CharField(max_length=8)
    course = models.CharField(max_length=250)

urls.py

lpatterns = [

     path('', views.showRestaurants, name='restaurants'),
     path('add/', views.addRestaurants, name='add'),
     path('edit/<id>', views.editRestaurants, name='edit'),
     path('<id>/delete/', views.deleteRestaurants, name='delete'),
     path('menu/<id>', views.showMenu, name='menu'),
     path('addmenu/<id>/', views.addMenu, name='addmenu'),
     path('menu/edit/<id>', views.editMenu, name='editmenu'),
     path('menu/<id>/delete', views.deleteMenu, name='deletemenu'),

 ]

edit.html

<form method='POST'>
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">Update</button>

            </form>

每次我单击更新时,都会带我到此错误页面

Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'menu' with no arguments not found. 1 pattern(s) tried: ['menu\\/(?P<id>[^/]+)$']

尽管菜单项已更新并添加到我的菜单列表中

1 个答案:

答案 0 :(得分:3)

您的menu网址格式带有一个ID,

 path('menu/<id>', views.showMenu, name='menu'),

但是尝试重定向时您没有提供ID:

 return redirect('menu')

您似乎应该这样做:

 return redirect('menu', id=id)