Make models belong to users in django

authentication, django, python

Solution

If you would like to have multiple objects belong to the user, a foreign key field to the User object will work. Note, you can still use a foreign key, and have one instance by passing the `unique` attribute to the field definition.

If one object (and only one) and belong to a user, use a one to one field. A one to one field can be accessed from either side of the models

You can use `user.classroom` or `classroom.user`, these bindings can be changed with the `related_name` attribute of one to one field definitions.

Problem

I am using django.contrib.auth and I am wondering how I can make an instance of a model "belong to" a particular user. Do I need to define a foreign key in the model that points to the user? I want users to keep their CRUD to themselves. ``` # The objects created from this model should belong # to the user who created them and should not be # viewable by other users of the website. from django.contrib.auth.models import User class Classroom(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=30) def __unicode__ (self): return self.name ``` Thanks.

Original source