我正在尝试找出允许用户使用django-allauth删除或停用其帐户的最佳方式,我假设我需要将is_active字段设置为False。
我的解决方案有以下几个问题: 1)渲染的复选框字段is_active显示文本"指定是否应将此用户视为活动用户。取消选择此项而不是删除帐户。"如何将此文本更改为"如果您确定要删除此帐户,请选中此框。"?
更新:刚刚实现检查框设置is_active为True,而取消选中框将其设置为False,那么我可能需要使用其他字段来验证表单?
2)如何在提交时注销用户?
forms.py:
class DeactivateUserForm(forms.ModelForm):
class Meta:
model = User
fields = ['is_active']
views.py:
login_required(login_url='/accounts/login/')
def deactivate_user_view(request):
pk = request.user.id
user = User.objects.get(pk=pk)
user_form = DeactivateUserForm(instance=user)
if request.user.is_authenticated() and request.user.id == user.id:
if request.method == "POST":
user_form = DeactivateUserForm(request.POST, instance=user)
if user_form.is_valid():
deactivate_user = user_form.save(commit=False)
user.is_active = False
deactivate_user.save()
return render(request, "account/userprofile_del.html", {
"user_form": user_form,
})
else:
raise PermissionDenied
userprofile_del.html:
<h2>Delete your account</h2>
<hr>
<form action="." method="POST" class="padding">{% csrf_token %}
{{ user_form.as_p}}
<button class="btn btn-primary" type="submit" name="action">{% trans "Confirm" %}</button>
</form>
答案 0 :(得分:2)
对于问题1,覆盖此字段的help-text属性;您可以在ModelForm的 init 方法中执行此操作。
SELECT
date_posts - INTERVAL WEEKDAY(date_posts) DAY AS date_start,
date_posts + INTERVAL (6 - WEEKDAY(date_posts)) DAY AS date_start,
COUNT(*) totalPosts,
COUNT(CASE WHEN Close_count = 1 THEN 1 END) closeCount,
COUNT(CASE WHEN Open_count = 1 THEN 1 END) openCount
FROM your_table
WHERE date_posts >= YOUR_START_DATE - INTERVAL WEEKDAY(YOUR_START_DATE) DAY
AND date_posts <= YOUR_END_DATE + INTERVAL (6 - WEEKDAY(YOUR_END_DATE)) DAY
GROUP BY YEARWEEK(date_posts,1);
对于问题2,您可能希望禁用allauth中介注销页面。在您的设置中:
SELECT
date_posts - INTERVAL WEEKDAY(date_posts) DAY AS date_start,
date_posts + INTERVAL (6 - WEEKDAY(date_posts)) DAY AS date_start,
COUNT(*) totalPosts,
COUNT(CASE WHEN Close_count = 1 THEN 1 END) closeCount,
COUNT(CASE WHEN Open_count = 1 THEN 1 END) openCount
FROM your_table
WHERE date_posts >= (CURDATE() - INTERVAL 5 WEEK) - INTERVAL WEEKDAY(CURDATE() - INTERVAL 5 WEEK) DAY
AND date_posts <= CURDATE() + INTERVAL (6 - WEEKDAY(CURDATE())) DAY
GROUP BY YEARWEEK(date_posts,1);
并重定向到视图逻辑中的注销页面。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="http://static.fusioncharts.com/code/latest/fusioncharts.charts.js"></script>
<script>
FusionCharts.ready(function () {
var csatscorechart = new FusionCharts({
type: 'angulargauge',
renderAt: 'chart-container',
width: '400',
height: '300',
dataformat: 'json',
datasource: {
"chart": {
"caption": "ph level in pond",
"subcaption": "current ph level",
"lowerlimit": "0",
"upperlimit": "14",
"showgaugeborder": "1",
"gaugebordercolor": "{dark-30}",
"gaugeborderthickness": "5",
"gaugeborderalpha": "14",
"showvalue": "1",
"valuebelowpivot": "1",
"theme": "fint"
},
"colorrange": {
"color": [
{
"minvalue": "0",
"maxvalue": "4",
"code": "#e44a00"
},
{
"minvalue": "5",
"maxvalue": "10",
"code": "#6baa01"
},
{
"minvalue": "10",
"maxvalue": "14",
"code": "#f8bd19"
}
]
},
"dials": {
"dial": [{
"value": "7"
}]
}
}
}).render();
});
//Tempreture sensor charts
FusionCharts.ready(function(){
var fusionchartstemp = new FusionCharts({
type: 'thermometer',
renderAt: 'chart-containertemp',
id: 'myThm',
width: '240',
height: '310',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Temperature Monitor",
"subcaption": " Central cold store",
"lowerLimit": "-10",
"upperLimit": "0",
"decimals": "1",
"numberSuffix": "°C",
"showhovereffect": "1",
"thmFillColor": "#008ee4",
"showGaugeBorder": "1",
"gaugeBorderColor": "#008ee4",
"gaugeBorderThickness": "2",
"gaugeBorderAlpha": "30",
"thmOriginX": "100",
"chartBottomMargin": "20",
"valueFontColor": "#000000",
"theme": "fint"
},
"value": "-6",
//All annotations are grouped under this element
"annotations": {
"showbelow": "0",
"groups": [{
//Each group needs a unique ID
"id": "indicator",
"items": [
//Showing Annotation
{
"id": "background",
//Rectangle item
"type": "rectangle",
"alpha": "50",
"fillColor": "#AABBCC",
"x": "$gaugeEndX-40",
"tox": "$gaugeEndX",
"y": "$gaugeEndY+54",
"toy": "$gaugeEndY+72"
}
]
}]
},
},
"events": {
"initialized": function(evt, arg) {
evt.sender.dataUpdate = setInterval(function() {
var value,
prevTemp = evt.sender.getData(),
mainTemp = (Math.random() * 10) * (-1),
diff = Math.abs(prevTemp - mainTemp);
diff = diff > 1 ? (Math.random() * 1) : diff;
if (mainTemp > prevTemp) {
value = prevTemp + diff;
} else {
value = prevTemp - diff;
}
evt.sender.feedData("&value=" + value);
}, 3000);
updateAnnotation = function(evtObj, argObj) {
var code,
chartObj = evtObj.sender,
val = chartObj.getData(),
annotations = chartObj.annotations;
if (val >= -4.5) {
code = "#00FF00";
} else if (val < -4.5 && val > -6) {
code = "#ff9900";
} else {
code = "#ff0000";
}
annotations.update("background", {
"fillColor": code
});
};
},
'renderComplete': function(evt, arg) {
updateAnnotation(evt, arg);
},
'realtimeUpdateComplete': function(evt, arg) {
updateAnnotation(evt, arg);
},
'disposed': function(evt, arg) {
clearInterval(evt.sender.dataUpdate);
}
}
}
);
fusionchartstemp.render();
});
</script>
</head>
<body>
<div align="center">
<h1>
Pond Gaurd
</h1>
<table>
<tr>
<td>
<div id="chart-container">FusionCharts will render here</div>
</td>
<td>
<div id="chart-containertemp">FusionCharts XT will load here!</div>
</td>
</tr>
</table>
<div style="height:333px"></div>
</div>
</body>
</html
这将重定向到注销网址,然后通过ACCOUNT_LOGOUT_REDIRECT_URL将用户转发到您设置中设置的网址。您的用户帐户现已停用,并且已注销。
答案 1 :(得分:1)
希望为停用和删除用户的视图提供潜在的答案。
# forms.py
from django import forms
class UserDeactivateForm(forms.Form):
"""
Simple form that provides a checkbox that signals deactivation.
"""
deactivate = forms.BooleanField(required=True)
class UserDeleteForm(forms.Form):
"""
Simple form that provides a checkbox that signals deletion.
"""
delete = forms.BooleanField(required=True)
# views.py
# You could make this DRYer, but sometimes repeating yourself
# for explicitness makes sense.
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth import logout
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import View
from .forms import UserDeactivateForm, UserDeleteForm
class UserDeactivateView(LoginRequiredMixin, View):
"""
Deactivates the currently signed-in user by setting is_active to False.
"""
def get(self, request, *args, **kwargs):
form = UserDeactivateForm()
return render(request, 'users/user_deactivation.html', {'form': form})
def post(self, request, *args, **kwargs):
form = UserDeactivateForm(request.POST)
# Form will be valid if checkbox is checked.
if form.is_valid():
# Make user inactive and save to database.
request.user.is_active = False
request.user.save()
# Log user out.
logout(request)
# Give them a success message.
messages.success(request, 'Account successfully deactivated')
# Redirect to home page.
return redirect(reverse('home'))
return render(request, 'users/user_deactivation.html', {'form': form})
class UserDeleteView(LoginRequiredMixin, View):
"""
Deletes the currently signed-in user and all associated data.
"""
def get(self, request, *args, **kwargs):
form = UserDeleteForm()
return render(request, 'users/user_deletion.html', {'form': form})
def post(self, request, *args, **kwargs):
form = UserDeleteForm(request.POST)
# Form will be valid if checkbox is checked.
if form.is_valid():
user = request.user
# Logout before we delete. This will make request.user
# unavailable (or actually, it points to AnonymousUser).
logout(request)
# Delete user (and any associated ForeignKeys, according to
# on_delete parameters).
user.delete()
messages.success(request, 'Account successfully deleted')
return redirect(reverse('home'))
return render(request, 'users/user_deletion.html', {'form': form})
然后,您需要为每个模板和URL路由创建模板,但是模板应该非常简单。