title: How to handle UniqueConstraint failure in Django Meta Class?
body: <p>I have created a UniqueConstraint Meta Class for my model, and it works when I test it by intentionally creating a duplicate but I am getting an error page instead of being redirected back to the original page. Where do I insert the code to go back to the page that I was just on?</p>
  
  <p>I assume the issue is in the view, but I have no idea what code to put in there and the Django docs contain nothing alluding to this problem.</p>
  
  <p>Model:</p>
  
  <pre><code>class StudentScheduledClass(models.Model):
      student = models.ForeignKey("users.User", on_delete=models.CASCADE, db_column="Student")
      scheduled_class = models.ForeignKey("ScheduledClass", on_delete=models.CASCADE, db_column="ScheduledClass")
      grade = models.FloatField(db_column="Grade", blank=True, null=True)
  
      class Meta:
          managed = True
          db_table = "StudentScheduledClass"
          verbose_name_plural = "StudentsScheduledClasses"
          constraints = [
              models.UniqueConstraint(fields=['student', 'scheduled_class'], name='student scheduled class restraint')
          ]
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>class StudentScheduledClassCreateView(LoginRequiredMixin, CreateView):
      model = StudentScheduledClass
      context_object_name = "student_scheduled_class"
      fields = ["student"]
  
      def form_valid(self, form):
          scheduled_class = self.kwargs["scheduled_class"]
          form.instance.scheduled_class = ScheduledClass(scheduled_class)
          return super().form_valid(form)
  
      def get_success_url(self):
          scheduled_class = self.kwargs["scheduled_class"]
          return reverse("scheduled-class-detail", args={scheduled_class})
  </code></pre>
  
  <p>I'd like to just go back to the original page with an error message, instead I get this integrity error:</p>
  
  <pre><code>IntegrityError at /classes/student_scheduled_class_create/1/
  UNIQUE constraint failed: StudentScheduledClass.Student, StudentScheduledClass.ScheduledClass
  Request Method: POST
  Request URL:    http://localhost:8000/classes/student_scheduled_class_create/1/
  Django Version: 2.2.2
  Exception Type: IntegrityError
  Exception Value:    
  UNIQUE constraint failed: StudentScheduledClass.Student, StudentScheduledClass.ScheduledClass
  </code></pre>