Search code examples
djangodjango-generic-views

HTTP forward from generic CreateView in Django?


I have a CreateView for a patient object (simplified):

from django.views.generic.edit import CreateView
import models

class PatientCreate(CreateView):
    model = models.Patient
    fields = ['name', 'country', ..]
    # template_name is "patient_form.html" from CreateView

(I have overridden form_valid and get_context_data to set a few things by default, see for example here, but I think that's irrelevant.)

If a patient by the same name already exists, I'd like to simply HTTP forward to the detail page for that patient instead of creating a new one.

How do I do that?

I'm using Django 1.11.


Solution

  • You can add this logic in form_valid override. For example:

    def form_valid(self, form):
        name = form.cleaned_data.get('name')
        your_model_objects = YourModel.objects.filter(name=name)
        if your_model_objects.exists():  # lazy query, won't hit the database
            obj = your_model_objects.first()  # as entry exists, fetch the first object
            return redirect(reverse('detail-url', args=[obj.pk])
        else:
            return super(YourClass, self).form_valid(form)