我尝试借助django doc设置唯一的6位支票号码。但是我仍然不希望得到期望的结果,它意味着它接受任何数字或字符,但是我希望它仅接受6个整数,并且还要确保该数字对于所有用户都应该是唯一的
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from uuid import uuid4
import string
from string import digits
class Mvouchar(models.Model):
cheque_no = models.CharField(max_length=6, null=True, blank=True, unique=True)
dated = models.DateTimeField(auto_now_add=True,null=True, blank=True)
def id_generator(size=6, chars=string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def save(self):
if not self.cheque_no:
self.cheque_no = id_generator()
while Mvouchar.objects.filter(cheque_no=self.cheque_no).exists():
self.cheque_no = id_generator()
self.dated = datetime.now()
super(Mvouchar, self).save()
def __str__(self):
if self.related:
return self.related.relation.username.title()
else:
return 'no related!'
class Meta:
verbose_name_plural = "Single Cheque Multiple Vouchar Of Users"
views.py
def mvouchar(request):
if request.method == "POST":
userdata = User.objects.get(username = request.user)
accountdata = Signs.objects.get(relation_id=userdata.id)
chq_no = request.POST['chequeno']
mini = Mvouchar(related_id=accountdata.id, cheque_no = chq_no)
mini.save()
messages.success(request, "Your Cheque is Created")
return HttpResponseRedirect("/mvouchar/")
return render(request, 'cheque/mvouchar.html', {})
答案 0 :(得分:1)
对于这样的示例,使用表格是标准做法,但我仍然考虑了您的示例并给出了解决方案。希望这对您有用。
models.py:
##change modelfield type
class Mvouchar(models.Model):
cheque_no = models.PositiveIntegerField(validators=[MaxValueValidator(6)], unique=True)
views.py:
def mvouchar(request):
if request.method == "POST":
userdata = User.objects.get(username = request.user)
accountdata = Signs.objects.get(relation_id=userdata.id)
chq_no = request.POST['chequeno']
##verify chq_no
if len(chq_no)==6 and chq_no.isdigit():
if Mvouchar.objects.filter(cheque_no =chq_no):
##raiseError chq_no is already exists and return
##your further code
else:
##raiseError chq_no is wrongly typed
答案 1 :(得分:0)
您应该使用ModelForm来验证发布的数据。由于您已经在cheque_no模型字段上设置了unique=True
,因此表单将为您进行检查。
class MvoucharForm(forms.ModelForm):
class Meta:
fields = ('cheque_no',)
def clean_cheque_no(self):
cheque_no = form.cleaned_data['cheque_no']
if not cheque_no.isdigit():
raise forms.ValidationError('Please enter digits only')
return cheque_no
...
def mvouchar(request):
if request.method == "POST":
form = MvoucharForm(request.POST(
if form.is_valid():
accountdata = Signs.objects.get(relation=request.user)
mini = form.save(commit=False)
mini.related = accountdata
mini.save()
messages.success(request, "Your Cheque is Created")
return HttpResponseRedirect("/mvouchar/")
else:
form = MvoucharForm()
return render(request, 'cheque/mvouchar.html', {'form': form})
不要忘记在模板中使用form
,尤其是{{ form.errors }}
。