0

I currently have a form that allows the user to edit their profile (django-profiles). The form is working great, except that I've put a switch in place for States and Provinces depending on whether ot not the user picks Canada or the US.

In my model, I have both State and Province set so that in the table there are 2 separate fields.

In my save method I have the following:

def user_created(sender, user, request, **kwargs):
    form = RegistrationFormZ(request.POST)
   ....stuff here.....
    if form.data["country"] == 'US':
      data.state = form.data["state"]
      data.provinces = None
    if form.data["country"] == 'CA':
      data.provinces = form.data["provinces"]
      data.state = None
   ....stuff here....
    data.save()

    user.first_name = form.data['first_name']
    user.last_name = form.data['last_name']
    user.save()

from registration.signals import user_registered
user_registered.connect(user_created)

The if statements are not working as I expected they would on save.

What's happening is that it correctly saves the value of the option that was selected (state/province) but then fails to update the opposing one to an empty value.

So for example let's say I had a user who had a Canadian address, and then updated it to the US address. The US state gets properly saved, but province does not get updated to None.

4

1 回答 1

0

也许更优雅的方式来实现这一点是使用字典。顺便说一句,您确定您的字段名称是省(复数)而不是单数吗?这是一个如何使用字典执行此操作的示例,请注意,您可以为不同的国家/地区添加更多字段而无需更多if语句,您甚至可以编写单独的 getter 函数来返回这些字典:

def user_created(sender, user, request, **kwargs):
    form = RegistrationFormZ(request.POST)

    ....stuff here.....

    data.state = None
    data.provinces = None

    state_field = {}
    state_field['US'] = {}
    state_field['US']['src'] = form.data['state']
    state_field['US']['dest'] = data.state

    state_field['CA'] = {}
    state_field['CA']['src'] = form.data['province']
    state_field['CA']['dest'] = data.province


    state_field[form.data['country'].upper()]['dest'] = state_field[form.data['country'].upper()]['src']

    ....stuff here....
    data.save()

    user.first_name = form.data['first_name']
    user.last_name = form.data['last_name']
    user.save()

from registration.signals import user_registered
user_registered.connect(user_created)
于 2012-05-18T21:25:28.027 回答