【问题标题】:How to pass ForeignKey value into initial data for Django form如何将 ForeignKey 值传递给 Django 表单的初始数据
【发布时间】:2014-03-20 17:58:17
【问题描述】:

我有一个这样的模型:

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 作为申请表上工作字段的初始值。我还希望将作业对象放在 ApplicationCreateView 的上下文中(告诉用户他们正在申请什么工作)。

在我看来,我将如何做这件事?

【问题讨论】:

    标签: django forms django-generic-views


    【解决方案1】:

    您可能对fantastic http://ccbv.co.uk/ 中的CreateView page 感兴趣,在此页面中,您可以一眼看出可以使用哪些成员方法和变量。

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

    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
    

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

    【讨论】:

      【解决方案2】:

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

      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 不是向上下文添加数据的正确位置。文档说:“尝试发送到正确的方法”。无论如何,如果您对解决方案感到满意,您应该投票给某人并接受答案。
      • 你试过我的建议了吗?你没有回答。 Afaik,它们是重载的正确方法。
      猜你喜欢
      • 2010-12-25
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      相关资源
      最近更新 更多