Amit Amit - 9 months ago 73
Python Question

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

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):

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

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',)

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()):
// Here I want to access id of just saved data of Model Publisher and Model Authors
form1.cleaned_data['publisher'] =['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 ` and

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


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

publisher_obj =
author_obj =
book_obj =
book_obj.publisher = publisher_obj

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