所以我的detailView页面上有一个按钮,用于我的模特'患者',这会带你到我的其他模特'的createView。我想要的是预约的外键字段,这取决于我来自哪个DetailView。到目前为止,这是我的代码:
urls.py:
HTTP/1.0 200 OK
Date: Sun, 25 Mar 2018 08:54:07 GMT
Server: Apache
Accept-Ranges: none
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Connection: close
Expires: Wed, 11 Jan 1984 05:00:00 GMT
X-Frame-Options: sameorigin
Content-Type: audio/ogg; codecs=opus
models.py:
# /patients/appointment/add
url(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'),
views.py:
class patient(models.Model):
TITLE_CHOICES = (
('Mr', 'Mr'),
('Mrs', 'Mrs'),
('Ms', 'Ms'),
('Miss', 'Miss'),
)
Title = models.CharField(max_length=100, blank=True, choices=TITLE_CHOICES)
First_Name = models.CharField(max_length=250, default='')
Surname = models.CharField(max_length=250, default='')
DOB = models.DateField()
class appointment(models.Model):
Patient = models.ForeignKey(patient, on_delete=models.CASCADE)
形状template.html:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
appointment_form.html:
<body>
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
</body>
来自患者detailView的按钮创建约会:
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<h3>Add new appointment</h3>
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'patients/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
例如,网址可能是/ appname / appointment / add /?Patient = pk,其中结尾部分确定患者的价值。我已经研究了get_initial函数,但不明白它是如何帮助我实现这一目标的。任何帮助表示赞赏。我对django比较新,所以请不要太复杂。
编辑:我已将此代码添加到我的模型中,感谢Dimitris Kougioumtzis:
<ul class="nav nav-pills" style="margin-bottom: 10px;">
<li role="presentation" class="active"><a href="{% url 'patients:index' %}">View All</a></li>
<li role="presentation"><a href="{% url 'patients:appointment-create' %}">Add New Appointment</a></li>
</ul>
我如何实现此代码?
答案 0 :(得分:2)
首先创建一个modelForm:
from django import forms
from your_app.models import appointment
class AppointmentForm(forms.ModelForm):
class Meta:
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
然后在CreateView中传递模型表单:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
form_class = AppointmentForm
def get_initial(self):
patient = self.request.GET.get('patient')
return {
'patient': patient,
}
将根据请求获取参数
填充您的患者选择字段