如何将外键值传递给Django表单的初始数据

时间:2014-02-20 02:26:06

标签: 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

用户将查看作业对象(/ jobs / <slug> /),然后填写作业的申请表(/ jobs / <slug> / apply /)。

我想将application.job.slug作为应用程序表单上作业字段的初始值传递。我还希望将job对象放在ApplicationCreateView的上下文中(告诉用户他们申请的是什么工作)。

我如何在我看来这样做?

2 个答案:

答案 0 :(得分:0)

您可能对CreateView pagefantastic http://ccbv.co.uk/感兴趣。在此页面中,您可以一目了然地看到可以使用的成员方法和变量。

在您的情况下,您有兴趣覆盖:

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

这根本没有经过测试。你可能需要稍微玩一下。玩得开心。

答案 1 :(得分:0)

我最终在我班上的一个函数中执行了以下操作:

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