简体   繁体   中英

refresh a page in django using ajax without reloading it?

I am building a messaging app and i want to reload my page every 1 minute so that the user can see new messages if there is some i know how to do it in html but i wanna use ajax(i am not so good in it) to reload the page. here is my views.py:

class MessagesView(LoginRequiredMixin,View):
    def get(self, request, chat_id):
        try:
            chat = Chat.objects.get(id=chat_id)
            if request.user in chat.members.all():
                chat.message_set.filter(is_readed=False).exclude(author=request.user).update(is_readed=True)
            else:
                chat = None
        except Chat.DoesNotExist:
            chat = None

        return render(
            request,
            'users/messages.html',
            {
                'user_profile': request.user,
                'chat': chat,
                'form': MessageForm()
            }
        )

    def post(self, request, chat_id):
        form = MessageForm(data=request.POST)
        if form.is_valid():
            message = form.save(commit=False)
            message.chat_id = chat_id
            message.author = request.user
            message.save()
        return redirect(reverse('messages', kwargs={'chat_id': chat_id}))

and my template is:

{% extends 'profile/base.html' %}
{% load tz %}
{% block title %}
Messages
{% endblock %}
{% block head %}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
          #form {
            position: fixed;
            bottom: 0;
            background-color:#f1f1f1;
          }

.container {
  border: 1px solid #dedede;
  background-color: #f1f1f1;
  border-radius: 5px;
  padding: 1px;
  margin: 1px 0;
}


.container::after {
  content: "";
  clear: both;
  display: table;
}

.darker {
  border-color: #ccc;
  background-color:#ddd;
}

.container img {
  float: left;
  max-width: 40px;
  height:40px;
  width: 100%;
  margin-right: 20px;
  border-radius: 50%;
}

.time-left {
  margin-left:61px;
  color: #999;
}

h4 {
    display:inline;
}
    </style>
{% endblock %}
{% block content %}
{% if not chat %}
    <div class="container">
         Impossible de commencer un chat avec cet utilisateur ou bien vous n'avez pas acces a ce chat.
    </div>
{% else %}
    {% if chat %}
        <div class="panel">
                {% for message_item in chat.message_set.all %}
                {% url 'profile' message_item.author.pk as the_user_url%}
    {% if message_item.is_readed %}
    <div class="container">
    {% else %}
    <div class="container darker">
    {% endif %}
    <a href="{{ the_user_url }}">

  <img src="{{ message_item.author.profile.avatar.url }}" alt="Avatar" style="width:100%;">
  <h4><a href="{{ the_user_url }}">{{ message_item.author.profile.prenom|title }}</a></h4>
  <p>{{ message_item.message }}</p>
  <span class="time-left">{{ message_item.pub_date|utc }}</span>
  </a>
</div>

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

    <div class='w3-container'>
    <div id='form'>
        <form method="post" action='{% url 'messages' chat.id %}'>
            {% csrf_token %}
            {{ form.as_p }}

            <input type="submit" value='envoyez' />
            </form>
        </div>
        </div>
{% endif %}
{% endblock %}

i know websocket is the best solution but for now i don't need it i just need ajax to reload my page.i will appreciate any help

Inside your template block put

<script>
  setTimeout('location.reload()', 60000)
</script>

No need to use ajax at all. Reloading a page makes a get request on the page url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM