如何将ForeignKey值传递到Django表单的初始数据中
我有一个这样的模型:如何将ForeignKey值传递到Django表单的初始数据中,django,forms,django-generic-views,Django,Forms,Django Generic Views,我有一个这样的模型: class Job(models.Model): slug = models.SlugField() class Application(models.Model): job = models.ForeignKey(Job) class ApplicationCreateView(CreateView): model = Application 还有这样一种观点: class Job(models.Model): slug = mode
class Job(models.Model):
slug = models.SlugField()
class Application(models.Model):
job = models.ForeignKey(Job)
class ApplicationCreateView(CreateView):
model = Application
还有这样一种观点:
class Job(models.Model):
slug = models.SlugField()
class Application(models.Model):
job = models.ForeignKey(Job)
class ApplicationCreateView(CreateView):
model = Application
用户将查看作业对象/jobs/,然后填写作业申请表/jobs//apply/
我希望将application.job.slug作为申请表上job字段的初始值。我还希望将job对象放在ApplicationCreateView的上下文中,告诉用户他们正在申请什么工作
在我看来,我该怎么做呢?您可能对本页的感兴趣,您可以一目了然地看到您可以使用哪些成员方法和变量
在您的情况下,您将有兴趣覆盖:
def get_initial(self):
# Call parent, add your slug, return data
initial_data = super(ApplicationCreateView, self).get_initial()
initial_data['slug'] = ... # Not sure about the syntax, print and test
return initial_data
def get_context_data(self, **kwargs):
# Call parent, add your job object to context, return context
context = super(ApplicationCreateView, self).get_context_data(**kwargs)
context['job'] = ...
return context
这根本没有经过测试。你可能需要玩一下。玩得开心。我在课堂上的一个函数中完成了以下操作:
class ApplicationCreateView(CreateView):
model = Application
form_class = ApplicationForm
success_url = 'submitted/'
def dispatch(self, *args, **kwargs):
self.job = get_object_or_404(Job, slug=kwargs['slug'])
return super(ApplicationCreateView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
#Get associated job and save
self.object = form.save(commit=False)
self.object.job = self.job
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def get_context_data(self, *args, **kwargs):
context_data = super(ApplicationCreateView, self).get_context_data(*args, **kwargs)
context_data.update({'job': self.job})
return context_data
很高兴知道您让它工作,但dispatch不是向上下文添加数据的正确位置。文档中说:尝试使用正确的方法进行调度。无论如何,如果你对解决方案感到满意,你应该投票给某人并接受答案。你试过我的建议了吗?你没有回答。好吧,它们是过载的正确方法。