【问题标题】:Cannot resolve keyword 'username' into field. Choices are: bio, blog, describtion, id, image, speciality, status, user, user_id无法将关键字“用户名”解析为字段。选项有:bio、blog、description、id、image、speciality、status、user、user_id
【发布时间】:2020-10-06 06:00:57
【问题描述】:

嘿,我想为我的用户创建一个个人资料页面,当人们登录网站时,他们可以查看每个用户的个人资料,每当我尝试登录用户的每个个人资料时,我都会收到上述错误明白了,下面是我的代码

views.py

​​>
class DoctorDetailView(LoginRequiredMixin, DetailView):
    model = Doctor
    fields = ['user', 'email', 'image', 'speciality', 'bio']
    template_name = 'pages/doctor_detail.html'

    def get_queryset(self):
        user = get_object_or_404(Doctor, username=self.kwargs.get('username'))
        return Doctor.objects.filter(doctor=user.doctor)

urls.py

​​>
    path('doctor/', doctor, name='doctor'),
    path('doctor/info/<str:username>', user_views.DoctorDetailView.as_view(), name='doctor-detail'),

医生.html

<a href="{% url 'doctor-detail' doc.user.username %}"><div class="img-wrap d-flex align-items-stretch">
                                <div class="img align-self-stretch" style="background-image: url({{ doc.user.doctor.image.url }}"></div>

models.py

​​>
class CustomUser(AbstractUser):
    is_doctor = models.BooleanField(default=False)

    def __str__(self):
        return self.email


class Status(models.Model):
    title= models.CharField(max_length=5)


    def __str__(self):
        return self.title


class Doctor(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="doctor")
    image = models.ImageField(default='jazeera.jpg', upload_to='profile_pics')
    bio = models.TextField()
    speciality = models.CharField(max_length=300)
    describtion = models.CharField(max_length=100)
    status = models.ManyToManyField(Status)

【问题讨论】:

  • 不应该 user = get_object_or_404(Doctor, username=self.kwargs.get('username'))user = get_object_or_404(User, username=self.kwargs.get('username'))(所以对于 User 模型)?

标签: django django-views django-templates


【解决方案1】:

Doctor 对象没有用户名,因此:

user = get_object_or_404(<s>Doctor</s>, username=self.kwargs.get('username'))

没有多大意义,但是你不需要先使用get_object_or_404 来获取用户,你可以过滤:

from django.shortcuts import get_object_or_404

class DoctorDetailView(LoginRequiredMixin, DetailView):
    model = Doctor
    fields = ['user', 'email', 'image', 'speciality', 'bio']
    template_name = 'pages/doctor_detail.html'

    def get_object(self):
        return get_object_or_404(Doctor, user__username=self.kwargs['username'])

【讨论】:

  • 在这个解决方案之后,我是否需要对我的 url.py 进行任何更改,因为我收到此错误,必须使用 URLconf 中的对象 pk 或 slug 调用通用详细视图 DoctorDetailView
  • @Chosenbrain:啊,是的,既然是SingleObjectMixin,那你最好覆盖get_object
  • 我怎么去找那位先生??
  • 老实说,我不清楚,请说清楚,因为您实际上提供了 2 个答案,第一个评论和第二个编辑我不知道我是否要写这两个
  • @Chosenbrain:您删除了get_queryset,并按照答案实施get_object
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2013-04-09
  • 2019-08-16
  • 2017-06-19
  • 2019-10-16
  • 2012-09-13
相关资源
最近更新 更多