0

我正在使用 Django 为用户创建一个 OneToOneField 对象,代码如下:

class ControlInformation(models.Model):
    user = models.OneToOneField(User)

    TURN_ON_OFF = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    AUTO_MANU = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    TEMP_DINNINGROOM = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    TEMP_LIVINGROOM = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    turn_on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
    auto_manu = models.CharField(max_length = 2, choices=AUTO_MANU)
    temp_dinningroom = models.CharField(max_length=2, choices=TEMP_DINNINGROOM)
    temp_livingroom = models.CharField(max_length=2, choices=TEMP_LIVINGROOM)


#signal function: if a user is created, add control information to the user    
def create_control_information(sender, instance, created, **kwargs):
    if created:
        ControlInformation.objects.create(user=instance)

post_save.connect(create_control_information, sender=User)

然后,我使用以下代码为该对象创建了一个表单:

class ControlInformationForm(forms.Form):

    TURN_ON_OFF = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    AUTO_MANU = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    TEMP_DINNINGROOM = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    TEMP_LIVINGROOM = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    on_off = forms.ChoiceField(label="on_off", choices=TURN_ON_OFF)
    auto_manu = forms.ChoiceField(label="auto_manu", choices=AUTO_MANU)
    temp_dinningroom = forms.ChoiceField(label="temp_dinningroom", choices=TEMP_DINNINGROOM)
    temp_livingroom = forms.ChoiceField(label="temp_livingroom", choices=TEMP_LIVINGROOM)

最后,我用

ControlInformation = request.user.get_profile()
form=ControlInformationForm(request.POST)

在views.py 中获取ControlInformation 对象的值,但它不起作用(错误:'UserProfile' 对象没有属性'turn_on_off')。我认为问题的发生是因为我使用了request.user.get_profile(). 我如何修改它以获取 ControlInformation 对象的值,然后修改并保存()它?

4

1 回答 1

1

而不是ControlInformation = request.user.get_profile()使用:

instance = ControlInformation.objects.get(user=request.user)

还有一些提示:

  • 用于ModelForm从您的模型自动创建表单。

  • 您可以使用 aBooleanField代替 ON/OFF。

您可以对两个字段使用一次查找:

  TEMP = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
  )

享受姜戈!

于 2013-11-13T10:18:51.663 回答