B
B
bwylla2019-03-30 14:53:28
Django
bwylla, 2019-03-30 14:53:28

How to display sent messages?

Like this is a chat for authorized users, messages are sent (checked through the shell), but the messages are not displayed on the dialog page.

#Модель чата
class Message(models.Model):
    user_from = models.ForeignKey(User,  on_delete=models.CASCADE, related_name='user_from')
    user_to = models.ForeignKey(User,  on_delete=models.CASCADE, related_name='user_to')
    message = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering=['pub_date']

    def __str__(self):
        return self.message

#views
def chat(request, pk):
    profile = get_object_or_404(Profile, pk=pk)
    user_from = request.user
    user_to = profile.user
    new_message = None

    if request.method == 'POST':
        message_form = MessageForm(request.POST)
        if message_form.is_valid():
            new_message = message_form.save(commit=False)
            new_message.user_from = user_from
            new_message.user_to = user_to
            new_message.save()
            return redirect('/')
    else:
        message_form = MessageForm()

    return render(request, 'chat/message.html', {'user_from': user_from,
                                                'user_to': user_to,
                                                'message_form': message_form,
                                                'new_message': new_message})

{{ user_from }}
{{ user_to }}


{% for mess in new_message %}
  {{ mess }}
{% endfor %}

<form method="post">
  {% csrf_token %}
  {{ message_form }}
  <input type="submit" name="" value="Отправить">
</form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question