i have a edit_profile view at my django application that also checks if the pgp key the users saves to his profile is in RSA format, Anyways if i add a profile avatar for the very first time it works like a charm, if i want to clear or delete it, im always jumping onto the execpt block and the user avatar remains unchanged. Well i dont see a clear reason why at the point can maybe smb give me a hint here:
validators.py
def default_image_file_extension(value):
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.jpg', '.jpeg', '.png']
if not ext.lower() in valid_extensions:
raise ValidationError(u'Unsupported file extension. Allowed types are: .jpg, .jpeg, .png')
def default_image_size(value):
limit = 2 * 1024 * 1024
if value.size > limit:
raise ValidationError('File too large. Size should not exceed 2 MiB/MB.')
models.py
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('media', filename)
def get_file_path_user_avatar(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('user_avatar', filename)
...
class User(AbstractBaseUser):
user = models.CharField(verbose_name='Username', max_length=20, unique=True)
bio = models.TextField(verbose_name='Bio', blank=True, null=True, max_length=2500)
pubpgp = models.TextField(verbose_name='Public RSA PGP Key - (ASCII-Armored)', blank=True, null=True, max_length=3000)
avatar = fields.ImageField(
null=True,
blank=True,
upload_to=get_file_path_user_avatar,
validators=[default_image_size, default_image_file_extension],
dependencies=[FileDependency(processor=ImageProcessor(
format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))])
views.py
def edit_profile(request):
if request.method == 'POST':
form = UserForm(request.POST, request.FILES, instance=request.user)
try:
pubpgp = request.POST.get('pubpgp')
if not pubpgp or PGPKey.from_blob(pubpgp.rstrip("\r\n"))[0].key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign:
if form.is_valid():
form.save()
messages.success(request, "Profile has been updated successfully.")
return redirect(reverse('home'))
else:
print(form.errors)
return render(request, 'app_Accounts/edit_profile.html', {'form': form})
else:
messages.error(request, "Uuups, something went wrong, please try again.")
return render(request, 'app_Accounts/edit_profile.html', {'form': form})
except Exception as e:
print(e.args)
messages.error(request, "PGP-Key is wrong formated.")
return render(request, 'app_Accounts/edit_profile.html', {'form': form})
else:
form = UserForm(instance=request.user)
args = {'form': form}
return render(request, 'app_Accounts/edit_profile.html', args)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = (
'avatar',
'bio',
'pubpgp'
)
captcha = CaptchaField()
field_order = ['avatar', 'bio', 'pubpgp']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['avatar'].label = mark_safe('Avatar:')
self.fields['avatar'].help_text = mark_safe("<h4 class='help_text'>→ Choose a Avatar for your Profile (max. 2 MB)</h4>")
self.fields['bio'].widget.attrs.update({'class': 'class-two-input-fields'})
self.fields['bio'].help_text = mark_safe("<h4 class='help_text'>→ Something about you</h4>")
self.fields['pubpgp'].widget.attrs.update({'class': 'class-two-input-fields'})
self.fields['pubpgp'].label = 'Public PGP-key (Optional)'
from Django unable to delete/clear data on form