Getting table without any records - angularjs

I'm new to Django REST and Angular JS, so I'm trying to understand the concepts behind them (and the integration between the two).
I'm making a REST API that should print a list of Classrooms and Students, and that's my work so far
models.py
class Classroom(models.Model):
school = models.ForeignKey(School, related_name='schools')
academic_year = models.CharField(max_length=9)
classroom = models.CharField(max_length=100)
floor = models.IntegerField(default=0)
class Meta:
unique_together = (('school', 'classroom', 'academic_year'),)
class Student(models.Model):
classroom = models.ForeignKey(Classroom, related_name='students')
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=60)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
birthday = models.DateField()
serializers.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('classroom', 'first_name', 'last_name', 'gender', 'birthday')
class ClassroomSerializer(serializers.ModelSerializer):
students = StudentSerializer(many=True)
class Meta:
model = Classroom
depth = 1
fields = ('school', 'academic_year', 'classroom', 'floor', 'students')
views.py
def index(request):
return render_to_response('school_app/base.html', RequestContext(request))
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
class ClassroomViewSet(viewsets.ModelViewSet):
queryset = Classroom.objects.all()
serializer_class = ClassroomSerializer
and urls.py
router = routers.SimpleRouter()
router.register(r'classrooms', ClassroomViewSet)
router.register(r'students', StudentViewSet)
urlpatterns = router.urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/classrooms/$', school_app.views.ClassroomViewSet.as_view({'get': 'list'}), name='classroom-list'),
url(r'^api/students/$', school_app.views.StudentViewSet.as_view({'get': 'list'}), name='student-list'),
url(r'^', 'school_app.views.index', name='index-page'),
]
And here's the Angular "part" of the project, with:
base.html
<body ng-app="userListApp" ng-controller="UsersController">
<table class="table table-striped">
<thead>
<tr>
<th>Classroom</th>
<th>School</th>
<th>Academic year</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
</tbody>
</table>
</body>
And app.js
var userListApp = angular.module('userListApp', ['ngResource']);
userListApp.controller('UsersController', function ($scope, Classroom) {
Classroom.query().then(function (result) {
console.log(result);
$scope.classrooms = result.classrooms;
}, function (result) {
alert("Error: No data returned");
});
});
userListApp.factory('Classroom', [
'$resource', function($resource) {
return $resource('/api/classrooms/:id', {
classrooms: '#classrooms'
});
}
]);
I think there's something wrong in the script, but I can't realize what part I'm missing. I'm not sure about the routing either.
I'm getting only the table without the records. Any thoughts?

Related

AttributeError: 'CharField' object has no attribute 'use_required_attribute'

