RobMcC
RobMcC

Reputation: 412

Can't find django model instance in new view

I have a CreateView in which users enter details, after submitting this should take the user to a DetailView for the just submitted entry. I am wanting to use a UUID to identify the entires - but after submitting the form I get the following error:

http://localhost:8000/patient/2792470c-216a-44cc-a4ef-98c12d946844/
NO patient found matching the query

This is the basic project structure:

models.py:

class Patient(TimeStampedModel):
    # get a unique id for each patient 
    patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False)

    name = models.CharField("Patient Name", max_length=255)

views.py

class PatientCreateView(LoginRequiredMixin, CreateView):
    model = Patient
    fields = ['name']

    def form_valid(self, form):
        form.instance.creator = self.request.user
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse('patient:detail',
                       kwargs={"slug": self.object.patient_id})


class PatientDetailView(DetailView):
    model = Patient

urls.py

urlpatterns = [
    path(
        route='add/',
        view=views.PatientCreateView.as_view(),
        name='add'),
    
    path(
        route='<slug:slug>/',
        view=views.PatientDetailView.as_view(),
        name='detail'),
]

Please could someone try and point out where i am going wrong?

Upvotes: 0

Views: 144

Answers (1)

RobMcC
RobMcC

Reputation: 412

You need to add the slug_field to the DetailView:

class PatientDetailView(DetailView):
    model = Patient
    slug_field = "patient_id"

Upvotes: 1

Related Questions