我想为一个人添加一个电话号码。
我的models.py
包含:
class Person(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
description = models.CharField(max_length=64)
class Phone(models.Model):
CHOICES = (
('P', 'personal'),
('C', 'company')
)
person = models.ForeignKey(Person)
number = models.CharField(max_length=20, unique=True)
type = models.CharField(max_length=1, choices=CHOICES)
我的views.py
包含:
class PersonCreate(CreateView):
model = Person
fields = ['first_name', 'last_name', 'description']
class PhoneCreate(CreateView):
model = Phone
fields = '__all__'
我的urls.py
包含:
url(r'^(?P<pk>\d+)/$', PersonDetailView.as_view(), name = 'detail'),
url(r'^(?P<pk>\d+)/addPhone$', PhoneCreate.as_view(),
name='phone_create')
现在它的工作原理如下:
我正在输入Person
详细信息视图(网址:'详细信息')。在这里,我有一个Add Address
按钮,可以重定向我查看(url:'phone_create'),但我仍然需要选择人。如何从详细视图中自动创建电话号码?
答案 0 :(得分:3)
我找到了正确答案:
class PhoneCreate(CreateView):
model = Phone
fields = ['number', 'type']
def form_valid(self, form):
form.instance.person_id = self.kwargs.get('pk')
return super(PhoneCreate, self).form_valid(form)