I am new in django, and I am creating table in postgresql. I want to perform insert, update and delete operation using django. I want creating followng code.
Models.py
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
def __str__(self):
return ' '.join([
self.name,
self.address,
])
viwes.py
def pramod(request):
if 'pname' in request.GET and request.GET['pname']:
p1 = request.GET['pname']
if 'address' in request.GET and request.GET['address']:
p2 = request.GET['address']
books = Publisher(name=p1,address=p2)
return render(request, 'Publisher.html',{'books': books})
To insert data, using forms, in django, first create a file with the name "forms.py" and create a class with the name of your model/table and add "Form" at the end of the classname as shown below. Open the views.py file and create a function with the name addStudent as given in the path above. # Create your views here.
Code for Adding RecordsGets the first name and last name with the request. POST statement. Adds a new record in the members table. Redirects the user back to the index view.
You need to create an instance of the model class (Publisher in this case), instantiate it with the appropriate values (name and address) and then call save()
, which composes the appropriates SQL INSERT
statement under the hood.
book = Publisher(name=p1, address=p2)
book.save()
I recommend you read the model docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With