避免Django def post在保存时重复

时间:2014-10-28 12:54:14

标签: django django-views has-many-through m2m

嗨我在保存时遇到重复对象的问题。 我怎么能防止这种情况?

提前致谢。

#models.py
class Candidate(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    birth = models.CharField(max_length=50)
     ...

class Job(models.Model):
    candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
    title = models.CharField(max_length=500)
    ...

class CandidateToJob(models.Model):
    job = models.ForeignKey(Job, related_name='applied_to')
    candidate = models.ForeignKey(Candidate, related_name='from_user')
    STATUS_CHOICES = (
       ('1', 'Not approved'),
       ('2', 'Approved'),
       ('3', 'Hired')
    )
    status = models.CharField(max_length=2, choices=STATUS_CHOICES)

    class Meta:
        unique_together = ("candidate", "job")

这是视图

#views.py
class JobDetails(generic.DetailView):

model = Job
template_name = 'companies/job-detail.html'
form_class = ApplyForm

def get_context_data(self, **kwargs):
    context = super(JobDetails, self).get_context_data(**kwargs)
    context['company_detail'] = Company.objects.all()
    return context

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    messages.success(request, 'Sucesso!')

    if form.is_valid():
        form.save(commit=False)
        #create job
        job = self.get_object(queryset=Job.objects.all())
        #create candidate
        candidate = Candidate.objects.get(pk=request.user)

        #assign to the through table
        candidatetojob = CandidateToJob.objects.create(job=job, candidate=candidate)

        candidatetojob.save()

    return HttpResponseRedirect('/jobs/')

表格

#forms.py
class ApplyForm(ModelForm):

class Meta:
    model = CandidateToJob
    exclude = ['candidate', 'job', 'status']

尽管unique_together,该函数总是保存复制它们的对象。

1 个答案:

答案 0 :(得分:2)

我得到了它的工作。这是我的代码:

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)

    #create job
    job = self.get_object(queryset=Job.objects.all())

    #create candidate
    candidate = Candidate.objects.get(pk=request.user)

    #check if objects exists before save
    if CandidateToJob.objects.filter(job = job, candidate = candidate).exists():

        messages.error(request, 'You have applied already for this position')

        return HttpResponseRedirect(reverse('jobdetail', kwargs={'pk': job.pk}))

    else:

        if form.is_valid():
            form.save(commit=False)

            #assign to the through table
            candidatetojob = CandidateToJob.objects.create(job=job, candidate=candidate, status='0')

            candidatetojob.save()

            messages.success(request, 'Success! Good luck.')

    return HttpResponseRedirect('/jobs/')