Reputation: 525
Basically, I'm creating an app and currently I'm testing out an "Edit Profile" feature. For me (the admin) I manually added myself to the Profile model using the admin page. However, when I tried it on my test account, it didn't work. I know what the problem is (I didn't add him to the model) but I was wondering how I could fix it. Here's my model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
Here's my views.py:
@login_required
def profile(request):
user_form = UpdateUser()
profile_form = UpdateProfile()
if request.method == 'POST':
user_form = UpdateUser(request.POST, instance = request.user)
profile_form = UpdateProfile(request.POST,
request.FILES,
instance = request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('profile')
else:
user_form = UpdateUser(instance = request.user)
profile_form = UpdateProfile(instance = request.user.profile)
context = {
'user_form' : user_form,
'profile_form' : profile_form
}
My signals.py:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@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):
instance.profile.save()
And finally, my apps.py:
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social',
'crispy_forms',
'users',
'users.apps.UsersConfig',
]
Upvotes: 0
Views: 66
Reputation: 3429
add args
to your save method:
@receiver(post_save, sender=User)
def save_profile(sender, instance, *args, **kwargs):
instance.profile.save()
Upvotes: 1