如何在Django中将数据库外键值与表单外键值进行比较?

时间:2018-09-11 04:59:19

标签: python django django-models django-forms django-views

我有一个 Django 项目,并且遇到了将数据库外键属性与表单外键属性进行比较的问题。我的项目文件如下:

我的Model.py文件:

class Teacher(models.Model):
    Name            = models.CharField(max_length=100)
    Designation     = models.CharField(max_length=100,choices=DESIGNATION)
    Department      = models.CharField(max_length=100,choices=T_Dept)
    Address         = models.CharField(max_length=100)

    def __str__(self):
        return self.Name + ", " + self.Designation + ", " + "("+self.Department +"), "+ self.Address

class Moderation(models.Model):
    year        = models.CharField(max_length=100,choices=T_Year)
    semester    = models.CharField(max_length=100,choices=T_Semester)
    examtype    = models.CharField(max_length=30,choices=EXAMTYPE)
    examyear    = models.CharField(max_length=30,choices=EXAMYEAR)
    NamAdd      = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    position    = models.CharField(max_length=100,choices=POSITON)


    def __str__(self):
        return unicode(self.NamAdd)

我的forms.py文件:

class modaForm(forms.ModelForm):
class Meta:
    model=Moderation
    fields=[
        'year',
        'semester',
        'NamAdd',
        'position','examtype','examyear'
    ]

我的HTML文件:

<form action="{% url 'modIni' %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Year &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; </span>
          {% load widget_tweaks %}
          {{ modForm.year|add_class:"form-control" }}
        </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Semester </span>
          {% load widget_tweaks %}
          {{ modForm.semester|add_class:"form-control" }}
        </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Exam Type</span>
          {% load widget_tweaks %}
          {{ modForm.examtype|add_class:"form-control" }}
        </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Exam Year</span>
          {% load widget_tweaks %}
          {{ modForm.examyear|add_class:"form-control" }}
        </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Name and Address</span>
          {% load widget_tweaks %}
          {{ modForm.NamAdd|add_class:"form-control" }}
        </div> 
    </div>
    <div class="col-sm-12 col-md-4">
      <br>
        <div class="input-group">
          <span class="input-group-addon">Position &nbsp; &nbsp; &nbsp; </span>
          {% load widget_tweaks %}
          {{ modForm.position|add_class:"form-control" }}
        </div>
    </div>

    <div class="col-sm-12 col-md-12"> 
        <br>
        <center>
        <button type="submit" class="btn btn-success btn-lg"><spam class="glyphicon glyphicon-send"> </spam>&nbsp;&nbsp;&nbsp;Submit</button>
        </center>
    </div>
</form>

我的View.py文件:

def modIni(request):
    modForm     = modaForm(request.POST or None,request.FILES or None)
    year        = modForm['year'].value()
    semester    = modForm['semester'].value()
    examtype    = modForm['examtype'].value()
    examyear    = modForm['examyear'].value()
    NamAdd      = modForm['NamAdd'].value()
    position    = modForm['position'].value()

    fMod        = Moderation.objects.all().last
    if modForm.is_valid():
        instance = modForm.save(commit=False)
        flag    =True
        for obj in Moderation.objects.all():
            if obj.year == year and obj.semester == semester and obj.examtype == examtype and obj.examyear == examyear and obj.NamAdd == NamAdd and obj.position == position:
                context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}      
                flag    = False
                break
        if flag:
            instance.save()
            #modForm = modaForm()
            context = {'NamAdd':NamAdd,'fMod':fMod,'modForm':modForm,'msg':"<span style='color:#4BB543;'><h3>successfully accomplished!</h3> Last entry : </span>"}
    else:
        context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:Red;'> <center>Please fill in all the fields</center>Last entry : </span>"}
    return render(request, 'tbs/form/modaration.html',context)

如何在视图文件中比较 obj.NamAdd.Name == NamAdd ?请提供任何提示来帮助我。

基本上,我想将一个唯一的Moderation对象保存到数据库中。还有其他方法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

obj.NamAdd == NamAdd怎么了?
很多。

比较失败的主要问题是NamAdd是一个整数(Teacher对象id),其中obj.NamAdd是模型对象。
因此,就此而言,应为obj.NamAdd.id == NamAdd

请不要这样做。不是那样。 您正在绕过输入验证。

可能是obj.NamAdd == modForm.cleaned_data['NamAdd']

由于您想要唯一的Moderation, 将此添加到模型中:

    class Meta:
    unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))

现在看起来像

class Moderation(models.Model):
year = models.CharField(max_length=100, choices=[])
semester = models.CharField(max_length=100, choices=[])
examtype = models.CharField(max_length=30, choices=[])
examyear = models.CharField(max_length=30, choices=[])
NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE)
position = models.CharField(max_length=100, choices=[])

def __str__(self):
    return unicode(self.NamAdd)

class Meta:
    unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))

(记住 makemigrations migrate
**请注意,我为choices使用了空列表,请根据您的情况进行调整。

现在在视图中,使用它来检查审核是否存在:

moderation_exists = Moderation.objects.filter(year=modForm.cleaned_data['year'], semester=modForm.cleaned_data['semester'],examtype=modForm.cleaned_data['examtype'], examyear=modForm.cleaned_data['examyear'], NamAdd=modForm.cleaned_data['NamAdd'], position=modForm.cleaned_data['position']).exists()


    if moderation_exists:
        context = {'fMod': fMod, 'modForm': modForm,
                   'msg': "<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}
        flag = False