在 Django 中使用更多字段扩展用户模型的最佳方法是啥?
Posted
技术标签:
【中文标题】在 Django 中使用更多字段扩展用户模型的最佳方法是啥?【英文标题】:What is the best way to extend User model with more fields in Django?在 Django 中使用更多字段扩展用户模型的最佳方法是什么? 【发布时间】:2022-01-05 23:08:49 【问题描述】:需要 Django 模型的帮助或资源。
你好,
我正在尝试修改/扩展django.contrib.auth.models.User
类,以便它可以注册更多字段,除了username
和password
。
目前,我仅将User
类实现为另一个Task 类中的外键。
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) # cascade deletes all tasks/items when user is deleted
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self) :
return self.title
class Meta:
ordering = ['complete']
我尝试了什么:
我尝试将其与 Employee
类建立一对一关系,但事情变得有些混乱,因为我需要先注册用户,然后再将属性添加到 Employee
以及选择(已经创建的)User
作为主键。我想这不切实际。
所以我的问题是:
在User
类中添加电子邮件、ID 号、名字、姓氏等属性的最佳方法是什么,以及如何在views.py
中实现/呈现适当的表单?
这是我的 views.py 文件:
from django.contrib.auth.mixins import LoginRequiredMixin # settings.py modification requried as following:
# add line: LOGIN_URL = 'login' above STATIC_URL field on line 120
from django.contrib.auth.forms import UserCreationForm # for registration
from django.contrib.auth import login
from .models import Task
# Create your views here.
class CustomLoginView(LoginView):
template_name = 'base/login.html'
fields = '__all__'
redirect_authenticated_user = True
def get_success_url(self):
return reverse_lazy('tasks') # Redirects to the homepage
class RegisterPage(FormView):
template_name = 'base/register.html'
form_class = UserCreationForm
redirect_authenticated_user = True
success_url = reverse_lazy('tasks')
def form_valid(self, form):
user = form.save()
if user is not None:
login(self.request, user)
return super(RegisterPage, self).form_valid(form)
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect('tasks')
return super(RegisterPage, self).get(*args, **kwargs)
class TaskList(LoginRequiredMixin ,ListView):
model = Task
context_object_name = 'tasks'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['tasks'] = context['tasks'].filter(user=self.request.user) # returns tasks from that user o.O
context['count'] = context['tasks'].filter(complete=False).count()
search_input = self.request.GET.get('search-area') or ''
if search_input:
context['tasks'] = context['tasks'].filter(title__icontains=search_input)
context['search_input'] = search_input
return context
class TaskDetail(LoginRequiredMixin, DetailView): # LoginRequiredMixin has to be added for security
model = Task
context_object_name = 'task'
template_name = 'base/task.html'
class TaskCreate(LoginRequiredMixin, CreateView):
model = Task
fields = ['title', 'description', 'complete']
success_url = reverse_lazy('tasks')
def form_valid(self, form):
form.instance.user = self.request.user
return super(TaskCreate, self).form_valid(form)
class TaskUpdate(LoginRequiredMixin, UpdateView):
model = Task
fields = ['title', 'description', 'complete']
success_url = reverse_lazy('tasks')
class TaskDelete(LoginRequiredMixin, DeleteView):
model = Task
context_object_name = 'task'
success_url = reverse_lazy('tasks')
和我的文件结构:
.
├── base
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_user.py
│ │ ├── 0003_delete_user.py
│ │ └── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── base
│ │ ├── login.html
│ │ ├── register.html
│ │ ├── task.html
│ │ ├── task_confirm_delete.html
│ │ ├── task_form.html
│ │ └── task_list.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── db.sqlite3
├── manage.py
└── todo_list
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
提前致谢! :)
【问题讨论】:
你可以看看这篇文章,也许会有所帮助:link 这能回答你的问题吗? Extending the User model with custom fields in Django 【参考方案1】:您可以从您正在使用的User
模型或AbstractUser
模型继承并创建您自己的用户模型,其中包含任意数量的字段
【讨论】:
以上是关于在 Django 中使用更多字段扩展用户模型的最佳方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章
在 Django 中扩展用户对象:用户模型继承还是使用 UserProfile?