Django表单复选框以更改UserProfile中的值

时间:2013-07-02 19:45:13

标签: django django-forms django-profiles

我正在使用Django-Profiles与Django 1.4,我需要一种取消订阅用户的方法,这样他们就可以停止收到电子邮件了。

我的UserProfile模型中的一个字段是user_type,我有一个USER_TYPES选项列表。为了让用户保持在系统中,即使他们取消订阅,我决定让其中一个USER_TYPES为InactiveClient,并且我会包含一个如下的复选框:

Models.py:

USER_TYPES = (
    ('Editor', 'Editor'),
    ('Reporter', 'Reporter'),
    ('Client', 'Client'),
    ('InactiveClient', 'InactiveClient'),
    ('InactiveReporter', 'InactiveReporter'),
)

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)
    user_type = models.CharField(max_length=25, choices=USER_TYPES, default='Client')
    ... etc.

forms.py

class UnsubscribeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UnsubscribeForm, self).__init__(*args, **kwargs)
        try:
            self.initial['email'] = self.instance.user.email
            self.initial['first_name'] = self.instance.user.first_name
            self.initial['last_name'] = self.instance.user.last_name
        except User.DoesNotExist:
            pass
    email = forms.EmailField(label='Primary Email')
    first_name = forms.CharField(label='Editor first name')
    last_name = forms.CharField(label='Editor last name')    
    unsubscribe = forms.BooleanField(label='Unsubscribe from NNS Emails')

    class Meta:
        model = UserProfile
        fields = ['first_name','last_name','email','unsubscribe']

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.email = self.cleaned_data['email']
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        if self.unsubscribe:
            u.get_profile().user_type = 'InactiveClient'
        u.save()
        client = super(UnsubscribeForm, self).save(*args,**kwargs)
        return client

修改:我添加了其他代码上下文。如果self.unsubscribe:在save()覆盖中。那应该在别的地方吗?谢谢。

Edit2:我尝试过多种方式更改UnsubscribeForm。现在我得到一个404,没有用户匹配给定的查询。但被调用的视图函数适用于其他形式,所以我不确定为什么?

urls.py

urlpatterns = patterns('',
    url('^client/edit', 'profiles.views.edit_profile',
        {
            'form_class': ClientForm,
            'success_url': '/profiles/client/edit/',
        },
        name='edit_client_profile'),
    url('^unsubscribe', 'profiles.views.edit_profile',
        {
            'form_class': UnsubscribeForm,
            'success_url': '/profiles/client/edit/',
        },
        name='unsubscribe'),
        )

这两个url正在使用不同的form_class调用相同的视图。

编辑3:所以我不知道为什么,但是当我从取消订阅网址中删除尾部斜杠时,表单最终会加载。但是当我提交表单时,我仍然会收到一个错误:'UnsubscribeForm'对象没有属性'取消订阅'如果有人可以帮助我理解为什么一个尾部斜杠会导致404错误(没有用户匹配给定的查询)我不会心灵知道。但截至目前,表单已加载,但未提交,并且跟踪在我的表单的这一行结束:

if self.unsubscribe:

1 个答案:

答案 0 :(得分:0)

再次回答我自己的问题。在ModelForms上,您可以添加模型中不存在的表单元素,并通过访问save方法中的self.cleaned_data [' form_element_name']来访问这些字段的值。

这就是我的保存方法:

def save(self, *args, **kwargs):
    u = self.instance.user
    p = self.instance.user.get_profile()
    u.email = self.cleaned_data['email']
    u.first_name = self.cleaned_data['first_name']
    u.last_name = self.cleaned_data['last_name']
    if self.cleaned_data['unsubscribe']:
        p.user_type = 'InactiveClient'
    u.save()
    p.save()
    client = super(UnsubscribeForm, self).save(*args,**kwargs)
    return client