Django在form.save()之前从db获取值

时间:2015-09-03 22:05:34

标签: python django django-queryset

我正在尝试创建一个可以为用户保存时间戳的应用程序。现在,我的表单现在正常工作,但我需要确保mpr_id存在于Player表之前的form.ave()我怎么能让我的应用程序这样做?

如果播放器中的播放器显示错误中不存在mpr_id

这是我的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)

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以通过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