如何使用 Crispy 表单使用会话变量填充输入文本?

How can I fill an input text with a session variable using Crispy forms?

如果存在会话变量,我需要自动完成字段,如果不存在,则将其留空。

但我不知道如何使用 Crispy 表单在 Django 中制作它。

这是观点:

def addclient(request):
    title = "Zona Clientes"
    form = NewClientForm(request.POST or None)

    if 'dni_cuit' in request.session:
        dni_cuit = request.session.get('dni_cuit')
        print("ESTÁ REGISTRADA LA SESSION DNI_CUIT"+dni_cuit)
        context = {
               "title": title,
               "form": form,
               "dni_cuit": dni_cuit
              }
    else:
        context = {
               "title": title,
               "form": form,
              }

    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        del request.session['dni_cuit']

        # Las 2 lineas anteriores pueden obviarse si solo queremos guardar
        # los datos sin hacer nada con ellos con la siguiente linea
        # form.save()

        context = {
                   "title": "Cliente Añadido - Gracias",
        }

    return render(request, "clients/addclient.html", context)

这是表格:

# Formulario crear cliente
class NewClientForm(forms.ModelForm):

    class Meta:
        model = Client
        fields = ['dni_cuit',
                  'first_name',
                  'last_name',
                  'phone',
                  'email',
                  'address',
                  ]

    def clean_dni_cuit(self):
        dni_cuit = self.cleaned_data.get('dni_cuit')
        return dni_cuit

    def clean_first_name(self):
        first_name = self.cleaned_data.get('first_name')
        return first_name

    def clean_last_name(self):
        last_name = self.cleaned_data.get('last_name')
        return last_name

    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        return phone

    def clean_email(self):
        email = self.cleaned_data.get('email')
        return email

    def clean_address(self):
        address = self.cleaned_data.get('address')
        return address

谁能告诉我如何为 dni_cuit 输入存储在 dni_cuit 上的值(如果已设置)?

您可以使用表格初始值

Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.

To accomplish this, use the initial argument to a Form. This argument, if given, should be a dictionary mapping field names to initial values. Only include the fields for which you’re specifying an initial value; it’s not necessary to include every field in your form.

所以在你的情况下,你检查会话并决定是否需要它。

if 'dni_cuit' in request.session:
    form = NewClientForm(request.POST or None, initial={'dni_cuit': request.session['dni_cuit']})
else:
    form = NewClientForm(request.POST or None)

Django docs

中阅读更多相关信息