【问题标题】:Django form checkbox to change a value in UserProfileDjango 表单复选框以更改 UserProfile 中的值
【发布时间】:2013-07-02 19:45:12
【问题描述】:

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

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

模型.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。

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

if self.unsubscribe:

【问题讨论】:

  • 拥有更多代码上下文会很有帮助。 if self.unsubscribe: 在类的函数中吗?这是哪个班的?

标签: django django-forms django-profiles


【解决方案1】:

再次回答我自己的问题。在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多