Search code examples
djangodjango-sessionsdjango-users

Hints for the logic of django app


I'm learning Django and for this reason I'm developing an application described below.

This application allows users (authenticated and anonymous) to send message to other users.

Authenticated users can send message and can track all messages simply as all application that uses this feature. (like Facebook messages, for example)

The problem are anonymous users. I would an anonymous user can send message to other users but he can track his messages only for his session. Users can also reply to a message of an anonymous user but If an anonymous user lost his session lost also his messages.

The problem is, how can I manage anonymous user and their messages for the session only?


Solution

  • Django supports anonymous sessions.

    If your app is relatively simple (it sounds like it is), I would do the following:

    1. Create a standard Django user profile model and link that to the users messages but do not use OneToOne to connect to User.
    2. Use database backed sessions (https://docs.djangoproject.com/en/dev/topics/http/sessions/#using-database-backed-sessions)
    3. Create a temporary user profile model for anonymous users and store their temporary profile id in their session.
    4. Once a day delete all profile objects that do not have a user AND whose id is not in the sessions table. A simple way (and what I would do) is have a created date/time field on the profile and just delete any profile that was created two weeks or more ago and has a null user field. I'd just crontab a django management command.

    The cool thing is that if somebody registers after using the app anonymously for a while you can use their temporary profile as their profile and they keep their messages.