我应该如何设置用户创建表单,以允许管理人员为员工创建帐户?

时间:2018-12-20 21:51:49

标签: django django-models django-forms

因此,我使用OneToOneField扩展了我的用户模型。我的目标是允许经理类型的用户创建员工用户。

我遇到的主要问题之一是填充啤酒厂外键字段。由于某种原因,无论何时我选择了一个啤酒厂,都提交该表单,即使选择了brewery_id,也会收到“无法将值NULL插入列'brewery_id'中”的信息。但是,仍然会创建用户,而不仅仅是扩展客户部分。

理想情况下,我希望根据创建该用户的管理员为新用户填充brewery_id。

我知道我的问题出在我看来,但是我能找到的所有示例仅用于更新当前用户。

models.py:

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    brewery = models.ForeignKey(Brewery, models.DO_NOTHING)
    phone_number = models.CharField(max_length=20)
    phone_carrier = models.CharField(max_length=80)
    role = models.CharField(max_length=60)

    class Meta:
        managed = True

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Customer.objects.create(user=instance)

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

forms.py:

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ('brewery', 'phone_number', 'phone_carrier', 'role')

views.py:

@login_required
def adminsite_register(request):
    if request.method == 'POST':
        user_form = UserRegisterForm(request.POST)
        cust_form = CustomerForm(request.POST)
        if user_form.is_valid() and cust_form.is_valid():
            user_form.save()
            cust_form.save()
            messages.success(request, f'Account has been created! You can now log in.')
            return redirect('index')
        else:
            messages.error(request, f'Please correct the errors.')
    else:
        user_form = UserRegisterForm(request.POST)
        cust_form = CustomerForm(request.POST)
    return render(request, "AdminSite/adminControls.html", {'user_form': user_form, 'cust_form': cust_form})

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的信号接收器中的这一行:

if created:
    Customer.objects.create(user=instance)

这正试图在不指定Customer的情况下创建Brewery,并会触发错误。

似乎您使用信号接收器的原因是将UserCustomer关联。在这样的视图中进行关联可能会更容易:

@login_required
def adminsite_register(request):
    ...
    if user_form.is_valid() and cust_form.is_valid():
        user = user_form.save()
        customer = cust_form.save(commit=False)  # Don't commit the customer just yet
        customer.user = user  # Associate the user
        customer.save()  # Now save the customer
        ...

然后完全删除信号接收器。