Amit Amit - 6 months ago 47
Python Question

how to access auto increment id of any model using form in django?

models.py

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)

def __unicode__(self):
return self.name


class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)


class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, blank=True)
publisher = models.ForeignKey(Publisher, blank=True, null=True)

def __unicode__(self):
return self.title


forms.py

class Books(forms.ModelForm):

class Meta:
model = Book
fields = ('title', 'authors', 'publisher',)


class Authors(forms.ModelForm):
class Meta:
model = Author
fields = ('first_name', 'last_name', 'email',)


class Publishers(forms.ModelForm):
class Meta:
model = Publisher
fields = ("id","name", 'address', 'city', 'state_province', 'country',)


views.py

def demo(request):
form1 = Books(request.POST)
form2 = Authors(request.POST)
form3 = Publishers(request.POST)
if (form1.is_valid() & form2.is_valid() & form3.is_valid()):
form3.save()
form2.save()
// Here I want to access id of just saved data of Model Publisher and Model Authors
form1.cleaned_data['publisher'] = form3.data['id']

return render(request, 'files/demo.html', {'form1': form1, 'form2': form2, 'form3': form3})


In Above code I want to save all data of all models in single view But errro is that Book model has ForenignKey relation with Publisher and Publisher doens't not have any unique data to identify the ID of just saved data. So My real question is that how can I access the Publisher and Author ID that data is saved using `


form3.save() and form2.save()


`I'm very confused to save multiple model data with same time with handle forenignkey relation between them.

Answer

save() returns the object, so you just need to do

publisher_obj = form3.save()
author_obj = form2.save()
book_obj = form1.save(commit=False)
book_obj.publisher = publisher_obj
book_obj.save()
book_obj.authors.add(author_obj)

and remove the 'id' from the form. You don't need it.

Comments