如何将request.user / user传递给Django中的消息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将request.user / user传递给Django中的消息相关的知识,希望对你有一定的参考价值。

所以我想让一个用户向另一个用户发送消息。我希望“发送者”字段自动为“ request.user”,而接收者字段为发送者通过其个人资料页面单击的用户。我将如何将这些信息传递给表单?

matches.html

<div class="container">

    <p>Username:  profile </p>
    <h5>Your Matches:</h5>
    % for item in match %
        <br>
        <p>Username: <br> item.username</p>
        <img src="  item.photo.url  " width="300">
        <p>Bio: <br> item.description </p>
        <br>
    % endfor %

</div>

forms.py/InstantMessageForm

class InstantMessageForm(forms.ModelForm):

    class Meta:
        model = InstantMessage
        fields = ('receiver','sender','message')


        def save(self, commit=True):
            user = super(InstantMessageForm, self).save(commit=False)
            user.receiver = cleaned_data['receiver']
            user.sender = cleaned_data['sender']
            user.message = cleaned_data['message']


            if commit:
                user.save()

            return user 

views.py/instant_message

def instant_message(request):

    if request.method == 'POST':
        form = InstantMessageForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('dating_app:home')

    else:
        form = InstantMessageForm()


    context = 'form':form

    return render(request, 'dating_app/instant_message_form.html',context)

models.py

class InstantMessage(models.Model):

    receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
    message = models.TextField()

类InstantMessage(models.Model):

receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
message = models.TextField()

instant_message_form.py

% extends "dating_app/base.html" %

% load bootstrap4 %

% block content %



<h1>Start chatting  now!</h1>




    <div class='container'>
        <form method="post" action="% url 'dating_app:instant_message' %" >


            % csrf_token %
             form.as_p 
            <button type="submit">Register</button>
        </form>
    </div>

% endblock content %
答案

您可以创建没有sender字段的表单:

class InstantMessageForm(forms.ModelForm):

    class Meta:
        model = InstantMessage
        fields = ('receiver', 'message')

然后在视图中,可以将request.user注入为.sender.instance,并以以下形式包装:

from django.contrib.auth.decorators import login_required

@login_required
def instant_message(request):
    if request.method == 'POST':
        form = InstantMessageForm(request.POST)
        if form.is_valid():
            form.instance.sender = request.user
            form.save()
            return redirect('dating_app:home')
    else:
        form = InstantMessageForm()
    context = 'form':form
    return render(request, 'dating_app/instant_message_form.html',context)

Note:您可以将视图限制为使用@login_required decorator [Django-doc]

为了设置接收者,您的网址应包含接收者的主键。然后,您也可以从表单中删除@login_required,然后使用:

receiver

您当然需要相应地更改from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 @login_required def instant_message(request, receiver_id): if request.method == 'POST': form = InstantMessageForm(request.POST) if form.is_valid(): form.instance.sender = request.user form.instance.receiver = get_object_or_404(get_user_mode(), pk=receiver_id) form.save() return redirect('dating_app:home') else: form = InstantMessageForm() context = 'form':form return render(request, 'dating_app/instant_message_form.html',context)urls.py网址,以使其包括接收者的主键。

以上是关于如何将request.user / user传递给Django中的消息的主要内容,如果未能解决你的问题,请参考以下文章

使用django时如何在ajax调用中传递request.user?

如何将有关 request.user 的信息提供给 clean 方法

使用包含 RadioSelect 小部件的 ModelChoiceField 在 ModelForm 的查询集中获取 request.user

Django Rest 框架:将查询集传递给 Response()

如何使用 AbstractUser 类访问 request.user

Django 3:创建 CRUD 表模板(将上下文变量传递给 HTML)