Search code examples
databasedjangoemailmodels

Django Model ValueError


I'm accessing emails in my email server, taking the body of each email and then applying regular expressions to find the data necessary to populate my Django model.

This all works fine except for one field, which is linked as a foreign key to another model field. Despite the value in my email being the same as the one in listed in my other model, it fails....

The error:

ValueError: Cannot assign "'Humanities'": "Subject.faculty" must be a "Faculty" instance.

For example, say each school subject has to be part of a faculty. When populating the database via a form, for the Subject's faculty field I drop down the menu to a list of faculty values/instances as there is a foreign key relationship defined in my model i.e. for the faculty field I can choose from Humanities, Art, Design Technology etc.

But when I find the value 'Humanities' in my email and try to add it to the database model, I get the error above.

Anyone shed any light on this? Am I being stupid or is it more than a ValueError as to me, the values are the same in both cases

Thank you

More code as requested:

class Faculty(models.Model):
  name = models.CharField(primary_key=True, max_length=50)
  leader = models.CharField(max_length=50)
  email = models.EmailField()
  mailing_list = models.ManyToManyField("Contact", null=True)

class Subject(models.Model):
  name = models.CharField(max_length=50)   
  faculty = models.ForeignKey(Faculty, to_field="name")
  faculty_head = models.CharField(max_length=50)

Solution

  • It sounds like you are trying to assign a string "Humantities" to a ForeignKey relationship. This doesn't make sense. You need to either find or create the actual Faculty object with the name "Humanities" and assign it to the Subject. Something like this in your view (depending on how your form is set up):

    if form.is_valid():
      faculty_str = form.cleaned_data['faculty']
      (faculty, was_created) = Faculty.objects.get_or_create(name=faculty_str, ...)
      # It's hard to tell if you are using a ModelForm or just a normal Form. Anyway, assume we already have access to the Subject object
      subject.faculty = faculty
      subject.save()
    

    get_or_create()