我是 Django 的新手,我正在建立一个工作委员会。但我不明白如何创建一个表单来获取 M2M 的相关字段。
这是我的代码:
#views.py
class JobDetails(generic.DetailView):
model = Job
template_name = 'companies/job-detail.html'
def get_context_data(self, **kwargs):
context = super(JobDetails, self).get_context_data(**kwargs)
context['company_detail'] = Company.objects.all()
return context
def apply(request):
if request.method == "POST":
form = ApplyForm(request.POST)
if form.is_valid():
form.save(commit=False)
#create job
job = Job.objects.all.get(pk=pk)
#create candidate
candidate = User.objects.all.get(pk=pk)
#assign to the through table
candidatetojob = CandidateToJob.objects.create(job=job, candidate=candidate)
form.save()
candidatetojob.save()
return HttpResponseRedirect('/jobs/')
else:
form = ApplyForm()
return render_to_response(
"companies/form-candtojob.html",
{'form': form}
)
#forms.py
class ApplyForm(ModelForm):
class Meta:
model = CandidateToJob
exclude = ['candidate', 'job', 'status']
#models.py
class Job(models.Model):
company = models.ForeignKey(Company)
candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
title = models.CharField(max_length=500)
pub_date = models.DateField(auto_now_add=True)
...
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('jobdetail', kwargs={'pk': self.pk})
class Candidate(models.Model):
user = models.OneToOneField(User, primary_key=True)
photo = models.ImageField(upload_to='candidateprofile/%Y/%m/%d')
...
def __unicode__(self):
return self.user.username
class CandidateToJob(models.Model):
job = models.ForeignKey(Job, related_name='applied_to')
candidate = models.ForeignKey(Candidate, related_name='from_user')
STATUS_CHOICES = (
('0', 'New'),
('1', 'Not approved'),
('2', 'Approved'),
('3', 'Hired')
)
status = models.CharField(max_length=2, choices=STATUS_CHOICES)
def __unicode__(self):
return self.job.candidate.user.username
但是在我的 template.html 中,正在登录的用户候选人申请工作(通过提交表单按钮)我收到 405 错误。我只能在管理员中执行此操作。
对我做错了什么的一些想法?提前致谢。