Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving ModelForm error(User_Message could not be created because the data didn't validate)

I came across a thread that seemed like it might be related at djangocode but it didn't really help. I'm trying to save a modelform and it's throwing an exception. I think that it might be related to referring to the same foreign key twice in my model. It might also have to do with the definition of unique=True in one of the foreign key fields. I don't know

class User_Message(models.Model):
   recipient=models.ForeignKey(User, unique=True, related_name="recipients")
   subject=models.CharField(max_length=100)
   sender=models.ForeignKey(User, related_name="senders")
   message=models.TextField(max_length=500)
sent=models.DateField(auto_now_add=True)

def __unicode__(self):
    return self.subject



if request.method=="POST" and request.POST['id_message']:
    messageform=User_MessageForm(request.POST)
    recipient=[]   #receiver of mail must be a list
    recipient.append(post.user)
    if messageform.is_valid:
        message=messageform.save(commit=False)
        message.sender=user
        message.recipient=post.user
        return HttpResponse('%s %s' %(user,post.user))
        message.save()

        #send the email
        subject=messageform.cleaned_data['id_subject']
        body=messageform.cleaned_data['id_message']

        try:
            send_mail(subject, body, sender, recipient)
        except BadHeaderError:
            return HttpResponse('Invalid header found.')

It's failing at the line, messageform.save(commit=False). Man I thought that statement was fail proof.

The POST data that is received by the modelform contains the subject and message fields. This data is successfully validated by my modelform.

Is it the related names, the unique=True... what gives?

Thanks

like image 992
Ben Avatar asked Mar 18 '11 22:03

Ben


1 Answers

Here's your problem:

if messageform.is_valid:

That line needs to be

if messageform.is_valid():

Basically, the error comes from calling save() on an invalid form.

like image 96
Yuji 'Tomita' Tomita Avatar answered Sep 20 '22 07:09

Yuji 'Tomita' Tomita