本文介绍了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'))
如果收件人不是无:
user = User.objects.get(username = recipient.candidate.user.username)
self.initial = {'收件人':用户}
返回超级(InboxCompany,self).get(* args,** kwargs)
forms.py
class ComposeMessage(ModelForm):
recipient = forms.CharField(
required = True,
widget = forms.TextInput(attrs = {'class':'form-control'})
)
body = forms.CharF ield(
required = True,
widget = forms.TextInput(attrs = {'class':'form-control'})
)
class Meta:
model =消息
解决方案
这是我的答案:
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)
上下文['sent_list'] = Message.objects.outbox_for(self.request.user)
返回上下文
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)
如果form.is_valid ():
#get从表单
data = form.cleaned_data
body = data ['body']
#auto填写字段的数据
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()
返回HttpResponse('Success')
form.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)
如果recipient_filter不是None:
self.fields ['recipient'] ._ recipient_filter = recipient_filter
def save(self,sender,parent_msg = None):
recipient = self.cleaned_data ['recipient']
body = self.cleaned_data ['body']
message_list = []
for r in recipient:
msg =消息(
sender = sender,
recipient = r,
subject = subject,
body = body,
)
if parent_msg不是无:
msg.parent_msg = parent_msg
parent_msg.replied_at = datetime.datetime.now()
parent_msg.save()
msg.save()
message_list.append(msg)
如果通知:
如果parent_msg不是None:
notification.send([sender],messages_replied,{'message':msg,})
notification.send([r],message_reply_received,{'message':msg,})
else:
notification.send([sender],messages_sent,{'message' :msg,})
notification.send([r],messages_received,{'message':msg,})
返回message_list
models.py
class Message
pre>
从用户到用户的私人消息
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)
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
解决方案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)
这篇关于Django无法分配“u'username”“:”Message.recipient“必须是“用户”例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!