Django 如何在表单中覆盖queryset none()属性并以某种方式允许保存字段?
我有模特Django 如何在表单中覆盖queryset none()属性并以某种方式允许保存字段?,django,django-forms,Django,Django Forms,我有模特 class Visit(Model): reference_visit = models.ForeignKey('self', help_text="Visit needs a refrence to Prior Visits", null=True, blank=True) show_prior_responses = models.BooleanField(default=False, help_text="Sh
class Visit(Model):
reference_visit = models.ForeignKey('self',
help_text="Visit needs a refrence to Prior Visits",
null=True, blank=True)
show_prior_responses = models.BooleanField(default=False,
help_text="Show PriorResponses")
# has many field but i am making it short.
def __unicode__(self):
result = """Visit id:%s pt:%s""" % (self.id, self.patient.id)
return result
forms.py
class VisitSetupForm(Form):
list_visit_ids = ModelChoiceField(
queryset=Visit.objects.none(),
empty_label='Select Revisit ID',required=False)
show_prior_visit = ModelChoiceField(
queryset=User.objects.all(),
empty_label="Select User for Revisit",required = False)
有很多问题,但问题在访问ID列表中。
views.py
def setup(request):
"""
Allow an Admin user the ability to setup a patient & visit all at once.
"""
if request.user.is_superuser:
form_class = AdminVisitSetupForm
all_topics = True
else:
form_class = VisitSetupForm
all_topics = False
f = form_class()
# Get a list of topics for each report.
report_topics = {}
for r in Interview.objects.all():
report_topics[r.id] = [t['ad'] for t in r.topics.values('ad')]
data = {
'superuser':request.user.is_superuser,
'report_topics':simplejson.dumps(report_topics)
}
try:
request.user.reviewer
data['reviewer'] = True
except:
pass
if request.method == "POST":
f = form_class(request.POST)
if f.is_valid():
# Create the patient, generate a password, and send them on their way.
cd = f.cleaned_data
patient = None
if cd['revisit']:
# Check for an existing user first.
try:
patient = Patient.objects.get(username=cd['username'])
except Patient.DoesNotExist, e:
data['form'] = f
data['msg'] = 'There is no user with this username.'
return render_to_response('visit/setup.html', data, context_instance=RequestContext(request))
admin_user = get_user(request)
organization = None
if admin_user:
organization = admin_user.organization
if patient and not request.user.is_superuser:
# Make sure the patient they've selected is one of their own.
if patient.organization != organization:
return HttpResponseForbidden('You are not allowed to see this page.')
if not patient:
password = generate_password()
user = User.objects.create_user(cd['username'], cd['contact_email'], password)
user.first_name = cd['first_name']
user.last_name = cd['last_name']
user.save()
patient = Patient(
user=user,
username=user.username,
contact_phone=cd['contact_phone'],
date_of_birth=cd['date_of_birth'],
email=user.email,
first_name=user.first_name,
gender=cd['gender'],
last_name=user.last_name,
maiden_name=cd['maiden_name'],
organization=organization,
patient_type=cd['patient_type'],
security_answer=cd['security_answer'],
security_question=cd['security_question'],
)
patient.save()
# Send them an email.
t = loader.get_template('www/new_account.txt')
c = Context({
'password':'%s-%s-%s' % (password[:3], password[3:5], password[5:]),
'patient':patient
})
msg = t.render(c)
try:
send_mail(
'A request by your physician to do an online medical history before your appointment.',
msg,
'support@careprep.com',
[user.email]
)
except Exception, e:
log.error('Could not send email for new account %s because: [%s]' % (user.username, e))
request.session['password'] = password
# Create the Visit, too.
interview = cd['interview']
list_visit_ids = cd['list_visit_ids']
print list_visit_ids
visit = Visit(
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
patient=patient
)
if request.user.is_superuser:
topics = cd['topics']
else:
topics = set(list(interview.topics.all()) + list(cd['topics']))
reviewer_mode = cd.get('reviewer_mode') or patient.patient_type == 'Reviewer'
url, visit = initialize_visit(
request,
patient=patient,
starting_section=interview.starting_section,
visit_title='%s %s' % (patient, interview.title),
topics=topics,
reviewer_mode=reviewer_mode,
chief_complaint=cd['chief_complaint'],
location=cd['interview_site'],
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
)
next_url = "/visit/confirmation/%s/%s/?next=%s" % (patient.user.id, interview.id, url)
else:
v = Visit.objects.get(pk=request.POST['list_visit_ids'])
print v
return HttpResponseRedirect(next_url)
# all the fields that are not given pls ignore.
模板很好。
现在,当我做list\u visit\u ID=ModelChoiceField(queryset=visit.objects.all(),empty\u label='Select retain ID',required=False)时,请看forms.py
它在我的本地机器上运行得非常好。但是在我的服务器上,它有大约6000个访问对象,所以这个页面挂起,或者我应该说继续加载
因此,最初我将其更改为list\u visit\u ID=modelcooicefield(queryset=visit.objects.none(),空的\u label='Select retain ID',required=False)
现在我知道,通过这种方式,表单变得无效,现在应该转到else部分。我的问题是,如何在else中制作reference\u visit=cd['list\u visit\u id'(表单无效)
case save()。
如何覆盖none()
属性
提前感谢,我会非常感激。如果您的目标是通过删除6000个选项来节省html页面负载(我也这么做了:用misc html包装的10000+
字段绝对会阻塞页面),那么您根本不应该使用选项字段。通过设置queryset=Visit.objects.none()
您可以显示6000个选择项下拉列表、单选框等,或者找到一种方法来/不/拥有一个巨大的选择下拉列表(例如隐藏的输入或字符字段),而不是围绕modelcooicefield
来伪造,其主要目的是填充该选择下拉列表并进行验证
简而言之:如果不打算使用由它生成的html选项,请不要使用modelcooicefield
。使用其他方法,通过clean_-FOO方法进行验证/建模
class MyForm(forms.Form):
my_input = forms.CharField()
def clean_my_input(self):
input = self.cleaned_data.get('my_input')
try:
return MyModel.objects.get(pk=input) # add a filter here if you want
# (whatever filters you were using in the queryset argument)
except MyModel.DoesNotExist:
raise forms.ValidationError("Doesn't exist / is invalid")
return input
如果您的目标是通过删除6000个选项来保存html页面负载(我也这么做了:用misc html包装的10000+
字段绝对会阻塞页面),那么您根本不应该使用选项字段。通过设置queryset=Visit.objects.none()
您可以显示6000个选择项下拉列表、单选框等,或者找到一种方法来/不/拥有一个巨大的选择下拉列表(例如隐藏的输入或字符字段),而不是围绕modelcooicefield
来伪造,其主要目的是填充该选择下拉列表并进行验证
简而言之:如果不打算使用由它生成的html选项,请不要使用modelcooicefield
。使用其他方法,通过clean_-FOO方法进行验证/建模
class MyForm(forms.Form):
my_input = forms.CharField()
def clean_my_input(self):
input = self.cleaned_data.get('my_input')
try:
return MyModel.objects.get(pk=input) # add a filter here if you want
# (whatever filters you were using in the queryset argument)
except MyModel.DoesNotExist:
raise forms.ValidationError("Doesn't exist / is invalid")
return input
我同意你的观点,但第二个下拉列表出现了问题,最初它没有加载任何内容。但当我从用户下拉列表中选择用户时,会进行ajax调用,并且会填充访问下拉列表,因此我只需要保存该值。表单处于无效状态。我正在寻找一种可以覆盖此内容的方法。我们可以在运行时覆盖它吗?我真的很感谢您的上述回答,这正是我所想的。如果没有使用modelcooicefield
来显示和限制选择,为什么您需要它的功能?只是不要使用那个字段,而是使用一个普通的旧CharField
,并按照您的意愿处理它!您可以动态创建一个ModelForm
,或者有两个不同的表单,或者通过form.fields['fieldname']=myfield()
设置字段,但我不明白您为什么会遇到这种麻烦。如果我对你的问题一点也不了解,请告诉我!我同意你的观点,但第二个下拉列表出现了问题,最初它没有加载任何内容。但当我从用户下拉列表中选择用户时,会进行ajax调用,并且会填充访问下拉列表,因此我只需要保存该值。表单处于无效状态。我正在寻找一种可以覆盖此内容的方法。我们可以在运行时覆盖它吗?我真的很感谢您的上述回答,这正是我所想的。如果没有使用modelcooicefield
来显示和限制选择,为什么您需要它的功能?只是不要使用那个字段,而是使用一个普通的旧CharField
,并按照您的意愿处理它!您可以动态创建一个ModelForm
,或者有两个不同的表单,或者通过form.fields['fieldname']=myfield()
设置字段,但我不明白您为什么会遇到这种麻烦。如果我对你的问题一点也不了解,请告诉我!