Search code examples
pythondjangodjango-modelscruddjango-urls

urls.py works but when I use <int:id> to update a particular item then I get "Current path didn't match any of these" error


My urls.py works when trying to read or create new items. But when trying to update an existing item I do the following: in app/urls.py:

...
path('update_goals/<int:id>', update_goals, name='update_goals'),

in views.py:

def update_goals(request, id):
    item = Items.objects.get(id=id)
    form = ItemFilterForm(request.POST or None, instance=item)
    if form.is_valid():  # validate the form
        form.save()
        return redirect(list_items)
    return render(request, 'items-form.html', {'form': form, 'item': item})

in models.py:

class Items(models.Model):
    id = models.AutoField(db_column='ID', primary_key=True)
    company = models.CharField(null=True, db_column='Company', max_length=40, blank=True)  # Field name made lowercase.
    ...
    class Meta:
        managed = False
        db_table = 'Items'
        verbose_name_plural = 'Items'

html:

        {% for i in item %}
        <a href="{url 'update_goals i.id'}">
                <li>{{i.company}}</li>
                ...
        </a>
        {% endfor %}

The other paths that I use to read current items and create new items work, but just the update doesn't work.

The error:

Page Not Found(404)
Request URL:    http://127.0.0.1:8000/%7Burl%20'update_goals%20i.id'%7D
Using the URLconf defined in app1.urls, Django tried these URL patterns, in this order:

...
update_goals/<int:id> [name='update_goals']
admin/
The current path, {url 'update_goals i.id'}, didn't match any of these.

It might have something to do with the ID column, but I tried using update_goals/<str:company> abd i.company as well and it still gives the same error.


Solution

  • # You just need to change url in the html file content
    
    {% for i in item %}
         <a href="{% url 'update_goals' id=i.id %}">
              <li>{{i.company}}</li>
         </a>
    {% endfor %}