0

I have the following existing code to work with (I included just the relevant parts).

models.py

class Customer(models.Model):
    customer_id = models.CharField(primary_key=True, max_length=16)
    account_phone = PhoneNumberField(null=True, blank=True, max_length=255)
    display_phone = PhoneNumberField(null=True, blank=True, max_length=255)
    .
    .
    .

customer.py

@render_to('customer/edit.html')
def edit(request, customer_id):
    customer = Customer.objects.get(customer_id=customer_id)
    if not request.POST:
        return dict(form=CustomerForm(instance=customer))
    submit = request.POST.copy()
    submit['customer_id'] = customer.customer_id
    form = CustomerForm(submit, instance=customer)
    if not form.is_valid():
        return dict(form=form)
    _f = form.save(commit=False)
    _f.save()

class CustomerForm(ModelForm):
    .
    .
    .
    def __init__(self, *args, **kwargs)
        super(CustomerForm, self).__init__(*args, **kwargs)
        .
        .
    class Meta:
        model = Customer

I need to add a query to the CustomerForm called something like assigned_numbers that will allow me to get the phone numbers from account_phone and display_phone that are associated with the customer_id. I am getting stuck on how to run the query correctly and would greatly appreciate any suggestions. If I need to provide more information, please let me know.

4

1 回答 1

0

您的表单是 的模型表单,因此除非您以排除它们的方式指定了字段,否则customer它将具有字段account_phone并且已经存在。display_phone

如果您需要对它们做一些事情,除了根据您的客户实例开始填充它们的字段之外,您可以访问form.instance.account_phone或其他任何东西。

如果由于某种原因更方便,在您的__init__方法中,您可以访问instancefromkwargs以查找值。

def __init__(self, *args, **kwargs)
    super(CustomerForm, self).__init__(*args, **kwargs)
    if 'instance' in kwargs:
        self.assigned_numbers = (instance.account_phone, instance.display_phone)
于 2013-06-13T21:44:17.503 回答