Мой пользовательский класс является расширением AbstractBaseUser и имеет поле site как поле ForeignKey из Django Site Framework, которое я сделал пустым и пустым True на время - будучи.
## MyUser Model
import uuid
from django.contrib.sites.managers import CurrentSiteManager
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.sites.models import Site
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import User
# Create your models here.
class MyUser(AbstractBaseUser, PermissionsMixin):
id = models.UUIDField(primary_key=True, editable=False,unique=True, default=uuid.uuid4)
email = models.EmailField(max_length=350, unique=True)
phone = PhoneNumberField(null=True, blank=True)
date_of_birth = models.DateTimeField(blank=True, null=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_Te = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = [] # by default username field and password
objects = MyUserManager()
on_site = CurrentSiteManager()
def __str__(self):
return self.email
class Meta:
unique_together = ('site', 'email')
@property
def is_admin(self):
return self.is_superuser
Мой вопрос в том, как мне написать код, чтобы любой пользовательский экземпляр, пытающийся создать, будет иметь поле сайта автоматически -назначено в зависимости от доменного имени, через которое оно пришло ?? Например, если пользователь был создан из http://127.0.0.1: 8000 / admin / user / myuser / присвоить полю сайта пользователя значение «1» (по моим текущим настройкам) или когда пользователь был создан из "www.example.com" присвоить полю сайта пользователя значение «2».
Хотя я не создавал никаких представлений для этого проекта и пытался создать пользователей только из панель администратора. Остальные мои коды ниже:
## MyUser's Model Manager
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError("User Must Have Email")
if not password:
raise ValueError("User Must Have password")
# implications- insert gathered Email i.e self.email into MyUser i.e self.model
email = self.normalize_email(email)
user = self.model(email=email, ** extra_fields)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
user = self.create_user(
email=email,
password=password,
**extra_fields
)
user.save(using=self.db)
return user
также инициировал структуру настройки В settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# for site's framework
'django.contrib.sites',
# Installed App
'user.apps.UserConfig',
# third-party app
'phonenumber_field',
'debug_toolbar',
]
SITE_ID = 1
## Forms.py
from django import forms
from .models import MyUser
from django.contrib.auth.forms import ReadOnlyPasswordHashField
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
fields = ('email', 'password', 'date_of_birth',
'is_active', 'is_superuser', 'phone')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
наконец admin.py
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from .forms import UserChangeForm, UserCreationForm
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import MyUser
class MyUserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_joined', 'is_superuser')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth', 'phone')}),
('Permissions', {'fields': ('is_superuser',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Register your models here.
admin.site.register(MyUser, MyUserAdmin)
admin.site.unregister(Group)
Также предложите любые необходимые правки, возможности или изменения поскольку я только начинаю с Django и пытаюсь выучить ..