2014-11-08 58 views
1

爲什麼我收到此錯誤?Django無法指定「u'username'」:「Message.recipient」必須是「用戶」實例

我不知道如何擺脫這個錯誤。 如何清理表單字段以啓用用戶名進行驗證?

在此先感謝。

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 
+2

的信息是明確問題。你正在試圖將'User'分配給Charfield,這是沒有意義的。記住你的'receient'字段是一個外鍵(我假設),所以它在你的'Message'表中由一個整數值表示。所以表示外鍵關係的表單字段也應該返回一個整數。你是否希望用戶能夠在表單字段中輸入用戶名並讓它查找該用戶並將它們保存爲「收件人」? – 2014-11-08 13:17:40

+0

感謝Timmy的快速反應。我不希望用戶在收件人字段中輸入用戶名。即使我更改id的用戶名,它也會返回相同的錯誤。 – 2014-11-08 13:21:03

+0

你想用表格做什麼?您是否試圖向用戶預先填寫「收件人」字段,然後驗證該用戶並在表單發佈後將其保存到'收件人'字段? – 2014-11-08 13:27:08

回答

0

我得到了它最後的工作。

這裏是我的回答:

的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') 

的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 

的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) 
相關問題