首页 > 解决方案 > 在更新表单之前,如何在表单中显示一行的 db 值?

问题描述

我试图在通过 URL 传递的 pk 过滤数据库后显示员工数据。

我可以更新表单,虽然我不希望表单字段为空,因为我只想更新,这意味着它不是我要接触的所有字段

表格.py

class AddEmployeeForm(forms.Form):

    genderset = [(0,'--Select an Option--'),('Male','Male'), ('Female', 'Female')]
    marital_status_set = [(0,'--Select an Option--'),('Married','Married'), ('Single', 'Single')]
    employment_type_set =  [(0,'--Select an Option--'),('Contract','Contract'), ('Full-Time', 'Full-Time'),('Intern', 'Intern')]
    employment_status_set =  [(0,'--Select an Option--'),('Active','Active'), ('Inactive', 'Inactive')]


    first_name = forms.CharField(label = "First Name ", max_length = 200)
    last_name = forms.CharField(label = "Last Name ", max_length = 200)
    employee_id = forms.IntegerField()
    email = forms.EmailField(label = "Email ", max_length = 200)
    address = forms.CharField(label = "Address", max_length = 200)
    role = forms.CharField( max_length = 200)
    date_of_birth = forms.DateField()
    join_date = forms.DateField()
    end_date = forms.DateField()
    location = forms.CharField( max_length = 200)
    hod  = forms.ModelChoiceField(queryset=Department.objects.only('lead'))
    phone_number = forms.CharField( max_length = 200)
    employment_type = forms.ChoiceField( choices = employment_type_set)
    employment_status = forms.ChoiceField( choices = employment_status_set  )
    marital_status = forms.ChoiceField( choices = marital_status_set )
    gender = forms.ChoiceField( choices = genderset )

    department = forms.ModelChoiceField(queryset=Department.objects.only('dept_name'))
    credentials = forms.FileField()
    passport = forms.FileField()
    date_added = forms.DateTimeField( initial = datetime.now, widget=forms.HiddenInput())


视图.py

@login_required(login_url='/accounts/login')
def edit(request, pk):
    employee = Employee.objects.filter(pk=pk)
    form = AddEmployeeForm()
    context = {
        'employee': employee,
        'form':form
    }


    return render(request, 'employees/edit.html', context)

编辑.html


{% extends 'base.html' %}
{% load crispy_forms_tags %}


{% block content %}

    <div class="page-wrapper">
        <div class="content container-fluid">
            <div class="row">
                <div class="col-xs-4">
                    <h4 class="page-title">Edit Employee Details</h4>
                </div>
                <div class="col-xs-4 text-center">
                    {% include "partials/_alerts.html" %}
                </div>
            </div>
            <form class="m-b-30" action="{% url 'add' %}" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="row"></div>
                    {% for field in form %}

                        <div class="col-sm-6">
                            <div class="form-group">

                                {{ field.errors }}
                                {{ field|as_crispy_field }}
                                {% if field.help_text %}
                                <p class="help">{{ field.help_text|safe }}</p>
                                {% endif %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>

                    <div class="m-t-20 text-center">
                        <button class="btn btn-primary">Save Changes</button>
                    </div>
            </form>
        </div>
    </div>

{% endblock content %}

它的意思是显示使用 PK 值从数据库中过滤出来的员工的值

标签: pythondjangodjango-modelsdjango-forms

解决方案


views.py中,您可以将字典传递给AddEmployeeForm构造函数以显示值:

@login_required(login_url='/accounts/login')
def edit(request, pk):
    employee = Employee.objects.filter(pk=pk)
    field_values = { 'first_name': employee.first_name } #...other fields
    form = AddEmployeeForm(field_values)
    context = {
        'employee': employee,
        'form':form
}
return render(request, 'employees/edit.html', context)

Form 实例要么绑定到一组数据,要么未绑定。

如果它绑定到一组数据,它就能够验证该数据并将表单呈现为 HTML,并在 HTML 中显示数据。

如果未绑定,则无法进行验证(因为没有要验证的数据!),但它仍然可以将空白表单呈现为 HTML。

参考https://docs.djangoproject.com/en/2.2/ref/forms/api/#ref-forms-api-bound-unbound


推荐阅读