I try to add a form-control class to an input field of a model-based form in Django, but I get this error message:
AttributeError: 'CharField' object has no attribute 'use_required_attribute'.
How do I fix this?
class in views.py:
class TweetCreate(LoginRequiredMixin, CreateView):
model = TweetSearch
fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country']
def get_form(self):
form = super().get_form()
form.fields['search_term'].widget = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'}))
form.fields['query_type'].widget = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'}))
form.fields['start_date'].widget = DateTimePickerInput(attrs={'class': 'form-control'})
form.fields['end_date'].widget = DateTimePickerInput(attrs={'class': 'form-control'})
form.fields['language'].widget = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})),
form.fields['country'].widget = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})),
return form
class in models.py:
class TweetSearch(models.Model):
from datetime import datetime, timedelta
search_term = models.CharField(max_length=200, default='blue bird')
QUERY_CHOICES = (
('t', 'in tweet'),
('h', 'in hashtag'),
('u', 'username'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True)
query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t')
start_default = datetime.now() - timedelta(days=30)
start_date = models.DateTimeField(default=start_default)
end_date = models.DateTimeField(default=datetime.now)
language = models.CharField(max_length=200, default='English')
country = models.CharField(max_length=200, default='USA')
searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
def get_absolute_url(self):
return reverse('tweet_detail', kwargs={'pk': self.pk})
def __str__(self):
return f"Tweets with the word {self.search_term} from {self.start_date} till {self.end_date} written in " \
f"{self.language} in {self.country}."
HTML:
<div class="container" id="searchcontainer" style="text-align: center">
<form action="" method="POST">
{% csrf_token %}
{{form.search_term}}
{{form.query_type}}
{{form.start_date}}
{{form.end_date}}
{{form.language}}
{{form.country}}
<input class="btn btn-primary" type="submit">
</form>
</div>
You are confusing form field with widgets. You should assign a widget like TextInput, not a form field like CharField, like:
class TweetCreateView(LoginRequiredMixin, CreateView):
model = TweetSearch
fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country']
def get_form(self):
form = super().get_form()
form.fields['search_term'].widget=forms.TextInput(attrs={'class': 'form-control'})
form.fields['query_type'].widget=forms.TextInput(attrs={'class': 'form-control'})
form.fields['start_date'].widget=DateTimePickerInput(attrs={'class': 'form-control'})
form.fields['end_date'].widget=DateTimePickerInput(attrs={'class': 'form-control'})
form.fields['language'].widget=forms.TextInput(attrs={'class': 'form-control'})
form.fields['country'].widget=forms.TextInput(attrs={'class': 'form-control'})
return form
It however here might be better to just plug in a ModelForm, so:
class TweetForm(forms.ModelForm):
class Meta:
model = TweetSearch
fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country']
widgets = {
'search_term': forms.TextInput(attrs={'class': 'form-control'}),
'query_type': forms.TextInput(attrs={'class': 'form-control'}),
'start_date': DateTimePickerInput(attrs={'class': 'form-control'}),
'end_date': DateTimePickerInput(attrs={'class': 'form-control'}),
'language': forms.TextInput(attrs={'class': 'form-control'}),
'country': forms.TextInput(attrs={'class': 'form-control'}),
}
and plug this into the TweetCreateView:
class TweetCreateView(LoginRequiredMixin, CreateView):
model = TweetSearch
form_class = TweetForm
if you however only want to change the class, you can simplify this with:
class FormControlForm(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class TweetForm(FormControlForm, forms.ModelForm):
class Meta:
model = TweetSearch
fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country']

Error when Django form try tu update data

I am very new in django.
Situation is like this
I have a model
class Slotmodels (models.Model):
modelid = models.AutoField(primary_key=True)
model_desc = models.TextField()
categoryid = models.ForeignKey(categories, on_delete=models.CASCADE)
shopid = models.ForeignKey(shops, on_delete=models.CASCADE)
brandid = models.ForeignKey(brands, on_delete=models.CASCADE)
reference = models.CharField(max_length=50,null=True)
history = models.TextField(null=True)
year = models.IntegerField(null=True)
purchase_price = models.FloatField(default=0)
actual_price = models.FloatField(default=0)
limited_edition = models.BooleanField(null=False,default=False)
color = models.CharField(max_length=50,null=True)
number = models.IntegerField(null=True)
livery = models.CharField(max_length=50,null=True)
sponsor = models.CharField(max_length=50,null=True)
scale = models.CharField(max_length=10,null=True)
engine = models.CharField(max_length=20,null=True)
eng_position = models.CharField(max_length=20,null=True)
crown = models.IntegerField(null=True)
pinion = models.IntegerField(null=True)
crown_bnd = models.CharField(max_length=20,null=True)
pinion_bnd = models.CharField(max_length=20,null=True)
active = models.BooleanField(default=True)
chasis = models.CharField(max_length=20,null=True)
rear_axis = models.CharField(max_length=30,null=True)
front_axis = models.CharField(max_length=30,null=True)
front_tire_diam = models.IntegerField(null=True)
rear_tire_diam = models.IntegerField(null=True)
front_tire_width = models.IntegerField(null=True)
rear_tire_width = models.IntegerField(null=True)
collection_desc = models.CharField(max_length=30,null=True)
bench_desc = models.CharField(max_length=30,null=True)
Total_weight = models.IntegerField(null=True)
def __str__(self):
return self.modelid, self.model_desc
With a form based on that model:
class FormAltaSlotModel(ModelForm):
class Meta:
model = Slotmodels
fields = ['modelid','model_desc','categoryid','shopid','brandid','reference','history','year','purchase_price',
'actual_price','limited_edition','color','number','livery','sponsor','scale','engine','eng_position',
'crown','pinion','crown_bnd','pinion_bnd','active','chasis','rear_axis','front_axis','front_tire_diam',
'rear_tire_diam','front_tire_width','rear_tire_width','collection_desc','bench_desc','Total_weight']
help_texts = {
}
widgets = {
'history': Textarea(attrs={'cols': 30, 'rows': 2}),
'model_desc': Textarea(attrs={'cols': 30, 'rows': 2})
}
When I instance the form to create a record, is everything ok!. It is important to say that I have three foreignkey fields so when I render the form , the list values of the model referenced appear in the screen. And, the values are recorded properly (in the related Id fields).
The point is when I tried to update a record previously recorded. In the screen appear the descriptions and the list is not appearing, then the values that are passed to the form are descriptions instead of the codes, so the message "Select a valid choice. That choice is not one of the available choices.", appear for the three foreignkey fields that are 'categoryid','shopid','brandid'.
I have tried to fix it, but with no success. Thanks in advance!
Here I tried to do full CRUD with your MODEL & MODELFORM
view.py
def InsertData(request):
my_data = Slotmodels.objects.all() # Show data of Student Table
if request.method == 'POST':
form = FormAltaSlotModel(request.POST,request.FILES)
if form.is_valid():
form.save()
messages.success(request,'Student Successfully Inserted')
return redirect('/')
else:
form = FormAltaSlotModel()
context= {'form':form,'my_data':my_data}
return render(request,'home.html',context)
def UpdateData(request,modelid):
my_data = Slotmodels.objects.all() # Show data of Student Table
set_student = Slotmodels.objects.get(modelid=modelid)
if request.method == 'POST':
form = FormAltaSlotModel(request.POST,request.FILES,instance=set_student)
if form.is_valid():
form.save()
messages.success(request,'Student Successfully Updated')
return redirect('/')
else:
form = FormAltaSlotModel(instance=set_student)
context= {'form':form,'my_data':my_data}
return render(request,'home.html',context)
def DeleteData(request,modelid):
set_student = Slotmodels.objects.get(modelid=modelid)
set_student.delete()
messages.success(request,'Student Successfully Deleted')
return redirect('/')
urls.py
urlpatterns = [
path('', InsertData,name='insert_data'),
path('up/<int:modelid>/', UpdateData,name='update_data'),
path('del//<int:modelid>/', DeleteData,name='delete_data'),
]
HTML Code
<div class="container my-5">
<div class="row">
<div class="col-12">
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add</button>
</form>
</div>
<div class="col-12">
<table class="table">
<thead>
<tr>
<th scope="col">No.</th>
<th scope="col">Categories</th>
<th scope="col">Shops</th>
<th scope="col">Brands</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for i in my_data %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.categoryid}}</td>
<td>{{i.shopid}}</td>
<td>{{i.brandid}}</td>
<td>
Update
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Output

