Django CreateView with foreign key fields… here is a solution to the problem.
Django CreateView with foreign key fields
I want to add a phone number to a person.
My models.py
contains:
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)
My views.py
contains:
class PersonCreate(CreateView):
model = Person
fields = ['first_name', 'last_name', 'description']
class PhoneCreate(CreateView):
model = Phone
fields = '__all__'
My urls.py
contains:
url(r'^(? P<pk>\d+)/$', PersonDetailView.as_view(), name = 'detail'),
url(r'^(? P<pk>\d+)/addPhone$', PhoneCreate.as_view(),
name='phone_create')
Now it works like this:
I’m going into the Person
Details View (url: “Details”). Here I have an Add Address
button that redirects me to view (url: ‘phone_create’), but I still have to select people. How do I automatically create a contact’s phone number from a detailed view?
Solution
I found the right answer:
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)