使用主键的Django createview

时间:2014-11-07 09:24:33

标签: django forms views

我有一个这样的模型:

class Appointment(models.Model):
    user = models.ForeignKey(User)
    engineer = models.ForeignKey(Engineer)
    first_name = models.CharField(max_length=100)
    middle_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100)
    age = models.IntegerField()
def __unicode__(self):
    return self.first_name

我使用此模型创建了一个表单,我想保存它。在这里,我希望“工程师”字段成为主键在URL中传递...如

engineer = Engineer.objects.get(pk=pk) 

我该怎么做?或者我应该创建一个普通的表单并通过get方法获取其值并分配给字段??

1 个答案:

答案 0 :(得分:1)

由于这是一个CreateView,您应该以示例in the documentation为基础并将其添加到form_valid中:

def form_valid(self, form):
    form.instance.engineer = Engineer.objects.get(self.kwargs['pk'])
    return super(AppointmentCreate, self).form_valid(form)