Когда я использую одиночную форму, проблем не возникает, но когда я использую мультиформы в представлении на основе классов, проверка проходит нерегулярно с полем изображения и пропускается из условия if в views.py. Я пытался исправить с помощью предыдущего решения, предоставленного в переполнении стека, но не смог его решить.
views.py
коды в представлениях
class ProfileEditView(View):
profile_class = ProfileForm
profile_image_class = ProfileImageForm
template_name = 'user/profile_edit.html'
def get(self,request,pk):
if pk:
user = User.objects.get(pk=pk)
profile = Profile.objects.get(user = user)
profile_image = ProfileImage.objects.get(user = user)
profile_form = self.profile_class(instance = profile)
profile_image_form = self.profile_image_class(instance = profile_image)
context = {
'profile_form':profile_form,
'profile_image_form':profile_image_form
}
return render(request, self.template_name, context)
else:
profile_form = self.profile_class(None)
profile_image_form = self.profile_image_class(None)
context = {
'profile_form':profile_form,
'profile_image_form':profile_image_form
}
return render(request, self.template_name, context)
def post(self,request,pk=None, **kwargs):
profile_form = self.profile_class(request.POST,instance=Profile())
profile_image_form = self.profile_image_class(request.POST,instance=ProfileImage())
if profile_image_form.is_valid(): #and profile_image_form.is_valid():
profile = profile_form.save(commit=False)
profile_image = profile_image_form.save(commit=False)
profile.user = self.request.user
profile_image.user = self.request.user
profile.save()
profile_image.save()
return redirect('music:album_list')
context = {
'profile_form':profile_form,
'profile_image_form':profile_image_form,
'error_message':'Something went wrong',
}
return render(request, self.template_name, context)
models.py
коды в модели
def get_profile_upload_to(instance,filename):
new_filename = '{}.{}'.format(uuid4,filename.split('.')[-1])
return "profile/{}/{}".format(instance.user.id, new_filename)
class ProfileImage(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(upload_to=get_profile_upload_to)
uploaded = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
bio = models.TextField(max_length=500,null=True, blank=True)
location = models.CharField(max_length=50,null=True, blank=True)
birth_date = models.DateField(null=True, blank=True)
email_confirmed = models.BooleanField(default=False)
form.py
коды в form.py
class ProfileImageForm(forms.ModelForm):
class Meta:
model = ProfileImage
fields = ['image']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['birth_date']