Django设计问题: extending User to make users that can't log in

标签 django model extend django-authentication

我正在处理的网站涉及教师创建学生对象。教师可以选择允许学生登录该站点(查看日历等),或者教师可以选择仅将学生对象用于记录保存,不允许学生登录。在学生创建中形式,如果教师提供用户名和密码,它应该创建第一种对象 - 可以登录的对象,即常规用户对象。如果教师没有提供用户名/密码,则应创建第二种类型。另一个要求是老师应该可以稍后进入并将未登录的学生更改为另一种。为这种情况设计的最佳方法是什么?子类用户并不需要用户名和密码?这还会影响什么?

编辑: 我最终使用了 User.set_unusable_password()。这是代码 - 我省略了其他形式等,我也在我的观点中使用它们:

表单

class StudentForm(forms.ModelForm):
    username = forms.RegexField(regex=r'^\w+$',
                                required=False,
                                max_length=30,
                                label=("Username"),
                                error_messages={ 'invalid': ("This value must contain only letters, numbers and underscores.") })
    password = forms.CharField(widget=forms.PasswordInput(),
                                    label="Password", required=False)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email', 'password')

请注意,表单中不需要用户名和密码。

查看

def create_student(request):
    if request.method == "POST":
        student_form = StudentForm(request.POST)
        if student_form.is_valid():
            user = student_form.save(commit=False)
            if student_form.cleaned_data['username'] == '':
                user.username = generate_random_username()
                user.set_unusable_password()
            else:
                user.set_password(user.password)
            user.save()

            return HttpResponseRedirect(reverse('student_list', args=['active']))

    #GET an empty form
    else:
        student_form = StudentForm()

return render_to_response('priviostudio/create_student.html', {
    'student_form': student_form,
})

在编辑学生的 View 中(这可能会与 create_student View 结合使用)我有这个用于 GET:

student_form_initial = {
        'username': user_instance.username if user_instance.has_usable_password() else '',
        'password': user_instance.password if user_instance.has_usable_password() else '',
    }
    student_form = StudentForm(instance=user_instance, initial=student_form_initial)

在 POST 中,如果老师提交了新的用户名和有效密码,我将只在 User 实例上设置它们。

感谢大家的想法。

最佳答案

auth 应用程序的 User 模型有一个 set_unusable_password方法;这可能会做你想做的,而不需要扩展模型。

关于Django设计问题: extending User to make users that can't log in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2751431/

相关文章:

c# - 如何让 newtonsoft 将 yes 和 no 反序列化为 bool 值

python - Django 查询过滤器中的参数 "name__icontains"和 "description__icontains"是什么意思?

django - docker和django中无法连接到redis

model - 在 CakePHP 3.x 中订购 'Contain' 模型

php - 在 PHP 中扩展 DateTime 和 DateTimeImmutable

Java——引用不同类中的方法

javascript - 在for循环Angular2 Django中获取多个可观察请求

python - 找不到 `pip install -r requirements.txt` 安装的包

javascript - Backbone.Models this.get() 是复制整个数组还是指向内存中的同一个数组

ruby-on-rails - 是否有任何与 Rails 模型集成的 ETL 工具?