【发布时间】:2018-09-02 22:16:56
【问题描述】:
所以我的 detailView 页面上有一个按钮,用于我的模型“患者”,它会将您带到我的另一个模型“约会”的 createView。我想要的是根据我来自的 detailView 预填充约会的外键字段。到目前为止,这是我的代码:
urls.py:
# /patients/appointment/add
url(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'),
models.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)
views.py:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
form-template.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>
appointment_form.html:
<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>
患者详情视图中创建预约的按钮:
<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>
例如,url 可能是 /appname/appointment/add/?Patient=pk ,其中结尾部分决定了 Patient 的值。我研究了 get_initial 函数,但不明白它如何帮助我实现这一目标。任何帮助表示赞赏。我对 django 比较陌生,所以请不要太复杂。
编辑:感谢 Dimitris Kougioumtzis,我已将此代码添加到我的模型中:
def get_context_data(self, **kwargs):
context = super(appointmentCreate, self).get_context_data(**kwargs)
context['patient_id'] = self.request.GET.get('patient')
return context
我如何实现这段代码?
【问题讨论】:
标签: django django-models django-forms django-views