如何在编辑时根据存储的值显示/隐藏django表单字段?

798qvoo8  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(107)

models.py

cv_choices = (
    ('One Time', 'One Time'),
    ('Renewal', 'Renewal'),
)

class Certification(models.Model):
    user = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)
    certName = models.CharField(_('Certification Name'), max_length=100, null=True)
    certId = models.CharField(_('Certification ID'), max_length=100, null=True)
    certUrl = models.URLField(_('Certification URL'), max_length=500, null=True)
    certStartDate = models.DateField(_('Certification Start Date'), null=True)
    certEndDate = models.DateField(_('Certification End Date'), null=True, blank=True)
    certValidity = models.CharField(_('Certification Validity'), max_length=10, choices=cv_choices, default='Renewal', null=True)
    createdDate = models.DateTimeField(_('Created Date'), auto_now_add=True, editable=False)
    modifiedDate = models.DateTimeField(_('Modified Date'), auto_now=True, editable=False)

    def __str__(self):
        return self.certName

forms.py

class CertificationForm(forms.ModelForm):
    certValidity = forms.ChoiceField(choices=[('One Time', 'One Time'),('Renewal', 'Renewal')])

    class Meta:
        model = empCertification
        fields = ('user', 'certName', 'certId', 'certUrl', 'certStartDate', 'certEndDate', 'certValidity')

    def __init__(self, *args, **kwargs):
        super(empCertificationForm, self).__init__(*args, **kwargs)
        self.fields['user'].widget.attrs['class'] = 'form-select'
        self.fields['certName'].widget.attrs['class'] = 'form-control'
        self.fields['certId'].widget.attrs['class'] = 'form-control'
        self.fields['certUrl'].widget.attrs['class'] = 'form-control'
        self.fields['certStartDate'].widget.attrs['class'] = 'form-control'
        self.fields['certEndDate'].widget.attrs['class'] = 'form-control'
        self.fields['certValidity'].widget.attrs['class'] = 'form-select'
        for field in self.fields:
            self.fields[field].widget.attrs['placeholder'] = 'Provide Details'

编辑模板文件

<form action="{% url 'certificationEdit' certification.pk %}" method="post" class="form"
                                  enctype="multipart/form-data" novalidate>
                                {% csrf_token %}
                                <div class="card-body border-top p-9">
                                    {% if certificaitonForm.errors %}
                                        {% for field in certificaitonForm %}
                                            {% for error in field.errors %}
                                            <div class="alert alert-danger">
                                                <strong>{{field.name|title}} - {{error|escape}}</strong>
                                            </div>
                                            {% endfor %}
                                        {% endfor %}
                                        {% for error in certificaitonForm.non_field_errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{error|escape}}</strong>
                                        </div>
                                        {% endfor %}
                                    {% endif %}
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.user}}
                                                <label class="required">User</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certValidity}}
                                                <label>Certification Validity</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certName}}
                                                <label class="required">Certification Name</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certId}}
                                                <label class="required">Certification ID</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certUrl}}
                                                <label class="required">Certification URL</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certStartDate}}
                                                <label class="required">Certification Start Date</label>
                                            </div>
                                        </div>
                                        <div class="col-lg-6 certEndDate">
                                            <div class="form-floating mb-7">
                                                {{certificaitonForm.certEndDate}}
                                                <label>Certification End Date</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer d-flex justify-content-end py-6 px-9">
                                    <a href="{% url 'certificationList' %}" class="btn btn-light-info me-3">Discard</a>
                                    <button type="submit" class="btn btn-primary">Save Changes</button>
                                </div>
                            </form>

url.py

from django.urls import path
from . import views

urlpatterns = [
    path('certificationEdit/<int:pk>', views.certificationEdit, name='certificationEdit'),
]

views.py

@login_required(login_url='login')
def certificationEdit(request, pk):
    certification = get_object_or_404(empCertification, id=pk)
    certificaitonForm = empCertificationForm(instance=certification)
    if request.method == 'POST':
        certificaitonForm = empCertificationForm(request.POST, instance=certification)
        if certificaitonForm.is_valid():
            certificaitonForm.save()
            messages.success(request, 'Certification has been updated.')
            return redirect('certificationList')
        else:
            messages.error(request, 'Please correct form errors.')

    context = {
        'certification': certification,
        'certificaitonForm': certificaitonForm,
    }
    return render(request, 'back/pages/certification/update.html', context)

显示/隐藏表单字段我使用以下JavaScript函数在添加数据时显示和隐藏字段。

$('select[name="certValidity"]').on('change', function(){
        if ($(this).val() == 'One Time') {
            $('.certEndDate').hide();
        } else {
            $('.certEndDate').show();
        }
    });

但是当使用Django模板检索同一行时,它会显示所有字段。

**例如:**如果我将证书有效期保存为“一次性”,其中不包括“CertEndDate”,并且当我尝试检索相同的数据时,其显示“certEndDate”字段。

所以我的问题是如何在检索“一次性”证书数据时隐藏certEndDate

gtlvzcf8

gtlvzcf81#

我找到了解决上述问题的方法。
在这里分享会帮助其他人,如果他们有类似的问题。
您需要在模板文件中添加以下内容。

{% if certificaitonForm.certValidity.value != 'One Time' %}
<div class="col-lg-6 certEndDate">
   <div class="form-floating mb-7">
      {{certificaitonForm.certEndDate}}
      <label>Certification End Date</label>
   </div>
</div>
{% endif %}

相关问题