How do you create a REST API (save and load data) with Python and consume it with AngularJS?

<div >
<table class="table">
<thead>
<th>Name</th>
<th>Roll</th>
<th>Town</th>
<th>Class</th>
</thead>
<tr ng-repeat="c in contacts.data | filter:query"><button ng-hide="editMode" ng-click="modifyDetails()">Edit</button><button ng-show="editMode" ng-click="modifyDetails()">Done</button>
<td><span ng-model="studName" ng-hide="editMode">{{ c.Name }}</span><input ng-show="editMode" ng-model="c.Name"> </td>
<td><span ng-model="studRoll" ng-hide="editMode">{{ c.Roll }}</span><input ng-show="editMode" ng-model="c.Roll"> </td>
<td><span ng-model="studTown" ng-hide="editMode">{{ c.Town }}</span><input ng-show="editMode" ng-model="c.Town"></td>
<td><span ng-model="studClass" ng-hide="editMode">{{ c.Class }}</span><input ng-show="editMode" ng-model="c.Class"></td>
</tr>
</table>
var module = angular.module("djangoApp", [])
module.controller("siaMyCtrl", siaMyCtrl)
function siaMyCtrl($scope, $http) {
$scope.editMode = false
$http.post('http://10.2.10.55:5000/')
.then(successCallback, errorCallback)
function successCallback(response) {
$scope.contacts = response;
}
function errorCallback(error) {
}
$scope.modifyDetails = function () {
$scope.editMode = ! $scope.editMode
}
$scope.addDetails = function () {
}}
after I save it changes the value but when I refresh It again changes to the earlier value.All these data I am getting from localhost.I want to update information on server(localhost) how can I do that
Please help me I am a beginner
from flask import Flask, jsonify, render_template, request
import MySQLdb, json
app = Flask(__name__)
#app.route('/',methods=['GET', 'POST'])
def process():
name1=request.form.get('name')
roll1=request.form.get('num')
town1=request.form.get('town')
class1=request.form.get('cls')
db = MySQLdb.connect("localhost","root","test123","test" )
with db:
cursor = db.cursor()
sql = "SELECT * FROM geninfo1"
cursor.execute(sql)
rows = cursor.fetchall()
x=[]
for i, item in enumerate(rows):
x.append({
'id':rows[i][0],
'Name':rows[i][1],
'Class':rows[i][3],
'Town':rows[i][4],
'Roll':rows[i][2]
})
return jsonify(x)
# return render_template('index.html', Name=name1)
db.close()
if __name__=='__main__':
app.run(host="10.2.10.55", port=5000, debug=True)
Update decided to familiarize myself with Flask and give a proper full answer here:
Database Setup (SQL run in terminal)
# mysql -u root -p
CREATE DATABASE pythontesting;
USE DATABASE pythontesting;
CREATE TABLE students (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255),
class varchar(255),
town varchar(255),
roll varchar(255),
PRIMARY KEY (id)
);
Python code hello.py
# Prerequisites: Python 2.7, Flask 0.12.2, Python-Mysql connector
# sudo pip install Flask
# sudo apt install python-mysqldb
# sudo pip install -U flask-cors
# Run with:
# FLASK_APP=hello.py flask run
# http://flask.pocoo.org/docs/0.12/api/#flask.request
from flask import Flask,request
# https://pypi.python.org/pypi/Flask-Cors
from flask_cors import CORS, cross_origin
# https://pythonspot.com/mysql-with-python/
import MySQLdb
import json
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}}, methods=['GET', 'POST', 'DELETE', 'PUT'])
#app.route("/api/v1/students",methods=['GET'])
def getStudents():
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
row_headers=[x[0] for x in cur.description] #this will extract row headers
json_data=[]
for result in rows:
json_data.append(dict(zip(row_headers,result)))
return json.dumps(json_data)
#app.route("/api/v1/students",methods=['POST'])
def createStudent():
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# https://stackoverflow.com/questions/7929364/python-best-practice-and-securest-to-connect-to-mysql-and-execute-queries
# Select data from table using SQL query.
cur.execute("INSERT INTO students (name, class, town, roll) VALUES (%s, %s, %s, %s)", (requestData["name"],requestData["class"],requestData["town"],requestData["roll"]))
db.commit()
return "OK"
#app.route("/api/v1/students",methods=['PUT'])
def updateStudents():
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# https://stackoverflow.com/questions/7929364/python-best-practice-and-securest-to-connect-to-mysql-and-execute-queries
# Select data from table using SQL query.
cur.execute("UPDATE students SET name=%s, class=%s, town=%s, roll=%s WHERE id=%s", (requestData["name"],requestData["class"],requestData["town"],requestData["roll"],requestData["id"]))
db.commit()
return "OK"
#app.route("/api/v1/students/<int:student_id>",methods=['DELETE'])
def deleteStudent(student_id):
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
cur.execute("DELETE FROM students WHERE id=%s", (student_id,))
db.commit()
return "OK"
HTML for front end index.html
<!DOCTYPE html>
<html ng-app="djangoApp">
<head>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
<script type="text/javascript" src="mainApp.js"></script>
<title></title>
</head>
<body ng-controller="siaMyCtrl as smc">
<button ng-hide="c.editMode" ng-click="smc.model.showAddRow = true">Add</button>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Roll</th>
<th>Town</th>
<th>Class</th>
<th></th>
</tr>
</thead>
<!-- Not valid HTML to have a form here but works -->
<form ng-submit="smc.create(smc.model.newStudent)">
<tr ng-show="smc.model.showAddRow">
<td><input ng-model="smc.model.newStudent.name"> </td>
<td><input ng-model="smc.model.newStudent.roll"> </td>
<td><input ng-model="smc.model.newStudent.town"></td>
<td><input ng-model="smc.model.newStudent.class"></td>
<td><button>Save</button></td>
</tr>
</form>
<tr
ng-repeat="c in smc.StudentsService.loadedStudents | filter:query">
<td><span ng-model="studName" ng-hide="c.editMode">{{ c.name }}</span><input ng-show="c.editMode" ng-model="c.name"> </td>
<td><span ng-model="studRoll" ng-hide="c.editMode">{{ c.roll }}</span><input ng-show="c.editMode" ng-model="c.roll"> </td>
<td><span ng-model="studTown" ng-hide="c.editMode">{{ c.town }}</span><input ng-show="c.editMode" ng-model="c.town"></td>
<td><span ng-model="studClass" ng-hide="c.editMode">{{ c.class }}</span><input ng-show="c.editMode" ng-model="c.class"></td>
<td>
<button ng-hide="c.editMode" ng-click="smc.edit(c)">Edit</button>
<button ng-hide="c.editMode" ng-click="smc.StudentsService.deleteStudent(c)">Delete</button>
<button ng-show="c.editMode" ng-click="smc.update(c)">Save</button>
<button ng-show="c.editMode" ng-click="smc.cancel(c)">Cancel</button>
</td>
</tr>
</table>
</body>
</html>
Script for angular execution mainApp.js
(function(){
var module = angular.module("djangoApp", []);
module.controller("siaMyCtrl", siaMyCtrl)
function siaMyCtrl(StudentsService) {
var ctrl = this;
ctrl.StudentsService = StudentsService;
ctrl.model = {
};
ctrl.modifyDetails = function (c) {
c.editMode = ! c.editMode
}
ctrl.update = function(student){
StudentsService.updateStudent(student)
.then(function(){
ctrl.model.showAddRow = false;
});
}
ctrl.edit = function(student){
student.editMode = true;
student.originalStudent = angular.copy(student);
}
ctrl.cancel = function(student){
angular.copy(student.originalStudent, student);
student.editMode = false;
student.originalStudent = null;
}
ctrl.create = function (student) {
StudentsService.createStudent(student)
.then(function(){
ctrl.model.showAddRow = false;
});
}
}
module.value('APIBase', 'http://127.0.0.1:5000/api/v1/');
module.service('StudentsService', function($http, APIBase){
var studentsURL = APIBase+'students';
var studentsService = {
loadedStudents: []
};
studentsService.readStudents = function(){
function successCallback(response) {
studentsService.loadedStudents = response.data;
}
return $http.get(studentsURL)
.then(successCallback, console.error)
}
studentsService.createStudent = function(student){
return $http.post(studentsURL, student).then(function(){
studentsService.readStudents();
})
}
//Notice same as create but uses PUT
studentsService.updateStudent = function(student){
return $http.put(studentsURL, student).then(function(){
studentsService.readStudents();
})
}
// Notice same as create but uses DELETE...
// you can also use a $resource to wrap this up but it uses $http under
// the hood so good to see how this works too, $http wraps the browsers
// regular XHR object and triggers angular view updates when data comes back
studentsService.deleteStudent = function(student){
return $http.delete(studentsURL+'/'+student.id).then(function(){
studentsService.readStudents();
})
}
studentsService.readStudents(); // Initialize the service with data
return studentsService;
})
})();
Wrote this up into a blog entry here so I can add details maybe not directly related to the original question:
https://www.intellectual-tech.com/blog/full-stack-python-angular-rest-api

