Yudi
Yudi

Reputation: 35

django model attribute field empty list

I'm trying to build an online forum. Right now, my forum model has several attributes and one of it is "owner", which is a ForeignKey to the user that created this forum. It also has another attribute "passcode" which makes sure that whenever an owner creates a forum, he/she has to type a passcode so that only others with the right passcode can join the forum. Now, I am trying to implement a new function such that users can choose to join existing forums; however, I am stuck.

1) My first issue is that in order to create a custom permission, I first need another model attribute that contains a list of the permissioned users. I was thinking of having a model attribute as an empty list, permissioned_users = [], so that whenever a user requests to join a forum and has the right passcode, his/her username will be appended to the list and then in my views.py I can use @user_passes_test to check if the request.user.username is in the list. However, i'm not sure if "students = []" will work such that i can do "anyparticularinstance".students.append("his name") will work.

2) How do i create a join forum function? I have fully implemented a create forum function but how do I allow users to join an existing forum? Thank you!

Upvotes: 0

Views: 677

Answers (2)

AR7
AR7

Reputation: 376

One Way you can achieve the permissions is by defining a Boolean field in your model, for example:

class Forum(AbstractBaseUser):
   username=models.CharField(max_length=20,unique=True)
   name = models.CharField(max_length=20)
   email = models.EmailField(max_length=254,null=True,blank=True)
   is_active   = models.BooleanField(default=True)
   is_admin    = models.BooleanField(default=False)
   is_staff    = models.BooleanField(default=False)

By extending the AbstractBaseUser in Django you can define custom permissions for users.Either from the default Admin provided by Django or may be your own custom admin, you can add or remove permissions to a particular user. For more information you can see the following link Django AbstractBaseUser

Upvotes: 1

almost a beginner
almost a beginner

Reputation: 1632

You can achieve your objective by using textfield, and then appending at the end of the textfield everytime you update the field.

Model:

permissioned_users = models.TextField(blank=True, null=True)

View:

foo = Forum.objects.get(id=id)
temp = foo.permissioned_users
temp = temp+" username"
foo.permissioned_users = temp
foo.save()

Obviously you have to do some more work, ex. when you want to check which user is given permission, you split the string using whitespace hence str.split(), then you can easily iterate through it and make your checks.

Upvotes: 0

Related Questions