【问题标题】:Cannot resolve keyword 'username' into field. Choices are: address, age, city, country, gender, name, phone, pt_id, user, user_id无法将关键字“用户名”解析为字段。选项有:地址、年龄、城市、国家、性别、姓名、电话、pt_id、用户、user_id
【发布时间】:2021-09-15 11:58:45
【问题描述】:

请帮助我,我遇到了这个错误。我是 django 新手,我不知道如何解决这个错误strong text
patients/views.py

@method_decorator([login_required, patient_required], name='dispatch')
    class EditPatient(UpdateView):
        model = Patient_Profile
        fields = ['pt_id', 'name', 'gender', 'age', 'phone', 'address', 'city', 'country']
        template_name = 'patient/patient_edit.html'
        slug_field = 'username'
        slug_url_kwarg = 'slug'
        success_url = reverse_lazy('patients:patient_page')
    
        def get_context_data(self, *args, **kwargs):
            context = super(EditPatient, self).get_context_data(*args, **kwargs)
            return context

患者/模型.py

class Patient_Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    pt_id = models.CharField(max_length=50)
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=15)
    age = models.CharField(max_length=10)
    phone = models.CharField(max_length=20)
    address = models.TextField()
    city = models.CharField(max_length=100)
    country = models.CharField(max_length=100)

    def __str__(self):
        return self.user.username

患者/urls.py

app_name = 'patients'
urlpatterns = [
    path('', views.patient_page, name='patient_home'),
    path('profile/<slug>', views.EditPatient.as_view(), name='profile'),
]

模板

<h1>I am {{user.username}} </h1>
<a href="{% url 'patients:profile' slug=user.slug %}">Edit Patient</a>
{%endblock%}

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-templates


    【解决方案1】:

    由于您或使用Profile,您应该过滤user__username,因为我们正在过滤userusername 字段Profile,所以:

    @method_decorator([login_required, patient_required], name='dispatch')
    class EditPatient(UpdateView):
        # …
        slug_field = 'user__username'
        # …

    注意:在使用基于类的视图时,mixins 通常比装饰器更受欢迎。对于@login_required 装饰器 LoginRequiredMixin [Django-doc] 可以使用。

    【讨论】:

      【解决方案2】:

      Patient_Profile 表中没有 username 字段。

      改用user__username

      @method_decorator([login_required, patient_required], name='dispatch')
      class EditPatient(UpdateView):
          # …
          slug_field = 'user__username'
          # …
      

      【讨论】:

        猜你喜欢
        • 2017-06-19
        • 2023-03-03
        • 2020-10-06
        • 2020-04-14
        • 2020-11-14
        • 2021-11-04
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多