Home > Mobile >  Why am I getting a No Reverse Match error when submitting using UpdateView?
Why am I getting a No Reverse Match error when submitting using UpdateView?

Time:09-21

I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error:

NoReverseMatch at /MyHealth/edit/8 Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name.

I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated!

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse


class HealthStats(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    weight = models.DecimalField(max_digits=5, decimal_places=2)
    run_distance = models.IntegerField(default=5)
    run_time = models.TimeField()

    class Meta:
        db_table = 'health_stats'
        ordering = ['-date']

    def get_absolute_url(self):
        return reverse('health_hub_history')

    def __str__(self):
        return f"{self.user} | {self.date}"

urls.py:

from django.urls import path
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from . import views

app_name = 'HealthHub'

urlpatterns = [
    path('', views.home, name='home'),
    path('MyHealth/', views.health_hub, name='health_hub'),
    path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
    path('MyHealth/history', views.health_history, name='health_hub_history'),
    path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
    path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
    path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
]

Views.py:

class EditHealth(UpdateView):
    model = HealthStats
    template_name = 'health_hub_edit.html'
    fields = ['weight', 'run_distance', 'run_time']

health_hub_edit.html:

{% extends 'base.html' %}
{% load static %}
{%load crispy_forms_tags %} 

{% block content %}
<div >
    <div >
        <div >
            <h1>Edit my Data</h1>
        </div>
    </div>
</div>
<div >
    <div >
        <div >
            <form method="post" style="margin-top: 1.3em;">
                {{ form | crispy }}
                {% csrf_token %}
                <button type="submit" >Submit</button>
            </form>
        </div>
    </div>
    <div >

    </div>
</div>
{% endblock content %}

CodePudding user response:

This error occurs because the django couldn't resolve the url you didn't specify a primary key to base the query on. you should modify this function

  def get_absolute_url(self):
      return reverse('health_hub_history', kwargs={'user': self.user})

also that health_history url is it a class based view you should add .as_view() to the end and observe camel casing

Lastly your url should observe the primary key specified

CodePudding user response:

You can do this:

class EditHealth(UpdateView):
    model = HealthStats
    template_name = 'health_hub_edit.html'
    fields = ['weight', 'run_distance', 'run_time']
    def get(self, request):
        return HttpResponse("health_hub")

    def post(self, request):
       # do something
       return redirect("health_hub")


urlpatterns = patterns('',
    url('', views.home, name='home'),
    url('MyHealth/', views.health_hub, name='health_hub'),
    url('^MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
    url('MyHealth/history', views.health_history, name='health_hub_history'),
    url('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
    url('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
    url('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
)

This will solve your problem

  • Related