我绝对是python,django框架的初学者。我不知道如何在Django中制作自定义装饰器。 我正在尝试,如果用户的个人资料已100%完成,他们可以申请工作,否则他们会显示警告消息“您的个人资料已完成,请首先完成您的个人资料,然后申请此工作”
我遵循以下代码 models.py
class profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True)
random = models.CharField(max_length=50)
image = models.ImageField(upload_to="profile_pics")
def __str__(self):
return f'{self.user.username} profile'
def get_absolute_url(self):
return reverse('jobseeker:profile_count')
@property
def percentage_complete(self):
percent = { 'random': 50, 'image': 50}
total = 0
if self.random:
total += percent.get('random', 0)
if self.image:
total += percent.get('image', 0)
return total
decorators.py
def complete_profile_required(view_func):
def wrapper_func(request, *args, **Kwargs):
if request.user.profile.percentage_complete == 100:
print(request.user.profile.percentage_complete)
return redirect('jobseeker:apply_job')
else:
return view_func(request, *args, **Kwargs)
return wrapper_func
views.py
@login_required
@jobseeker_required
@complete_profile_required
def apply_job(request):
return render(request, 'apply_job.html')
urls.py
path('apply_job', views.apply_job, name='apply_job')
答案 0 :(得分:0)
您必须重定向到另一个视图。您收到TOO_MANY_REDIRECTS
错误。因为您将其重定向到同一视图。
您必须更换装饰器
def complete_profile_required(view_func):
def wrapper_func(request, *args, **Kwargs):
if request.user.profile.percentage_complete == 100:
# change your logic here
return redirect('jobseeker:another_view')
else:
return view_func(request, *args, **Kwargs)
return wrapper_func