Home > OS >  reverse lazy error NoReverseMatch at django DeleteView
reverse lazy error NoReverseMatch at django DeleteView

Time:11-27

I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url

So this is my model:

class PatientAnalysis(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    analysis_date = models.DateTimeField(help_text = "Разделяйте даты точками! Используйте '/' или '-'")
    # analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу
    analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1)
    analysis_data = models.DecimalField(max_digits=5, decimal_places=2)
    def __str__(self):
        return f"{self.patient}"
    def get_analysis_type(self):
        return f"{self.analysis_type}"
    def get_absolute_url(self):
        return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk})
    class Meta:
        unique_together = ('analysis_date','analysis_type',)

Here's the class for list all analyses per patient

class PatientAnalysisListView(ListView):
    model = PatientAnalysis
    template_name = 'journal/patient_analysis.html'
    context_object_name  = 'analysis'

    def get_context_data(self, *, object_list=None, **kwargs):
        <...>      
        
        return context

    def get_queryset(self):
        return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date')

And here i stuck with next code:

class PatientAnalysisDeleteView(DeleteView):
    # Form --> Confirm Delete Button
    # model_confirm_delete.html
    model = PatientAnalysis
    
    success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient})
    

And getting error:

NoReverseMatch at /journal/patientanalysis_delete/49

Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_] )\\Z']

Request Method:     POST
Request URL:    http://127.0.0.1:8000/journal/patientanalysis_delete/49
Django Version:     4.1.3
Exception Type:     NoReverseMatch
Exception Value:    

Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_] )\\Z']

Exception Location:     /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix
Raised during:  journal.views.PatientAnalysisDeleteView
Python Executable:  /usr/bin/python3
Python Version:     3.10.6
Python Path:    

['/home/verts/Documents/social-network/social_network/medicine',
 '/usr/lib/python310.zip',
 '/usr/lib/python3.10',
 '/usr/lib/python3.10/lib-dynload',
 '/home/verts/.local/lib/python3.10/site-packages',
 '/usr/local/lib/python3.10/dist-packages',
 '/usr/lib/python3/dist-packages']

Server time:    Sat, 26 Nov 2022 21:24:52  0300`

Tried to make a funtion to get succes url but unsuccesfully.

EDIT: Additionally to Willem Van Onsem solution you can simply reverse via html code:

<form action="../patient_analysis/{{patientanalysis.patient.hist_num}}" method="POST">

CodePudding user response:

You can override the .get_success_url() method [Django-doc] to return the path to which we redirect:

from django.urls import reverse


class PatientAnalysisDeleteView(DeleteView):
    model = PatientAnalysis

    def get_success_url(self):
        return reverse(
            'journal:patient_analysis',
            kwargs={'hist_num_slug': self.object.patient_id},
        )
  • Related