python Django:在表单中传递一个禁用选择字段的值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django:在表单中传递一个禁用选择字段的值相关的知识,希望对你有一定的参考价值。

from django.views.generic import CreateView

from contract.models import AssertRequest
from contract.forms import AssertRequestForm
from customer.utils import get_current_customer


class AssertRequestCreateView(CreateView):
    form_class = AssertRequestForm
    # ...

    def get_initial(self):
        initial = super(AssertRequestCreateView, self).get_initial()
        if self.customer:
            initial['customer'] = self.customer
        return initial

    def dispatch(self, *args, **kwargs):
        self.customer = get_current_customer(self.request)
        return super(AssertRequestCreateView, self).dispatch(*args, **kwargs)

    def get_form(self, form_class):
        form = form_class(**self.get_form_kwargs())
        if self.customer:
            # make a field readonly 
            form.fields['customer'].widget.attrs['disabled'] = True
            # limot choices to one value
            form.fields['customer'].choices = [(self.customer.id, self.customer),]
        return form
from django import forms

from customer.models import Customer

class AssertRequestForm(forms.ModelForm):
    customer = forms.ModelChoiceField(
        label=u'Cliente',
        queryset=Customer.objects.all(),
        required=False,
    )
    
    # ...

以上是关于python Django:在表单中传递一个禁用选择字段的值的主要内容,如果未能解决你的问题,请参考以下文章

在 Django 表单中水平对齐单选按钮

python Django:将表单视图中的变量传递给表单

如何在 django 中创建表单和模型中使用的字段的单选按钮

将HTML表单变量传递给Django中的python函数

choiceField的“禁用”选项 - Django

Django:如何创建多选表单?