Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django createview using primary key

Tags:

forms

django

view

I have a model like this:

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

I have created a form using this model and I want to save it. Here I want the 'engineer' field to to be as the primary key is passed in the url.. like

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

How can I do this. Or I should create a normal form and get its value via get method and assign to the field??

like image 518
gamer Avatar asked Sep 10 '26 01:09

gamer


1 Answers

Since this is a CreateView, you should build on the example in the documentation and add it in form_valid:

def form_valid(self, form):
    form.instance.engineer = Engineer.objects.get(pk=self.kwargs['pk'])
    return super(AppointmentCreate, self).form_valid(form)
like image 200
Daniel Roseman Avatar answered Sep 11 '26 16:09

Daniel Roseman