简体   繁体   中英

How to compare a database foreign key value with form foreign key value in Django?

I have a Django project and I encountered with a problem of comparing a database foreign key attribute with form foreign key attribute. My project files are below :

My Model.py File:

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)

My forms.py File :

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

My HTML File :

<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>

My View.py File :

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)

How to compare obj.NamAdd.Name == NamAdd in view File? Please help me by providing any hint.

Basically, I want to save a unique Moderation object into database How doing this? Has any alternative way?

Thanks advance.

Whats wrong with obj.NamAdd == NamAdd ?
Many.

The primary issue for the comparison failure is that NamAdd is an integer( Teacher object id) where obj.NamAdd is a model object.
So, on this regard, it should be obj.NamAdd.id == NamAdd

Don't do this please. Not that way. You are bypassing input validation.

It could be obj.NamAdd == modForm.cleaned_data['NamAdd']

Since you want unique Moderation , add this to the model:

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

so that it now looks like

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'))

(remember makemigrations and migrate )
**note I used empty list for choices , adjust for your case.

now in the view, use this for checking moderation existence:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM