【问题标题】:Django pre-filling data in form from URLDjango 从 URL 预填充表单中的数据
【发布时间】: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


    【解决方案1】:

    首先你创建一个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,
          }
    

    并且您的患者选择字段将根据请求获取参数填充

    【讨论】:

    • 感谢您的回复。我真的不明白代码。您能否进一步解释一下,因为我是 django 的新手。 (cmets 会很好)
    • 有道理,但是,在表单中,我将如何设置值?我将更新我的问题以显示模板
    • Django 有许多钩子可以在表单中传递请求获取参数。您必须决定哪个更适合您的实施。
    • 我做了一点修改。患者中的 p 应该是大写的,我不得不添加一些词。
    猜你喜欢
    • 2012-08-14
    • 2018-08-15
    • 2012-07-20
    • 2013-05-23
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多