1

why I'm getting this error?

I don't know how to get rid of this error. How can i clean the form field to enable the username to be validated?

Thanks in advance.

class InboxCompany(generic.UpdateView):

    model = CandidateToJob
    template_name = 'dashboard/inbox-company.html'
    form_class = ComposeMessage

    def get(self, *args, **kwargs):
        recipient = self.get_object(queryset=CandidateToJob.objects.select_related('candidate'))
        if recipient is not None:
            user = User.objects.get(username=recipient.candidate.user.username)
            self.initial = {'recipient': user}
        return super(InboxCompany, self).get(*args, **kwargs)

forms.py

 class ComposeMessage(ModelForm):
    recipient = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    body = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )

    class Meta:
        model = Message
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
Ronaldo Bahia
  • 576
  • 3
  • 24
  • 2
    The message is clear about the problem. You are trying to assign a `User` to a `Charfield` which doesn't make sense. Remember that your `receipient` field is a foreign key (I assume) so it is represented in your `Message` table by an integer value. So the form field representing that foreign key relationship should return an integer too. Do you want the user to be able to type the user name into the form field and have it look up that user and save them as the `recipient`? – Timmy O'Mahony Nov 08 '14 at 13:17
  • Thanks for the fast response Timmy. I don't want the user to type the username in the recipient field. even if I change username for id, it's returning the same error. – Ronaldo Bahia Nov 08 '14 at 13:21
  • What are you trying to do with the form? Are you trying to pre-populate the `receipient` field with a user then validate that user and save it to the `receipient` field when the form is posted? – Timmy O'Mahony Nov 08 '14 at 13:27
  • That's correct. here is the model: class Message(models.Model): body = models.TextField(_("Body")) sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages') recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=False, blank=True) – Ronaldo Bahia Nov 08 '14 at 13:29
  • You will need to add that to you post. The quick fix is to change this `self.initial = {'recipient': user}` to `self.initial = {'recipient': user.pk}`. If you want to show their username though it is more complicated. Alternatively you could show a dropdown with all of the users in the system and allow them select one – Timmy O'Mahony Nov 08 '14 at 13:41
  • Still getting error: Cannot assign "u'9'": "Message.recipient" must be a "User" instance. – Ronaldo Bahia Nov 08 '14 at 14:12

1 Answers1

0

I got it working finally.

Here is my answer:

The views.py

class InboxCompany(generic.UpdateView):

model = CandidateToJob
template_name = 'dashboard/inbox-company.html'
form_class = ComposeMessage

def get_success_url(self):
    return reverse('inboxcompany', kwargs={'pk': self.object.pk})

def get_context_data(self, **kwargs):
    context = super(InboxCompany, self).get_context_data(**kwargs)
    context['message_list'] = Message.objects.inbox_for(self.request.user)
    context['sent_list'] = Message.objects.outbox_for(self.request.user)
    return context

def get_initial(self, *args, **kwargs):
    recipient = self.get_object(queryset=CandidateToJob.objects.select_related('candidate.user.id'))
    self.initial = {'recipient': recipient}
    return self.initial

def get_form_kwargs(self, *args, **kwargs):
    kwargs = {'initial': self.get_initial()}
    return kwargs

def post(self, request, *args, **kwargs):

    form = self.form_class(request.POST)

    if form.is_valid():

        #get data from the form
        data = form.cleaned_data
        body = data['body']

        #auto fill fields
        sender = request.user
        sent_at = timezone.now()
        recipient = self.get_object(queryset=CandidateToJob.objects.select_related('candidate.user.id'))
        user = User.objects.all().get(id=recipient.candidate.user.id)

        a = Message.objects.create(sender=sender, recipient=user, sent_at=sent_at, body=body)
        a.save()


    return HttpResponse('Success')

The forms.py

class ComposeMessage(forms.Form):
recipient = forms.CharField(
    required=True,
    widget=forms.HiddenInput(attrs={'class': 'form-control'})
)
body = forms.CharField(
    required=True,
    label="Mensagem",
    widget=forms.TextInput(attrs={'class': 'form-control'})
)

def __init__(self, *args, **kwargs):
    recipient_filter = kwargs.pop('recipient_filter', None)
    super(ComposeMessage, self).__init__(*args, **kwargs)
    if recipient_filter is not None:
        self.fields['recipient']._recipient_filter = recipient_filter


def save(self, sender, parent_msg=None):
    recipients = self.cleaned_data['recipient']
    body = self.cleaned_data['body']
    message_list = []
    for r in recipients:
        msg = Message(
            sender = sender,
            recipient = r,
            subject = subject,
            body = body,
        )
        if parent_msg is not None:
            msg.parent_msg = parent_msg
            parent_msg.replied_at = datetime.datetime.now()
            parent_msg.save()
        msg.save()
        message_list.append(msg)
        if notification:
            if parent_msg is not None:
                notification.send([sender], "messages_replied", {'message': msg,})
                notification.send([r], "messages_reply_received", {'message': msg,})
            else:
                notification.send([sender], "messages_sent", {'message': msg,})
                notification.send([r], "messages_received", {'message': msg,})
    return message_list

The models.py

class Message(models.Model):
"""
A private message from user to user
"""
body = models.TextField(_("Mensagem"))
sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages')
recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=False, blank=True)
parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True)
sent_at = models.DateTimeField(null=True, blank=True)
Ronaldo Bahia
  • 576
  • 3
  • 24