Elegant way to store anonymous users with usernames in django?

I have a simple Post model in my django application:

class Post(models.Model): category = models.CharField(max_length=10, choices=choices) message = models.CharField(max_length=500) user = models.ForeignKey(User, editable=False) 

I would like to implement the function of anonymous users to create messages with nicknames. Unfortunately, django does not allow storing an instance of AnonymousUser as a foreign key in the Post class.

I was thinking of adding a custom "dummy" entry in db that represents an anonymous user (id = 0 or some kind of negative number, if possible) that will be used for all messages without a user. And if it is present, a name field with a null name will be used to represent the alias of the anonymous user.

This decision seems a bit hacked to me. Is there a more effective, more efficient solution?

+4
source share
4 answers

If you can identify new users by any session information, you can simply create regular user accounts, proforma so to speak, with a flag to identify them as mutable (this can lead to some regular cleaning of the system).

If during a user session the user wants to register, you can reuse the user account on your side, and the user can store all of his data.

As @slacy commented, and @Dominique replied; instead of turning your own views on existing projects, for example. this is:

+6
source
+1
source

You can add blank=True and null=True to User ForeignKey and set it to None if the user is anonymous. You just need to save the alias somewhere.

0
source

I am recently in Django. One of my friends told me not to use ForeignKey using CharField. ForeignKey is slower than CharField, as it has some verification of user information.

0
source

Source: https://habr.com/ru/post/1334065/


All Articles