我在django应用程序上有一个edit_profile视图,该视图还检查用户保存到其配置文件中的pgp密钥是否为RSA格式,无论如何,如果我第一次添加配置文件头像,它是否像超级按钮一样工作,如果我要清除或删除它,我总是跳到execpt块,并且用户头像保持不变。 好吧,我看不出为什么现在可以在这里给我一个提示的明确原因:
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)'
答案 0 :(得分:0)
尝试检测表单错误和异常错误
和 is_valid 是保存表单所必需的
尝试
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)
答案 1 :(得分:0)
似乎是Django-smartfields的错误,请参见:https://github.com/lehins/django-smartfields/issues/17 希望这个问题能很快得到解决!