Question

I have a model that represents a user comment on a blog. I would like to leave the possibility for the user to post his comment as a logged-in user or as an unregistered user. Depending on the case, the author of the comment would be displayed either as the user name with a link to its profile, or as a simple string (showing a nickname choosen by the unregistered user).

How shall I implement this in my model?

I could define two fields for the author of the comment: a UserField and a CharField. Then I can use custom validators to ensure that one, and only one, of these fields is filled. But is there any other better way to obtain the behaviour described above?

Thanks.

Was it helpful?

Solution

There are other ways, but having two distinct fields on the same model is the most performant one.

OTHER TIPS

Having a separate UserField and CharField is probably your best bet. However I think there's a better way to implement it than using custom validators as you said. It would be easier to create a custom property like this:

models.py

class Comment(models.Model):
    user = models.ForeignKey(User, null=True)
    nickname = models.CharField(blank=True)

    @property
    def username(self):
        if self.user:
            return self.user.username
        else:
            return nickname

If they are logged in, then you just assign the user to the comment. If not, you assign the nickname to the comment.

This ensures that you only have to call something like {{ comment.username }} in your comment template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top