向其他用户发送消息时如何自动填写“发件人”? CBV

时间:2019-03-02 09:20:36

标签: django django-forms django-views

我知道我可以使用第三方消息库,但是我想学习如何制作自己的库。我一直在努力在我的CreateMessageForm中自动设置发件人。

我的错误代码:__init__() got an unexpected keyword argument 'sender'

表格

class CreateMessageForm(forms.ModelForm):
    reciever = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control form-control-sm','placeholder':'Send to'}))
    title = forms.CharField(max_length=20, widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Enter message subject', 'rows':'1'}))
    msg_content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Writing your message', 'rows':'10'}))

    class Meta:
        model = Message
        fields = (
            'sender', 'reciever', 'title', 'msg_content',
        )

    def __init__(self, *args, **kwargs):
        sender = kwargs.pop('sender') # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole
        super(CreateMessageForm, self).__init__(*args, **kwargs)

查看

class MessageCreateView(CreateView):
    model = Message

    fields = ['sender', 'reciever', 'title', 'msg_content']

    def get_form_kwargs(self):
        """This method is what injects forms with their keyword
            arguments."""
        # grab the current set of form #kwargs
        kwargs = super(MessageCreateView, self).get_form_kwargs()
        # Update the kwargs with the sender_id
        kwargs['sender'] = self.request.user.id
        return kwargs

模型

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE)
    reciever = models.ForeignKey(User, related_name="reciever", on_delete=models.CASCADE)
    title = models.CharField(max_length=20)
    ...

我看过其他线程,但是无法修复。

我尝试遵循此__init__() got an unexpected keyword argument 'user'

如何解决此问题,以便表单自动填写“发件人”消息?

1 个答案:

答案 0 :(得分:0)

由于@DanielRoseman(提供了他的指导和链接),我弄清楚了如何进行这项工作。这是万一您遇到相同问题的代码。

class MessageCreateView(CreateView):
    model = Message

    fields = ['reciever', 'title', 'msg_content']

    def form_valid(self, form):
        form.instance.sender = self.request.user
        return super().form_valid(form)

class CreateMessageForm(forms.ModelForm):
    reciever = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control form-control-sm','placeholder':'Send to'}))
    title = forms.CharField(max_length=50, widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Enter message subject', 'rows':'1'}))
    msg_content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Writing your message', 'rows':'10'}))

    class Meta:
        model = Message
        fields = (
            'reciever', 'title', 'msg_content',
        )