更改用户名或电子邮件可以,但不能更改个人资料图片。我在“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.pyfrom django.db import modelsfrom 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 adminfrom .models import Profil admin.site.register(Profil)然后我在 forms.py 中创建了配置文件修改表单:from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationFormfrom .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']
1 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
当您使用 HTML 形式的文件时,应该添加 enctype。
<form method="post" enctype="multipart/form-data">
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消