Home > Software design >  AttributeError: 'Doctor' object has no attribute 'comments'
AttributeError: 'Doctor' object has no attribute 'comments'

Time:12-16

I'm working on this project but I got the following error comm = doctor_detail.comments.filter(active=True) AttributeError: 'Doctor' object has no attribute 'comments' however I think that everything is alright

this is my models.py

class Comments(models.Model):
    co_name = models.CharField(max_length=50, verbose_name="الاسم ")
    co_email = models.EmailField(
        max_length=50, verbose_name="البريد الالكتروني")
    co_body = models.TextField(max_length=400, verbose_name='التعليق')
    created_dt = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)
    post = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='comments')

    def __str__(self):
        return 'علق {} على {}'.format(self.co_name, self.post)

this is my views.py

def doctor_detail(request, slug):
    # استدعاء جميع البينات اللي في البروفايل
    doctor_detail = get_object_or_404(Doctor, slug=slug)
    comm = doctor_detail.comments.filter(active=True)
    form = Commentair()
    if request.method == 'POST':
        form = Commentair(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = doctor_detail
            new_comment.save()
            form = Commentair()
    else:
        form = Commentair()
    return render(request, 'user/doctor_detail.html', {'doctor_detail': doctor_detail,
                                                       'comm': comm,'form': form
                                                       })

I really don't know why I'm facing this error because the related name is available and I think everything is okay .please if there is an answer to this write it and explain it to me. thank you

CodePudding user response:

Based on the code you provided, it looks like the comments attribute you're trying to access is defined on the User model, not the Doctor model. You're trying to access it through a Doctor object, which is why you're getting the error.

To fix this, you'll need to access the comments attribute through a User object instead. If you want to get the User object that is associated with a Doctor object, you can use the user attribute of the Doctor object. For example, you could replace this line:

comm = doctor_detail.comments.filter(active=True)

with this line:

comm = doctor_detail.user.comments.filter(active=True)
  • Related