Angulary and Django REST

How can I filtred my queryset?
Simply example:
.controller('TViewController', ["$scope", "$stateParams", "Ad", "Banner", function($scope, $stateParams, Ad, Banner) {
$scope.ad = Ad.get({ ad_id: $stateParams.ad_id });
$scope.banners = Banner.query();
}])
And
class CBanner(models.Model):
image = models.ImageField(upload_to="img")
ad = models.ForeignKey(CAds, null=True, blank=True)
class CADs(models.Model):
name = models.CharField(max_length=80, null=True, blank=True)
They both have viewset, serializer and routing register
class AdsViewer(viewsets.ModelViewSet):
queryset = CADs.objects.all()
serializer_class = AdsSerializer
etc...
How can I filtered this: $scope.banners = Banner.query(); to get only banners with ad(foreignKey) = ad_id?
You need to add a query parameter to your url, such as:
http://example.com/api/ads/?ad_fk=5
In AdsViewer:
def get_queryset(self):
"""
This view should return a list of all the ads filtered with proper foreign key
"""
ad_fk = self.request.query_params.get('ad_fk', None)
return CADs.objects.filter(ad=ad_fk)
For more info see the doc

edit and update the row in database using django

models.py
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age = models.IntegerField()
def __unicode__(self):
return "{0} {1} {2} {3} {4}".format(
self, self.first_name, self.last_name, self.email, self.age)
class Book(models.Model):
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
def __unicode__(self):
return "{0} {1} {2}".format(
self.pk, self.book_name, self.publisher_name)
forms.py
class AuthorForm(ModelForm):
class Meta:
model = Author
BookFormset = inlineformset_factory(Author, Book,
fields=('book_name', 'publisher_name'), extra=1,
can_delete=False)
urls.py is
admin.autodiscover()
urlpatterns = patterns('',
url('^$', index),
url('^index/$', index),
url('^addbook/$', addbook),
url('^book_detail/$', book_detail, 'book_summary'),
url('^editbook/(?P<book_id>\d+)/$', editbook) ,
url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,
url(r'^admin/', include(admin.site.urls)),
)
I need to perform edit and update the row in database,i did it by using single table.But using two table have some confusion how to take 2nd table using that particular id.I am using forms in this.Can you help me in this to write codes in views.py.Example for doing the same using two table is no where i seen.
Thanks
def update_book(request, book_id):
author = get_object_or_404(Author, pk=author_id)
form = AuthorForm(instance=author)
book_formset = BookFormset(instance=author)
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
author = form.save(commit=False)
book_formset = BookFormset(request.POST, instance=author)
if book_formset.is_valid():
author.save()
book_formset.save()
return redirect('/index/')
return render_to_response('updatebook.html',{
'form': form, 'formset': book_formset
},context_instance=RequestContext(request))
<div align="center">
<tr>
<form method="POST">
{% csrf_token %}
<h5>Author:</h5>
{{ form.as_p }}
<h5>Book:</h5>
{{ formset.as_p }}
<input type="submit" value="submit">
</form>
</tr>
</div>

Resources