我已经在users/middleware.py
文件中创建了自定义中间件。直到昨天,该请求在中间件返回HttpResponseRedirect之后终止。但是今天,请求继续进行并重新加载了个人资料页面。下面是我的middleware.py文件。我正在使用Django 2.1.7
from django.utils.deprecation import MiddlewareMixin
import pytz
from django.urls import reverse_lazy , reverse
from django.utils import timezone
from django.http import HttpResponse ,HttpResponseRedirect
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
request.session['timezone'] = 'Asia/Kolkata'
timezone.activate(pytz.timezone('Asia/Kolkata'))
class CheckProfileMiddleware(MiddlewareMixin):
def process_request(self,request):
if request.user.first_name == "" or request.user.last_name == "":
if 'profile' not in request.path_info:
request.session['is_incomplete']=1
# return HttpResponse("ok")
return HttpResponseRedirect(reverse('profile'))
else:
request.session['is_incomplete']=0
return None
基本上,如果用户的个人资料不完整,我想将其重定向到个人资料页面。以下是我在setings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'users.middleware.TimezoneMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'users.middleware.CheckProfileMiddleware',
]
当我使用return HttpResponse
时,它会停止执行,但会继续在HttpResponseRedirect
上执行
这是我的URLConf。
path('profile/', profile, name='profile'),
我的view.py
@login_required
def profile(request):
user= User.objects.get(id=request.user.id)
user_profile = Profile.objects.get(user_id=request.user.id)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f' Your Profile has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context={
'profile' : profile,
'u_form': u_form,
'p_form': p_form,
'users':user,
}
return render(request,'profile.html', context)
答案 0 :(得分:0)
实际上我找到了解决方案。罪魁祸首是AJAX请求。在每个页面上,AJAX与页面加载同时调用。因此,每当调用AJAX时,中间件就将其视为GET请求,并再次重定向到profile
视图。所以我把条件放在中间件中以避免它是AJAX请求。我更新的middleware.py
class CheckProfileMiddleware(MiddlewareMixin):
def process_request(self,request):
if request.user.is_authenticated:
if not request.path.startswith(settings.STATIC_URL):
if request.user.first_name == "" or request.user.last_name == "":
if ('profile' not in request.path_info) and (not request.is_ajax()):
request.session['is_incomplete']=1
return HttpResponseRedirect(reverse('profile'))
else:
request.session['is_incomplete']=0