Reputation: 768
I have a site using Django that has a model named 'CampaignProfile' - and authenticated (logged in) users can create a CampaignProfile object through a form. Once created, the model object can be viewed on the authenticated users personal dashboard. However, when I log in to other user accounts then the same model objects are viewable on their personal dashboard when they shouldn't be.
How would I specify that only the objects created by any given user can only be seen by that user (with the exception of the Django Admin)?
dashboard.views.py:
def dashboard_main(request):
if request.user.is_authenticated:
all_campaigns = CampaignProfile.objects.all()
return render(request, 'dashboard-main.html', {'all_campaigns': all_campaigns})
else:
return redirect('/users/login/?next=')
I've already tried 'user.CampaignProfile.objects.all()
' when I create variable 'user=request.user.id
' so that the user requesting the objects can only see their own; but this leads to errors saying that user does not have attribute CampaignProfile. Though I've set the ForeignKey for my CampaignProfile model to be related to UserModel (the following model)...
Here's my custom user model accounts.models.py:
class UserModel(AbstractBaseUser):
user_email = models.EmailField(max_length=255, unique=True, verbose_name='Email Address')
user_fname = models.CharField(max_length=30, verbose_name='First Names')
user_lname = models.CharField(max_length=30, verbose_name='Last Name')
dt_joined = models.DateTimeField(auto_now_add=True)
dt_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'user_email'
REQUIRED_FIELDS = ['user_fname','user_lname']
Any suggestions would be amazing thanks.
Upvotes: 2
Views: 1906
Reputation: 4818
In CampaignProfile
model create a ForeignKey
mapped to UserModel
(Or a OneToOneField
if each user can create only one instance of CampaignProfile
).
class CampaignProfile(models.Model):
user = models.ForeignKey(UserModel)
# other fields
Then filter the instances related to logged in user.
all_campaigns = CampaignProfile.objects.filter(user=request.user)
Upvotes: 10