Please forgive the mistake as it is written by a beginner with a memo. I'm making a chat app, but I want to make sure that only the participants in the room can see the chat room. I spent a lot of time trying to implement it by overriding the methods in the class view, There was an insanely easy way, so I will introduce it.
models.py
class Room(models.Model):
(Abbreviation)
class User(AbstractBaseUser, PermissionsMixin):
(Abbreviation)
class JoinRoom(models.Model):#Intermediate table
room = models.ForeignKey(Room,on_delete=models.CASCADE)
user = models.ForeignKey(User,on_delete=models.PROTECT)
It may not be better to write it here, but I will summarize it here for the sake of clarity. It seems that get is faster than using filter, so I do this.
views.py
from django.contrib.auth.mixins import UserPassesTestMixin
class OnlyParticipantMixin(UserPassesTestMixin):
raise_exception = True
def test_func(self):
try:
exist_or_not = MyRoom.objects.get(room=self.kwargs['pk'],user=self.request.user)#I haven't tried yet if I need to substitute.
return True
except MyRoom.DoesNotExist:
return False
class CommentCreateView(OnlyParticipantMixin,generic.CreateView):#Doesn't it work unless it's in this order?
template_name = 'hogehoge/hogehoge'
That's it. If anyone other than the participant tries to peep, an error will occur.
reference
https://developer.yukimonkey.com/article/20200417/
https://intellectual-curiosity.tokyo/2018/12/06/django%E3%81%AE%E8%A9%B3%E7%B4%B0%E7%94%BB%E9%9D%A2detailview%E3%81%A7%E8%87%AA%E5%88%86%E4%BB%A5%E5%A4%96%E3%81%AE%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%9A%E3%83%BC%E3%82%B8%E3%81%AB%E3%82%A2%E3%82%AF/
Recommended Posts