我试图创建一个应用程序,我可以为用户保存时间戳。现在,我的表单工作,现在,但我需要确保mpr_id存在于播放器表之前form.save()我怎么能使我的应用程序做到这一点?
如果mpr_id不存在,则显示表单
错误this is my forms.py:
from django import forms
from .models import PlayerRecordTime
class AddTimeForm(forms.ModelForm):
class Meta:
model = PlayerRecordTime
fields = ['mpr_id']
models.py:
class Player(models.Model):
mpr_id = models.CharField(verbose_name="MPR ID", max_length=3, editable=True, unique=True)
full_name = models.CharField(verbose_name="Nombre Completo", max_length=200, editable=True)
phone = models.CharField(verbose_name="Telefono", max_length=10, editable=True)
email = models.EmailField(verbose_name="Email", editable=True)
class Meta:
verbose_name = "Jugador"
verbose_name_plural = "Jugadores"
ordering = ['mpr_id']
def __unicode__(self):
return self.mpr_id
class CheckPoint(models.Model):
id = models.IntegerField(verbose_name="ID", unique=True, editable=False, primary_key=True)
place_name = models.CharField(verbose_name="Nombre Lugar", max_length=60, editable=True, default=True, unique=True)
class Meta:
verbose_name = "CheckPoint"
verbose_name_plural = "CheckPoints"
def __unicode__(self):
return self.place_name
class PlayerRecordTime(models.Model):
mpr_id = models.CharField(verbose_name="MPRID", max_length="3", editable=True)
place_name_id = models.CharField(verbose_name="Check Point ID", max_length=1)
check_in_time = models.TimeField(verbose_name="CheckIn Time", auto_now=True)
class Meta:
verbose_name = "Tiempo"
verbose_name_plural = "Tiempos"
unique_together = ('mpr_id', 'place_name_id')
def __unicode__(self):
return self.mpr_id
views.py
def cp(request, cpid, template_name):
title = "ScavengerRun - CP%s" % cpid
head = "Check Point %s" % cpid
form = AddTimeForm()
if request.method == "POST":
form = AddTimeForm(request.POST)
form.instance.place_name_id = cpid
if form.is_valid():
try:
form.save()
form = AddTimeForm()
except IntegrityError:
form.errors["mpr_id"] = ["Ya existe un record"]
else:
pass
context = {
"title": title,
"head": head,
"form": form,
"cpid": cpid
}
return render(request, template_name, context)
感谢您的帮助。
可以通过get()函数检查对象是否存在
if request.method == "POST":
form = AddTimeForm(request.POST)
form.instance.place_name_id = cpid
if form.is_valid():
try:
plyr = Players.objects.get(mpr_id == form.cleaned_data["mpr_id"])
form.save()
form = AddTimeForm()
except IntegrityError:
form.errors["mpr_id"] = ["Ya existe un record"]
except DoesNotExist:
//does not save
else:
pass