Home > other >  Submit forms in django without refreshing the page
Submit forms in django without refreshing the page

Time:10-05

Okay, first of all, I know that there are a lot of videos and tutorials out there to help with the question I have raised. However, my case is a little different than the usual. So, basically, I am trying to build out a chat app on Django. For this I am planning to save the messages that the user wants to send in the database and then render them on screen. Now, in order to send this data to the server, I wish to use Ajax as it would prevent page reload and thus make for a much smoother UX. However, that raises an issue. The issue is that how do I keep track of the fact that which room/ chat is the message coming from and which user sent it? The obvious solution that comes to mind is the create a hidden field inside if my form and then pass in the room details of it through that hidden field. But won't that be highly insecure as the data could be subject to change, allowing users to send messages from a chat they have access to, to a chat they don't have access to? The username part can still be managed using request.user. The trouble is arising only with the tracking room details part. Any help/ideas are welcome. Thanks!

CodePudding user response:

First of all take a look at Django Unicorn: https://www.django-unicorn.com/

This might be the perfect fit for this kind of application.

But won't that be highly insecure as the data could be subject to change, allowing users to send messages from a chat they have access to, to a chat they don't have access to?

As Abdul Aziz Barkat already pointet out is true for all kind of form submission. You have to check in your code if the user is allowed to post to/from a room and to a person. This can be done in the forms clean() method where you can raise errors like PermissionDenied.

Edit

response to your first comment:

You need to keep track permissions of the chat. e.g. which users are allowed to write in this chat and those that are allowed to read the chat

class Chat(models.Model):
    # your generic chat class
    # ...
    write = models.ManyToManyField(User, blank=True, related_name="users_write_access")
    read = models.ManyToManyField(User, blank=True, related_name="user_read_access")

As soon as a user becomes a member of a chat add them to the write and read field.

If a user tries to send a message to a chat check if he's a member of the write list. e.g.

from django.shortcuts import get_object_or_404
from django.contrib.auth import PermissionDenied

def send_message_to_chat(request, chat_id):
    chat = get_object_or_404(Chat, pk=chat_id)
    if request.user not in chat.write.all():
        raise PermissionDenied("You are not allowed to write in this chat...")
    # continue with your code to send messages

to something similar for read access. I hope this helps

  • Related