Я хочу изменить изображение профиля по умолчанию в зависимости от пола. Я выбираю Мужской в форме регистрации, но всегда отображаю «default_f.png».
models.py
GENDER_CATEGORY = (
('U','Undefined'),
('F','Female'),
('M','Male')
)
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(upload_to="profile_pics",verbose_name="")
cover_image = models.ImageField(default="default_cover.jpg",upload_to="cover_pics",verbose_name="")
bio = models.CharField(max_length=160,null=True,blank=True)
location = models.CharField(max_length=30,null=True,blank=True)
birth_date = models.DateField(null=True,blank=True)
follow = models.ManyToManyField(User,related_name="follower")
date_created = models.DateTimeField(default=timezone.now)
gender = models.CharField(choices=GENDER_CATEGORY,max_length=2)
Сигналы
Поэтому я пробую это выражение if, но всегда показываю default_f.png. Я изменяю pre_save на post_save, но он не меняется.
def post_save_avatar(sender, instance, *args, **kwargs):
if not instance.image:
if instance.gender == 'M':
instance.image="default_m.jpg"
else:
instance.image = "default_f.png"
print(instance.gender)
pre_save.connect(post_save_avatar, sender=Profile)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile,sender=User)
forms.py
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('username','email','password1','password2')
class ProfileRegisterForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['bio','gender']
views.py
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
p_form = ProfileRegisterForm(request.POST)
if form.is_valid() and p_form.is_valid():
user = form.save()
user.refresh_from_db()#load the profile instance create by the signal
p_form = ProfileRegisterForm(request.POST,instance=user.profile)
p_form.full_clean()
p_form.save()
# username = form.cleaned_data.get('username')
return redirect('login')
else:
form = RegisterForm()
p_form = ProfileRegisterForm()
context = {
'form':form,
'p_form':p_form
}
fields = ['bio','gender']