ユーザープロフィール
15107 ワード
モデル.パイ
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class profile(models.Model):
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
user = models.OneToOneField(User, on_delete=models.CASCADE)
def save(self, *args, **kwargs):
super(profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (150, 150)
img.thumbnail(output_size)
img.save(self.image.path)
フォーム.パイfrom .models import profile
from django import forms
class updateProfile(forms.ModelForm):
class Meta:
model = profile
fields = ['image']
ビューパイfrom .forms import updateProfile
def profilePage(request):
if request.method == 'POST':
form = updateProfile(request.POST, request.FILES, instance=request.user.profile)
if form.is_valid():
print('ok')
form.save()
return redirect('profile')
else:
form = updateProfile()
context = {'form':form}
return render(request, 'app/profile.html',context)
プロファイル.HTML<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Info</legend>
{{ form }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
URL.パイurlpatterns = [
path('profile/',views.profilePage,name='profile'),
]
シグナルを作成する.パイfrom django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import profile
from django.core.exceptions import ObjectDoesNotExist
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
try:
instance.profile.save()
except ObjectDoesNotExist:
profile.objects.create(user=instance)
アプリ.パイfrom django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app'
def ready(self):
import app.signals
URL.Py in mainプロジェクトfrom django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('app.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
設定パイimport os
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
移動をする> Python manage.py makemigrations
> Python manage.py migrate
100 %良い仕事を楽しんでください
Reference
この問題について(ユーザープロフィール), 我々は、より多くの情報をここで見つけました https://dev.to/phansivang/django-user-profile-ln7テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol