0

When saving an object which has a ForeignKey, I get the common error: 'Cannot assign "(myObject)": "(my ForeignKey field)" must be an instance'.

This question is answered clearly:

django foreign key save

Django - Foreign Key must be an instance

Django ForeignKey Instance vs Raw ID

but the solutions aren't working for me.

models.py

class User(models.Model):
  email = models.EmailField(max_length=100, unique=True)
  password = models.CharField(validators=[MinLengthValidator(8)],max_length=60)
  is_teacher = models.BooleanField(default=0)


class Question(models.Model):
  question_text = models.CharField(max_length=5000)
  pub_date = models.DateTimeField('date asked')
  answered = models.BooleanField(default=False)
  asker = models.IntegerField(default=0)
  def __str__(self):
    return self.question_text
  def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now;
  def asked_by(self):
    return self.asker

class Answer(models.Model):
  to_question = ForeignKey(Question, null=False)
  pub_date = models.DateTimeField('date answered')
  answer_text = models.CharField(max_length=10000)
  answered_by = ForeignKey(User, null=False)
  def __str__(self):
    return self.answer_text

views.py

@staff_member_required()
def answerQuestion(request):
  if request.method == 'POST':
    form = QuestionAnswerForm(request.POST,label_suffix='',error_class=DivErrorList)
    if form.is_valid():
      answer_text = request.POST['answer_text']
      question_id = request.POST['question_id']
      now = timezone.now()
      try:
        to_question = Question.objects.get(pk=question_id)
        answered_by= User.objects.get(pk=request.user.id)
        Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by=answered_by)
        return render(request, 'askWisdom/answerQuestion.html', { 'result':'Thanks for Your Answer' })
      except Question.DoesNotExist:
        return HttpResponse("Question doesn't exist.")
      except User.DoesNotExist:
        return HttpResponse("Answering User doesn't exist.")

    else:
      return render(request, 'askWisdom/answerQuestion.html', {'form': form, 'error_message': form.errors })

The actual error is: 'Cannot assign "User: sampleUser@gmail.com": "Answer.answered_by" must be a "User" instance'.

The strange thing is, my Answer model has two ForeignKeys, but when doing

Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by=answered_by)

the error is flagged on the second ForeignKey (answered_by=answered_by) but not the first one (to_question=to_question) assuming they are processed in sequence.

Ok, so change it to force saving a numeric id at the database level:

answered_by_id= User.objects.get(pk=request.user.id).id
Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by_id=answered_by_id)

and I get the error: 'column answer.id does not exist'

In this case, there's an actual column in the Postgres database named answered_by_id, so I don't see why it's looking for a hidden, apparently auto-generated 'answer.id' column instead.

But anyway, I'd rather get the default method working of passing an instance to the ForeignKey field.

Is there something obvious I'm overlooking? I'll be embarrassed if it's just a typo.

Community
  • 1
  • 1
Ron
  • 357
  • 1
  • 6
  • 18
  • Ah, yes. I installed the django-allauth app which uses the built-in User, but didn't remove my own User model. I up voted your comment, if it was an answer I'd accept it. – Ron Jun 10 '16 at 22:33

1 Answers1

0

Unless you have set up a custom user model, request.user will be a django.contrib.auth.models.User instance, which is a different model from your User model. You shouldn't create your own model with a password field like that, it's insecure.

Alasdair
  • 298,606
  • 55
  • 578
  • 516