Django:验证模型值的组合是唯一的

时间:2015-10-27 05:50:04

标签: python django

我是Django的新手,我创建了一个人们可以报名换饭的表格。野营旅行的四天中的每一天都有两顿饭,每顿饭有四班。我的模型正在运行,数据正在显示,但经过广泛搜索后我无法弄清楚如何确保人们只能注册无人认领的班次。

提交表单时,数据清理应检查数据库中是否已存在值的组合。我正在使用django 1.8。

models.py

class mealShifts(models.Model):
    Sunday = "Sunday"
    Monday = "Monday"
    Tuesday = "Tuesday"
    Wednesday = "Wednesday"
    Thursday = "Thursday"
    Friday = "Friday"
    Days = (
        (Sunday, "Sunday"),
        (Monday, "Monday"),
        (Tuesday, "Tuesday"),
        (Wednesday, "Wednesday"),
        (Thursday, "Thursday"),
        (Friday, "Friday"),
        )
    Breakfast = "Breakfast"
    Dinner = "Dinner"
    Meals = (
        (Breakfast, "Breakfast"),
        (Dinner, "Dinner"),
        )
    Chef = "Chef"
    Sous_Chef = "Sous-Chef"
    KP ="KP"
    Shifts = (
        (Chef, "Chef"),
        (Sous_Chef, "Sous_Chef"),
        (KP, "KP"),
        )
    assigned = models.BooleanField(default=False)
    day = models.CharField(max_length = 10, choices=Days, default=Sunday)
    meal = models.CharField(max_length = 10, choices=Meals, default=Dinner)
    shift = models.CharField(max_length = 10, choices=Shifts, default=KP)
    camper = models.CharField(max_length = 30, default="none")

forms.py:

class MealForm(ModelForm):

class Meta:
    model = mealShifts
    fields = '__all__'
def clean(self):
    #modelform cleaning happens, but how?

views.py:

def signup(request):
    if request.method == 'POST':
        form = MealForm(request.POST)
        if form.is_valid():
            form.save()
            mealshifts = form.cleaned_data['mealShifts']
            return index(request)
    else:
        form = MealForm()
    return render_to_response('signup.html', RequestContext(request, {'form':form},))

1 个答案:

答案 0 :(得分:0)

试试这个

def clean(self):
    data = self.cleaned_data
    #check whether data is present as your wish 
    #if exists raise Validation error.
    return super(MealForm, self).clean()