我正在尝试做一些门户网站的事情。我希望一个用户可以申请不同的工作,但不是同一个工作。当一个用户申请一个工作时,他不能申请另一个工作。这就是问题,当我运行视图时使用我的逻辑
' integrityerror'
。请帮我。 谢谢
model.py
class JobsApplied(models.Model):
'''
Events
'''
class Meta:
'''
Meta properties for this model
'''
app_label = 'admin'
verbose_name_plural = 'JobsApplied'
job = models.ForeignKey('Job', db_index=True,related_name='appliedjobs')
user = models.OneToOneField(UserProfile)
create_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
'''
Returns object display name
'''
return self.job
views.py
def job_applyview(request):
job_id = request.POST.get('job_id')
## if admin have rights to apply the job please remove "not request.user.is_staff"
# job_id = 11
if request.user and not request.user.is_staff:
job = Job.objects.get(id=job_id)
### please enable below commands after verify
user = UserProfile.objects.get(user__id=request.user.id)
# applied_job = JobsApplied.objects.get(job=job, user=user)
applied_job = JobsApplied.objects.create(job=job, user=user)
applied_job.save(force_insert=True)
message = "you have applied in as " + str(job.job_title)
job_title = Job.objects.get(id=job_id).job_title
industry_id = Job.objects.get(id=job_id)
emp_name = IndustryProfile.objects.get(id=industry_id.industry_id).name
email = IndustryProfile.objects.get(id=industry_id.industry_id).email
b = StudentProfile.objects.get(user_profile=UserProfile.objects.get(user_id=request.user.id))
name = b.name
contact_num = b.mobile_phone
location = b.address_line1
if b.resume:
resume = b.resume.url
else:
resume = ""
body = '''Dear %s, \n The following candidate applied for the job that you have published in Nasscom Jobs Portal.
\n \n Job Title : %s \n name : %s \n Contact_No : %s \n Address : %s \n Resume : %s\n \n Thanks,\n \n Job Portal Support Team''' % (
emp_name, job_title, name, contact_num, location, resume)
email = EmailMessage('Job Applied', body, to=[email])
email.send()
form = JobForm(instance=job)
return render_to_response(
'admin/job.html', {'form': form, 'message': message},
context_instance=RequestContext(request),
)
else:
return redirect('/admin/')
答案 0 :(得分:0)
你说:
一个用户可以申请不同的工作
但您实施为:
class JobsApplied(models.Model):
# [...]
user = models.OneToOneField(UserProfile)
当2个对象强烈链接在一起时,使用OneToOne字段。在这里,你说JobApplied的任何实例都对应一个唯一的用户(这似乎是正确的)但你也说过任何用户都链接到1(并且只有1个)JobApplied实例。因此,在该表单中,用户无法申请2个或更多作业。
这里你想要的是0..n关系:你希望用户申请0或更多的工作。所以你必须在UserProfile模型中声明一个ForeignKey。