我使用Django-Profiles与Django 1.4,我需要一种方式取消订阅一个用户,以便他们可以停止收到电子邮件。
我的UserProfile模型中的一个字段是user_type,我有一个USER_TYPES选项列表。为了将用户保留在系统中,即使他们取消订阅,我也决定拥有一个USER_TYPES be 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'),
)这两个urls只使用不同的form_class调用相同的视图。
Edit3:,所以我不知道为什么,但是当我从取消订阅url中删除尾随斜杠时,表单最终会加载。但是当我提交表单时,我仍然会得到一个错误:'UnsubscribeForm‘对象没有属性’un订阅‘,如果有人可以帮助我理解为什么拖尾斜杠会导致404错误(没有用户与给定的查询匹配),我不介意知道。但到目前为止,表单加载,但不提交,跟踪结束在我的表单的这一行:
if self.unsubscribe:发布于 2013-07-17 14:33:15
再次回答我自己的问题。在ModelForms上,可以添加模型中不存在的表单元素,并通过访问保存方法中的自清洁_数据‘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 clienthttps://stackoverflow.com/questions/17434480
复制相似问题