Elegant way to store anonymous users with nick names in django?
Asked Answered
T

4

5

I have a simple Post model in my django app:

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'd like to implement the feature of having anonymous users create posts with nick names. Unfortunately django doesn't allow you to save an instance of AnonymousUser as a foreignkey to the Post class.

I was thinking of adding a "dummy" user record into the db that represents the anonymous user(id=0, or some negative number if possible) that would be used for all posts without a user. And if it is present a nullable name field would be used to represent the nickname of the anonymous user.

This solution seems a bit hacky to me. Is there any cleaner more effecient solution?

Toul answered 3/1, 2011 at 13:5 Comment(0)
H
7

If you can identify new users by some session information, you could just create normal user accounts, pro forma so to speak - with a flag to identify them as volatile (this may lead to some regular maintenance cleanup).

If, during session lifetime, the user actually want to register, you can reuse the user account on your side and the user can keep all his data on his.

As @slacy commented and @Dominique answered; instead of rolling your own take a look at existing projects, e.g. this:

Hypostasis answered 3/1, 2011 at 13:9 Comment(1)
This is the same approach that django-lazysignup uses, and I'd suggest using that instead of rolling your own. Watch out, because you're going to have casual users, crawlers, and all kinds of other random things creating user accounts that (may) never go away. django-lazysingup handles that pretty well.Minny
B
1

Not tested , but this can help: https://github.com/danfairs/django-lazysignup

Billposter answered 3/1, 2011 at 13:56 Comment(0)
M
0

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

Moravia answered 3/1, 2011 at 13:8 Comment(1)
May I still do joins once User is nullable?Toul
C
0

I am new to Django. A friend told me not to use ForeignKey further stating that using CharField is ok. ForeignKey is slower than CharField, as it has some check for user info.

Cobbie answered 26/12, 2014 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.