更改用户名或电子邮件可以,但不能更改个人资料图片。
我在“INSTALLED_APPS”中添加了我的个人资料应用程序,设置 MEDIA_ROOT 和 MEDIA_URL 并设置 urlspatterns :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'inscription.apps.InscriptionConfig',
'profile.apps.ProfilConfig',
]
[...]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
[...]
urlpatterns = [
path('profile/', p.profile, name='profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我将用户链接到其个人资料,设置默认图像models.py并在中注册模型admin.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_image')
def __str__(self):
return f"{self.user.username}'s Profile"
[...]
from django.contrib import admin
from .models import Profil
admin.site.register(Profil)
然后我在 forms.py 中创建了配置文件修改表单:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class ChangeUserForm(forms.ModelForm):
username = forms.CharField(
label = 'Username',
min_length = 4,
max_length = 150,
initial=User.username,
)
email = forms.EmailField(
label = 'Email',
min_length = 4,
max_length = 150,
)
class Meta:
model = User
fields = ['username', 'email']
class ChangeProfileForm(forms.ModelForm):
image = forms.FileField(
label = 'Profile form'
)
class Meta:
model = Profile
fields = ['image']
收到一只叮咚
相关分类