简体   繁体   English

Django:如何使用“代码”和pre_save信号注册用户

[英]Django: How to register a user with “code” and pre_save signal

sorry if the title is not so descriptive, I did not know how to put it. 抱歉,如果标题不是那么描述性的,我不知道该怎么说。 I have two tables: 1.- The "Matricula" table which contains a code field and another "is_taken" field that is in "False" 2.- The "User" table and when registering a new user must insert an existing code in the table "Matricula", if the code exists then "is_taken" will be "True" and allow the user to register, my question is ... How can I do it ?, Which way would be the best? 我有两个表:1.-“矩阵”表,其中包含一个代码字段和另一个位于“ False”中的“ is_taken”字段2.-“用户”表以及在注册新用户时必须在其中插入现有代码在表格“矩阵”中,如果代码存在,则“ is_taken”将为“ True”并允许用户注册,我的问题是...我该怎么做?,哪种方法是最好的?

I was dealing with a "pre_save" signal but without success. 我当时正在处理“ pre_save”信号,但没有成功。

models.py models.py

class Matricula(models.Model):
    code = models.CharField(max_length=9, blank=True)
    is_taken = models.BooleanField("¿Esta ocupado?", default=False)
    created_at = models.DateTimeField("Fecha de creación", auto_now_add = True)
    updated_at = models.DateTimeField("Fecha de actualización", auto_now = True)

def __str__(self):
    return "%s" %(self.matricula)

class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
    code = models.CharField("Matricula", max_length=9, blank=True)
    email = models.CharField("Correo Electrónico", max_length=100, blank=True, unique=True)
    first_name = models.CharField("Nombre(s)", max_length=60, blank=True)
    last_name = models.CharField("Apellidos", max_length=60, blank=True)
    is_staff = models.BooleanField("¿Es Staff?", default=False, blank=True)
    is_active = models.BooleanField("¿Es Activo?", default=False, blank=True)
    date_joined = models.DateTimeField("Fecha de registro", auto_now_add=True)

Or could it be added in the views? 还是可以在视图中添加它? in the process of user registration? 在用户注册过程中?

And sorry for my bad english 对不起,我英语不好

If you want to add a matricula for each user, you should use relations, instead of a CharField, supposing each User have only one matricula use OneToOneField : 如果要为每个用户添加一个matricula ,则应该使用关系,而不是CharField,假设每个User只有一个matricula使用OneToOneField

class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
    matricula = models.OneToOneField(Matricula)

Well that part is easy, the problem come when you create the views, so if you create your modelform according with the relation, Django will show the existing matricula objects, so in your modelform exclude this field and in the view add the modelform of a matricula object so you can create it and save it. 好了,那部分很容易,问题是在创建视图时出现的,因此,如果您根据关系创建模型,Django将显示现有的matricula对象,因此在模型中,请排除此字段,然后在视图中添加模型的模型矩阵对象,因此您可以创建它并保存它。

def add_and_create_matricula(request):

    if request.method = 'POST':
        form_user = ModelForm_user(request.POST)
        form_matricula = ModelForm_matricula(request.POST)
        if form_user.is_valid and form_matricula.is_valid():
            matricula = form_matricula.save()
            user = form_user.save(commit=False)
            user.matricula = matricula # Here we add the realtion to the matricula
            user.save() # And save the relation

    form_user = ModelForm_user()
    form_matricula = ModelForm_matricula()
    return render(request, your_template.html, {'form_user':form_user, 'form_matricula':form_matricula})

Here I leave you an example how you should store the matricula object inside user 在这里,我为您提供一个示例,说明如何将matricula对象存储在user内部

Try not using signals as much as possible because they hurt code readabilty by inversion of control. 尽量不要使用信号,因为它们会因控制反转而损害代码的可读性。

As I understand your question you don't want people who do not have an invitation code, "Matricula" to be able to register on your site. 据我了解,您不希望没有邀请代码“ Matricula”的人能够在您的网站上注册。 You are better off doing it in your registration form. 您最好在注册表中填写。 Maybe something like this: 也许是这样的:

class UserRegistrationForm(AuthRegistrationForm):
    code = forms.CharField(max_length=9)

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
        try:
            matricula = Matricula.objects.get(code=cleaned_data.get('code', None), is_taken=False)
        except ObjectDoesNotExist:
            raise forms.ValidationError('Invalid code')
        else:
            cleaned_data['code'] = matricula

        return cleaned_data



# in your views:

.... if form.is_valid():
      matricula = form.cleaned_data['code']
      matricula.is_taken = True
      matricula.save()
      new_user = form.save()
.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM