用户位于具有id(父表/模型)的患者的DetailView中,或者选择患者来创建子(表/模型)对象(我希望这是准确的术语)。 我正在尝试使用父表中的正确外键“预填充”我的表单。基本上,每位患者将有几次就诊,并且访问需要与患者表(“主”模型)具有正确的外键关系。
我在def form_valid
文件中收到与views.py
命令相关的以下错误。如果我删除此命令,则会收到not null
错误,因为该字段需要填写。我也尝试了get_instance
功能,但论坛建议不要使用def form_valid
。
错误
Cannot assign "<SimpleLazyObject:
<django.contrib.auth.models.AnonymousUser object at 0x10d62d278>>":
"Visit.fk_visit_user" must be a "User" instance.
Request Method: POST
Request URL: http://127.0.0.1:8000/clincher/visit/add/2
Django Version: 2.0.4
Exception Type: ValueError
Exception Value:
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x10d62d278>>": "Visit.fk_visit_user" must be a "User" instance.
Exception Location: /Users/nrsmoll/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __set__, line 197
Python Executable: /Users/nrsmoll/venv/bin/python
Python Version: 3.6.4
Python Path:
['/Users/nrsmoll/PycharmProjects/clincher',
'/Users/nrsmoll/PycharmProjects/clincher',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
'/Users/nrsmoll/venv/lib/python3.6/site-packages',
'/Users/nrsmoll/venv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg',
'/Users/nrsmoll/venv/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg',
'/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']
Server time: Wed, 6 Jun 2018 13:16:29 +0000
回溯
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/clincher/visit/add/2
Django Version: 2.0.4
Python Version: 3.6.4
Installed Applications:
['clincher.apps.clincherConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/views/generic/edit.py" in post
172. return super().post(request, *args, **kwargs)
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/views/generic/edit.py" in post
142. return self.form_valid(form)
File "/Users/nrsmoll/PycharmProjects/clincher/clincher/views.py" in form_valid
63. form.instance.fk_visit_user = self.request.user
File "/Users/nrsmoll/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in __set__
197. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /clincher/visit/add/2
Exception Value: Cannot assign "<SimpleLazyObject:
<django.contrib.auth.models.AnonymousUser object at 0x10d62d278>>":
"Visit.fk_visit_user" must be a "User" instance.
的 Models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class Main(models.Model):
name = models.CharField(max_length = 256)
date_of_birth = models.CharField(max_length = 256)
age = models.CharField(max_length=4)
def get_absolute_url(self):
return reverse('clincher:main-detail', kwargs={'pk': self.pk})
def __str__(self):
return self.name + ' - ' + self.date_of_birth
class Visit(models.Model):
fk_visit_main = models.ForeignKey(Main, on_delete=models.CASCADE, verbose_name=('Patient Name'))
visit_date = models.DateField(auto_now = True, editable=True)
fk_visit_user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name=('Practitioner'), max_length=500)
def __str__(self):
return '%s %s' % (self.visit_date, self.visit_label)
def get_absolute_url(self):
return reverse('clincher:main-detail', kwargs={'pk': self.pk})
Views.py
class VisitCreate(CreateView):
model = Visit
fields = [ 'visit_label', 'visit_type', 'visit_progress_notes']
def form_valid(self, form):
form.instance.fk_visit_user = self.request.user **Error Here**
form.instance.main_id = self.kwargs['pk']
return super(VisitCreate, self).form_valid(form)
def get_success_url(self):
return reverse('clincher:main-detail', args={'pk': self.object.id})
基本上,我需要有一个维持父子关系的表单,如果有更好的方式或更有效的方式,请告诉我。
答案 0 :(得分:2)
如错误所示,您正在尝试将AnonymousUser分配给该对象。这是因为访问您网页的用户未登录。您需要使用视图上的LoginRequired mixin来确保他们已登录。