【问题标题】:Can't find django model instance in new view在新视图中找不到 django 模型实例
【发布时间】:2021-08-16 06:03:10
【问题描述】:

我有一个 CreateView,用户可以在其中输入详细信息,提交后应该将用户带到刚刚提交的条目的 DetailView。我想使用 UUID 来识别整体 - 但在提交表单后,我收到以下错误:

http://localhost:8000/patient/2792470c-216a-44cc-a4ef-98c12d946844/
NO patient found matching the query

这是基本的项目结构:

models.py:

class Patient(TimeStampedModel):
    # get a unique id for each patient 
    patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False)

    name = models.CharField("Patient Name", max_length=255)

views.py

class PatientCreateView(LoginRequiredMixin, CreateView):
    model = Patient
    fields = ['name']

    def form_valid(self, form):
        form.instance.creator = self.request.user
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse('patient:detail',
                       kwargs={"slug": self.object.patient_id})


class PatientDetailView(DetailView):
    model = Patient

urls.py

urlpatterns = [
    path(
        route='add/',
        view=views.PatientCreateView.as_view(),
        name='add'),
    
    path(
        route='<slug:slug>/',
        view=views.PatientDetailView.as_view(),
        name='detail'),
]

请有人尝试指出我哪里出错了?

【问题讨论】:

  • 你能发布完整的DetailView吗?
  • 您是否检查过患者条目是否已正确添加到数据库中?
  • @ÇağatayBarın 这是完整的细节视图(当我使用 Autoslug(从名称字段而不是 uuid 字段填充)时它起作用了)
  • @AragornCrozier 是的,正在将患者添加到数据库中,谢谢

标签: python django url django-models django-views


【解决方案1】:

您需要将 slug_field 添加到 DetailView:

class PatientDetailView(DetailView):
    model = Patient
    slug_field = "patient_id"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多