Home > Mobile >  Django: on visiting page I get an alert with dictionary values in it. What is causing this?
Django: on visiting page I get an alert with dictionary values in it. What is causing this?

Time:12-16

New to Django and python, been following a tutorial and playing around with creating a user to user messaging functionality. So far all works great except that when I visit the messages page I always get an alert like: {'user': <User: test2>, 'last': datetime.datetime(2022, 12, 15, 20, 21, 19, 109214, tzinfo=datetime.timezone.utc), 'unread': 0}

alert

Any ideas on what is causing this and how can I remove it?

urls.py

from django.urls import path
from . import views as user_views

app_name = 'chat'

urlpatterns = [
    path('messages/', user_views.inbox , name='messages'),
    path('messages/<username>', user_views.Directs , name='directs'),
    path('messages/send/', user_views.SendDirect , name='send_direct'),
]

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Message
from django.http import HttpResponse, HttpResponseBadRequest
from django.template import loader
from django.contrib.auth.models import User

@login_required
def inbox(request):
    messages = Message.get_messages(user=request.user)
    active_direct = None
    directs = None

    if messages:
        message = messages[0]
        active_direct = message['user'].username
        directs = Message.objects.filter(user=request.user, recipient=message['user'])
        directs.update(is_read=True)

        for message in messages:
            if message['user'].username == active_direct:
                message['unread'] = 0

    context = {
        'directs': directs,
        'messages': messages,
        'active_direct': active_direct,
        }

    template = loader.get_template('chat.html')

    return HttpResponse(template.render(context, request))      

@login_required
def Directs(request, username):
    user = request.user
    messages = Message.get_messages(user=user)
    active_direct = username
    directs = Message.objects.filter(user=user, recipient__username=username)
    directs.update(is_read=True)

    for message in messages:
        if message['user'].username == username:
            message['unread'] = 0

    context = {
        'directs': directs,
        'messages': messages,
        'active_direct': active_direct,
    }

    template = loader.get_template('chat.html')

    return HttpResponse(template.render(context, request))  

@login_required
def SendDirect(request):
    from_user = request.user
    to_user_username = request.POST.get('to_user')
    body = request.POST.get('body')

    if request.method == 'POST':
        to_user = User.objects.get(username=to_user_username)
        Message.send_message(from_user, to_user, body)
        return redirect('chat:messages')
    else:
        HttpResponseBadRequest()

template:

<!DOCTYPE html>
{% extends "base.html" %}
{% load static %}
{% block content %}
<h1>Messages</h1>
<div >
     <!-- Chats List -->
    <div >
      <div >
        
        {% for message in messages %}
        <a  href=""></a>
            <div  style="width: 18rem;">
              <div >
                {% if message.user.userinfo.userImage.url %}
                <div ><img  src="{{ message.user.userinfo.userImage.url }}" height="75" width="75" alt="Profile Picture"></div>
                {% endif %}
                <div >
                    <h5>{{ message.user.username }}</h5>
                    <p></p>
                    <a href="{% url 'chat:directs' message.user.username %}"><button type="button" >View Messages</button></a>

                </div>
              </div>
            </div>
        {% endfor %}

      </div>
    </div>
  <!-- Chat Window -->

    <div >
        {% for direct in directs %}
      <div >
        <p ><strong>{{ direct.sender.username }}</strong><small> on: {{ direct.date|date:'N d G:i' }}</small></p>
        {{ direct.body }}
      </div>
      {% endfor %}
 <!-- Chat Window -->
        <div>
            <form role="form" method="POST" action="{% url 'chat:send_direct' %}">
                {% csrf_token %}
                <input type="hidden" name="to_user" value="{{ active_direct }}">
                <div>
                    <p >
                    <textarea  name="body" rows="2" style="width: 30rem;" placeholder="Add a comment..." ></textarea>
                    </p>
                </div>
                <div >
                    <button type="submit" name="action" >Send</button>
                </div>
            </form>
        </div>
    </div>
  </div>
{% endblock %}

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models import Max
from django.utils import timezone

class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user')
    recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user')
    body = models.TextField(max_length=500, blank=True, null=True)
    date = models.DateTimeField(default=timezone.now())
    is_read = models.BooleanField(default=False)

    def send_message(from_user, to_user, body):
        sender_message = Message(
            user=from_user,
            sender=from_user,
            recipient=to_user,
            body=body,
            is_read=True)
        sender_message.save()

        recipient_message = Message(
            user=to_user,
            sender=from_user,
            body=body,
            recipient=from_user)
        recipient_message.save()

        return sender_message

    def get_messages(user):
        messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')
        users = []

        for message in messages:
            users.append({
                'user': User.objects.get(pk=message['recipient']),
                'last': message['last'],
                'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()
            })

        return users

First I thought it was an error due to timezone rendering, tried setting USE_TZ = False, eventually imported tz_detect and timezone issue was fixed, but it seems that it is not what is causing this.

Also tried hiding the alert with js, with no success.

CodePudding user response:

try adding the following in you settings.py

LANGUAGE_CODE = "es-mx"

TIME_ZONE = "America/Mexico_City"

USE_I18N = True

USE_L10N = True

USE_TZ = True

CodePudding user response:

try changing this line in models.py

date = models.DateTimeField(default=timezone.now())

to

date = models.DateTimeField(default=timezone.now)
  • Related