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?

TheOne
  • 10,819
  • 20
  • 81
  • 119

4 Answers4

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:

miku
  • 181,842
  • 47
  • 306
  • 310
  • 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. – slacy Jun 08 '11 at 22:07
1

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

Dominique Guardiola
  • 3,431
  • 2
  • 22
  • 22
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.

Toluwalemi
  • 391
  • 5
  • 16
Huangzy
  • 149
  • 1
  • 6
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.

gruszczy
  • 40,948
  • 31
  • 128
  • 181