Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django admin根据模型中的字段验证内联表单集_Python_Django_Admin_Inline Formset - Fatal编程技术网

Python Django admin根据模型中的字段验证内联表单集

Python Django admin根据模型中的字段验证内联表单集,python,django,admin,inline-formset,Python,Django,Admin,Inline Formset,我目前正在学习python和django,我被卡住了。我有以下型号: class State(models.Model): name = models.CharField(max_length=30) population = models.IntegerField() class Candidate(models.Model): name = models.CharField(max_length=30) # Represents the election resu

我目前正在学习python和django,我被卡住了。我有以下型号:

class State(models.Model):
    name = models.CharField(max_length=30)
    population = models.IntegerField()

class Candidate(models.Model):
    name = models.CharField(max_length=30)

# Represents the election result of a particular Candidate in a particular State
class Result(models.Model):
    candidate = models.ForeignKey(Candidate)
    state = models.ForeignKey(State)
    num_votes = models.IntegerField()
My admin.py包含以下内容:

class CandidateAdmin(admin.ModelAdmin):
    fields = ['name']

class ResultInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        # Check that total number of votes doesn't exceed population
        sum = 0
        for form in self.forms:
            sum += form.cleaned_data.get('num_votes')
            # This is the part where I'm stuck
            if (sum > value_of_population_field_from_State_form):
                raise forms.ValidationError("Total number of votes cannot exceed state population")

class ResultInline(admin.TabularInline):
    model = Result
    extra = 0
    formset = ResultInlineFormset

class StateAdmin(admin.ModelAdmin):
    fields = ['name', 'population']
    inlines = [ResultInline]

admin.site.register(Candidate, CandidateAdmin)
admin.site.register(State, StateAdmin)
正如你所看到的,我需要以某种方式检查总票数(所有候选人的票数之和)是否高于该州的人口。要做到这一点,我想我需要以状态形式访问人口字段的值,但我不知道如何做,或者是否可能?

可能的重复项