title: How check UniqueConstraint in Django with CreateView and custom forms if field set in view?
body: <h2>I do:</h2>
  <p>I define UniqueConstraint (also try with 'unique_together') in model:</p>
  <pre><code>class Project(models.Model):
      class Meta:
          constraints = [
              models.UniqueConstraint(
                  fields=['company', 'name'], name=&quot;unique_project_name_in_company&quot;
              )
          ]
  
      name = models.CharField(blank=False, max_length=256)
  
      company = models.ForeignKey(
          Company,
          on_delete=models.CASCADE
      )
  </code></pre>
  <p>I set company in form_valid in view (I think it's reason of my problem):</p>
  <pre><code>class ProjectCreateView(LoginRequiredMixin, generic.CreateView):
      model = Project
      form_class = ProjectForm
      
      def form_valid(self, form):
          form.instance.company = self.request.user.company
          return super().form_valid(form)
  </code></pre>
  <p>I try define message for 'unique_project_name_in_company' in form:</p>
  <pre><code>class ProjectForm(forms.ModelForm):
      model = Project
  
      class Meta:
          model = Project
          fields = ['name']
  
          error_messages = {
              NON_FIELD_ERRORS: {
                  'unique_project_name_in_company': &quot;Name isn't unique!&quot;,
              }
          }
  </code></pre>
  <hr />
  <h2>Unexpected behavior</h2>
  <p>If I submit form with non-unique pair (inputed non-unique name) I want get my custom error_message but I get:
  <a href="https://i.stack.imgur.com/uKk79.png" rel="nofollow noreferrer">500 IntegrityError UNIQUE constraint failed: company_id, name</a></p>