我正在尝试为用户构建一种键入"代码"如果代码与存储在单独模型字段中的值等于相同的字符串,则允许表单保存并更新名为"注册"的模型布尔字段。
这是我的模特:
def random_key(size=25, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class Keyreg(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
privKey = models.CharField(max_length=50, default=random_key, editable = False)
pubKey = models.CharField(max_length=50, default='feedme123')
registered = models.BooleanField(default=False)
这是我的modelForm:
class KeyregForm(forms.ModelForm):
class Meta:
model = models.Keyreg
fields = ('pubKey',)
def clean(self):
cleaned_data = super(KeyregForm, self).clean()
privKey = # data already saved in db... ?
pubKey = cleaned_data.get('pubKey')
if pubKey != privKey:
raise forms.ValidationError("Your Registration Is Invalid.")
return cleaned_data
这是我的观点:
@login_required
def update_pubkey(request):
profile = get_object_or_404(Profile, user=request.user)
pubkey = get_object_or_404(Keyreg, user=request.user)
pub_key = Keyreg.objects.filter()
form = KeyregForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return HttpResponseRedirect("/me/keyzone/")
return render(request, 'keyzone.html', {'form':form, 'pubkey':pubkey,
'pub_key', pub_key})
任何帮助都会很棒,谢谢你的时间。
答案 0 :(得分:1)
如果您的模型实例已经在数据库中,那么只有您可以获得privKey。为此,您需要将Keyreg的实例传递给表单: 在您的视图中编辑此行:
form = KeyregForm(request.POST, instance=pubkey)
并修改干净方法:
def clean(self):
cleaned_data = super(KeyregForm, self).clean()
if self.instance.pk:
privKey = self.instance.privKey
pubKey = cleaned_data.get('pubKey')