使用在views.py中存在的方法中传递的变量检查signal.py中的条件-django

时间:2018-12-19 09:47:45

标签: python django django-views django-signals

我正在尝试评估一种情况。我有一个自定义用户模型(使用AbstractUser),其中包含一个名为“ role”的额外字段。我可以使用变量访问views.py中此字段的值。现在,我想在执行signals.py之前使用该变量检查post_save中的条件。 到目前为止,这是我的代码段。

views.py

from django.shortcuts import render, redirect
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test, login_required

# Create your views here.
@user_passes_test(lambda u: u.is_superuser)
def register(request):
    if request.method == 'POST':
        register_form = UserRegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data.get('username')
            role = register_form.cleaned_data.get('role') //**This is the variable**
            messages.success(request, f'Welcome {username}, thank you for signing up.')
            return redirect('home')
    else:
        register_form = UserRegisterForm()

    context = {
        'register_form' : register_form,
        'title' : 'Register'
    }

    return render(request, 'users/register.html', context)

signals.py

from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from .models import Teacher

User = get_user_model()
@receiver(post_save, sender=User)
def create_teacher(sender, instance, created, **kwargs):
    if created:
        if hasattr(instance, 'role') and role == 'teacher': //Here is the condition
            Teacher.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_teacher(sender, instance, **kwargs):
    instance.teacher.save()

有人可以帮我怎么做吗?谢谢

1 个答案:

答案 0 :(得分:0)

您为此付出了极大的努力。只需在视图中创建老师即可。

if register_form.is_valid():
    instance = register_form.save()
    username = register_form.cleaned_data.get('username')
    role = register_form.cleaned_data.get('role')
    if role == 'teacher':
        Teacher.objects.create(user=instance)
    messages.success(request, f'Welcome {username}, thank you for signing up.')
    return redirect('home')