I'm using django and rest-framework to develop a website. I have a users app in which the models are shown below:
class User(AbstractUser):
pass
class Comment(models.Model):
comment_text = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL,default=DefaultUser,on_delete=models.SET_DEFAULT,related_name='author')
# DefaultUser is similar to AnonymousUser in django.contrib.aut.models
date = models.DateTimeField(default=now)
class User_Comment(Comment):
on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser)
class User_Comment(Comment):
on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser)
so it's basically a comment system where a user can comment on another user.
I've used a rest framework serializer for posting comments:
class User_CommentSerilizer(serializers.ModelSerializer):
comment = User_Comment
class Meta:
model = User_Comment
fields = ('comment_text','on_user')
# extra_kwargs = {'password': {'write-only': True}}
def create(self, validated_data):
comment = User_Comment(
author= User.objects.filter(username=self.context['request'].user)[0],
on_user= User.objects.filter(username=validated_data["on_user"])[0],
validated=False,
comment_text= validated_data["comment_text"]
)
comment.save()
return comment
and then using a UserCommentViewSet in views.py:
class User_CommentViewSet(viewsets.ViewSet):
serializer_class = User_CommentSerilizer
queryset = User_Comment.objects.all()
and finally in the urls file I've registered the view:
router = DefaultRouter()
router.register('profile' , views.UserViewSet)
router.register('comment' , views.User_CommentViewSet)
router.register('login' ,views.LoginViewSet, base_name='login')
urlpatterns = [
path('users/', include(router.urls)),
]
the profile and login routers are working fine. however the comment router is not showing at all (and returns 404) without raising any other error. it's like the router is not registered.
I can't figure out what the problem is, Although I did find out that it has something to do with the queryset part. I'd really much appreciate it if anyone could figure this out.
the bug was simply because I was using a ViewSet instead of ModelViewSet in User_CommentViewSet function.