models.py
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
class Meta:
db_table=u'Author'
def __unicode__(self):
return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
class Meta:
db_table = u'Book'
def __unicode__(self):
return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)
can you please tell me how to write a forms.py and views.py for this model to display the data from database.
my forms.py is
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['author_id','first_name','last_name','email','age']
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields=['book_id','book_name','publisher_name','author_id']
So i writen the forms.py in this way it is writen for models field.So please tell me that the form what i given is correct,if not please tell me how to write a forms.py and views.py for displaying the data from database from two tables.
my views.py is
def index(request):
book = forms.ModelMultipleChoiceField(queryset=Book.objects.all())
return render_to_response('index.html', locals(),context_instance=RequestContext(request))
I am not able to show all the data from database.please help me with this.If any problem with my views.py content guide me how to write views.py
my index.html is
<html>
<head>
<title>
</title>
</head>
<body>
<div align="center">
<table border="0" cellpadding='8' cellspacing='10'>
<tr>
<td align="right" colspan="10">Add Book</td>
</tr>
<tr>
<th>Book Id</>
<th>Book name</th>
<th>Publication name</th>
<th>Author Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>E Mail</th>
<th>Age</th>
<th></th>
<th></th>
</tr>
{% for book in books %}
<tr>
<td>{{ book.book_id }}</td>
<td>{{ book.book_name }}</td>
<td>{{ book.publisher_name }}</td>
<td>{{ book.author_id }}</td>
<td>{{ book.author.first_name }}</td>
<td>{{ book.author.last_name }}</td>
<td>{{ book.author.email }}</td>
<td>{{ book.author.age }}</td>
<td>Edit</td>
<td>Delete</td>
{% endfor %}
</table>
</div>
</body>
</html>
Thanks,
try this in your views.py:
from models import Book
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
books = Book.objects.all()
return render_to_response('index.html',
locals(),
context_instance=RequestContext(request))
Your models and forms look correct off hand. Please see part 4 of the Django tutorial for help writing views to connect them.
Related
In the below table I have been using data to store in a array format
which should be stored in a single row in database table.
<table class="table">
<tr>
<th>transaction_number</th>
<th>date</th>
<th>item_number</th>
<th>desc</th>
<th>variant_code</th>
<th>quantity</th>
<th>cost</th>
</tr>
#php ($current_transaction_number = null)
#foreach ($items as $item)
#if ($loop->index > 0 && $current_transaction_number != $item->transaction_number)
#include ('subtotal', compact('items', 'current_transaction_number'))
#endif
<tr>
#if ($current_transaction_number == $item->transaction_number)
<td colspan="2"></td>
#else
#php ($current_transaction_number = $item->transaction_number)
<td>{{ $item->transaction_number }}</td>
<td>{{ $item->date }}</td>
#endif
<td>{{ $item->item_number }}</td>
<td>{{ $item->desc }}</td>
<td>{{ $item->variant_code }}</td>
<td>{{ $item->quantity }}</td>
<td>{{ $item->cost }}</td>
</tr>
#if ($loop->last)
#include ('subtotal', compact('items', 'current_transaction_number'))
#include ('total', compact('items'))
#endif
#endforeach
</table>
I'm not sure that I understand the question fully, and I don't see the reason for storing all of that data in one column, but you can definitely do that using MySQL JSON field.
In your migration use $table->json('name_of_the_column')->nullable(); to create this column.
In your model add:
protected $casts = [
'name_of_the_column' => 'array'
];
Then you will be able to retrieve stuff like Model::where('name_of_the_column->name_of_the_property', 'Key')->get();
For more details, you can see this link: https://www.qcode.in/use-mysql-json-field-in-laravel/
I hope this helps.
I'm currently making a website for my parent's bakery. And I want to make a custom admin page for them so they can update their products with ease.
All I have so far is a ListView that displays all the products.
This is my model:
class menulist(models.Model):
name = models.CharField(max_length=120)
description = models.CharField(max_length=500)
price = models.DecimalField(decimal_places=1, max_digits=10, default=100.00)
category_choices = (
('breads', 'Breads'),
('cakes', 'Cakes'),
('hotfood', 'Hot Food'),
('porkrolls', 'Pork Rolls'),
('drinks', 'Drinks'),
('MISC', 'Misc'),
)
category = models.CharField(max_length=50, choices=category_choices, default='MISC',)
dateadded = models.DateField(auto_now_add=True)
dateupdated = models.DateField(auto_now=True)
img = models.ImageField(upload_to='products/', default='products/blank.jpg')
def __str__(self):
return self.name
The View:
class ProductAdminView(ListView):
template_name = 'menulistapp/product_admin.html'
queryset = menulist.objects.all()
The template:
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<table class="table table-striped table-hover ">
<thead class="thead-dark">
<tr>
<th style="width: 15%"scope="col"></th>
<th style="width: 55%" scope="col">Product Name</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
<th scope="col">Date Added</th>
<th scope="col">Last Updated</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<td class="align-middle"><img src="{{ obj.img.url }}" class="img-fluid"></td>
<td class="align-middle">{{ obj.name }}</td>
<td class="align-middle">{{ obj.get_category_display }}</td>
<td class="align-middle">${{ obj.price }}</td>
<td class="align-middle">{{ obj.dateadded }}</td>
<td class="align-middle">{{ obj.dateupdated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
How do I separate the items into their own category tables?
And how do I make it so that each cell is editable with their own CharField, and there's a "SAVE" button at the bottom of each table?
EG:
You have to use the concept of forms to attain that
For more information, go through https://docs.djangoproject.com/en/2.1/topics/forms/
I have a table, where a user can choose an option from it, and based on this option I should take the object that was selected and populate it in another table.... (Users is populated by calling an api in the angular controller). what i am trying to do in brief is, ask the user to enter a search word, then retrieve users based on that keyword, and when the user select the user he was searching for, I should show that user in another table (user Details)
{{ form_row(form.userKeyword, { 'attr': { 'ng-model': 'userKeyword', 'ng-value' :'userSelect.id'} }) }}
<table class="table table-bordered table-hover" ng-show="showTable">
<tr>
<th>User Id </th>
<th>Full name </th>
<th>E-mail </th>
<th>Phone Number </th>
</tr>
<tr ng-click="OnTableSelect()" ng-repeat="user in users track by user.id" ng-model="userSelect">
<td>{{ 'ng::user.id::' }}</td>
<td>{{ 'ng::user.name::' }}</td>
<td>{{ 'ng::user.email::' }}</td>
<td>{{ 'ng::user.phone::' }}</td>
</tr>
</table>
Search
</div>
<div class="form-group" ng-show="showUserDetails">
<label>User Details: </label>
<table class="table table-bordered table-hover">
<tr>
<th>User Id </th>
<th>Full name </th>
<th>E-mail </th>
<th>Phone Number </th>
</tr>
<tr ng-model="userSelect">
<td>{{ 'ng::user.id::' }}</td>
<td>{{ 'ng::user.name::' }}</td>
<td>{{ 'ng::user.email::' }}</td>
<td>{{ 'ng::user.phone::' }}</td>
</tr>
</table>
app.controller('My Controller', function($scope, $http) {
$scope.showTable = false;
$scope.showUserDetails = false;
$scope.users = [];
$scope.searchBy = "";
$scope.keyword = "";
$scope.userSelect = "";
$scope.userKeyword = "";
$scope.OnButtonClick = function() {
$scope.showTable = true;
console.log($scope.searchBy);
var request = $http({
method: "GET",
url: Routing.generate('api_keyword_users', {
'searchBy': $scope.searchBy,
'keyword': $scope.keyword,
})
});
request.success(function(response) {
$scope.users = response;
console.log($scope.users);
});
}
$scope.OnTableSelect = function() {
$scope.showUserDetails = true;
$scope.showTable = false;
console.log($scope.userKeyowrd);
console.log($scope.userSelect);
}
You can't use ng-model on a <tr> element. What you could do instead is use the ng-click directive on the <tr> and pass the user as part of the call to the controller method:
<table class="table table-bordered table-hover" ng-show="showTable">
<tr>
<th>User Id </th>
<th>Full name </th>
<th>E-mail </th>
<th>Phone Number </th>
</tr>
<tr ng-click="OnTableSelect(user)" ng-repeat="user in users track by user.id">
<td>{{ 'ng::user.id::' }}</td>
<td>{{ 'ng::user.name::' }}</td>
<td>{{ 'ng::user.email::' }}</td>
<td>{{ 'ng::user.phone::' }}</td>
</tr>
</table>
$scope.OnTableSelect = function(user) {
$scope.showUserDetails = true;
$scope.showTable = false;
console.log(user);
}
Here , i wanna retrieve my subdocument array data from nested JSON object using Angular ng-repeat
this is my JSON nested object:
[
{
_id: "5693bc169f5d75301ff5999d",
booking:
[
{
can_name: "Kinley",
can_quantity: "5",
can_cost: "200",
delivery_date: "12-01-2016",
delivery_timeslot: "3pm-8pm",
order_id: "18214",
address: "140,Bajanai koil street, Melmanagar,Poonamallee,Chennai",
_id: "5694926fd6227ee408b9d051",
ordered_at: "2016-01-12T05:43:11.076Z",
status: "UnderProcess"
}
]
},
{
_id: "5693baf07fe08c6012034b13",
booking:
[
{
can_name: "Kinley",
can_quantity: "4",
can_cost: "160",
delivery_date: "12-01-2016",
delivery_timeslot: "3pm-8pm",
order_id: "14426",
address: "154,Pilliayar koil street,Poonamallee,Chennai",
_id: "569491fad6227ee408b9d04f",
ordered_at: "2016-01-12T05:41:14.531Z",
status: "UnderProcess"
},
{
can_name: "Bisleri",
can_quantity: "5",
can_cost: "250",
delivery_date: "12-01-2016",
delivery_timeslot: "3pm-8pm",
order_id: "11391",
address: "154,Pilliayar koil street,Poonamallee,Chennai",
_id: "5694923ad6227ee408b9d050",
ordered_at: "2016-01-12T05:42:18.900Z",
status: "UnderProcess"
}
]
}
]
Angular Controller Code:
$http.get('/auth/booking-date/' + id).success(function(response){
$scope.todaylist = response;
console.log(response);
$scope.today = '';
});
Here, how can i use ng-repeat to retrieve every subdocument data.
this is what am tried, but am not able get every data:
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Address</th>
<th>Can Name</th>
<th>Can Quantity</th>
<th>Can Cost</th>
<th>Timeslot</th>
<th>Delivery Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="today in todaylist">
<td>{{today._id}}</td>
<td>{{today.booking[0].address}}</td>
<td>{{today.booking[0].can_name}}</td>
<td>{{today.booking[0].can_quantity}}</td>
<td>{{today.booking[0].can_cost}}</td>
<td>{{today.booking[0].delivery_timeslot}}</td>
<td>{{today.booking[0].delivery_date | date:'dd-MM-yyyy'}}</td>
</tr>
</tbody>
</table>
</div>
Help will be appreciated...
See above i posted my JSON data instead of Link
I am not sure but check if this solves your problem:
<tr ng-repeat="today in todaylist">
<div ng-repeat="bookingObj in today.booking">
<td>{{today._id}}</td>
<td>{{bookingObj.address}}</td>
<td>{{bookingObj.can_name}}</td>
<td>{{bookingObj.can_quantity}}</td>
<td>{{bookingObj.can_cost}}</td>
<td>{{bookingObj.delivery_timeslot}}</td>
<td>{{bookingObj.delivery_date | date:'dd-MM-yyyy'}}</td>
</div>
</tr>
I am just applying my logic directly here. Try this:
<tbody ng-repeat="today in todaylist">
<tr ng-repeat="bookingObj in today.booking">
<td>{{today._id}}</td>
<td>{{bookingObj.address}}</td>
<td>{{bookingObj.can_name}}</td>
<td>{{bookingObj.can_quantity}}</td>
<td>{{bookingObj.can_cost}}</td>
<td>{{bookingObj.delivery_timeslot}}</td>
<td>{{bookingObj.delivery_date | date:'dd-MM-yyyy'}}</td>
</tr>
</tbody>
Also, try removing this line, I guess it because this line will replace current content of today, and hence no data will be displayed:
$scope.today = '';
Just use the below code
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Address</th>
<th>Can Name</th>
<th>Can Quantity</th>
<th>Can Cost</th>
<th>Timeslot</th>
<th>Delivery Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="today in todaylist">
<div ng-repeat="booking in today.booking">
<td>{{today._id}}</td>
<td>{{booking.address}}</td>
<td>{{booking.can_name}}</td>
<td>{{booking.can_quantity}}</td>
<td>{{booking.can_cost}}</td>
<td>{{booking.delivery_timeslot}}</td>
<td>{{booking.delivery_date | date:'dd-MM-yyyy'}}</td>
</div>
</tr>
</tbody>
</table>
</div>
It looks like your objects are stored in the booking array. To iterate through this array and add a new row on your DOM for each item in your array, I'd suggest the following:
<tbody>
<tr ng-repeat="booking in todaylist.booking">
<td>{{ today._id }}</td>
<td>{{ booking.address }}</td>
<td>{{ booking.can_name }}</td>
<td>{{ booking.can_quantity }}</td>
<td>{{ booking.can_cost }}</td>
<td>{{ booking.delivery_timeslot }}</td>
<td>{{ booking.delivery_date | date:'dd-MM-yyyy' }}</td>
</tr>
</tbody>
For the sake of clarity, you may want to change the variable name of your array from booking to bookings. I find it less confusing to keep the variable names of collections as plural nouns. This makes it easier to easily identify what to expect in your collection.
With that change, you'd have:
<tbody>
<tr ng-repeat="booking in todaylist.bookings">
<td>{{ today._id }}</td>
<td>{{ booking.address }}</td>
<td>{{ booking.can_name }}</td>
<td>{{ booking.can_quantity }}</td>
<td>{{ booking.can_cost }}</td>
<td>{{ booking.delivery_timeslot }}</td>
<td>{{ booking.delivery_date | date:'dd-MM-yyyy' }}</td>
</tr>
</tbody>
I have a navbar on my page that has an input on it that I want to search a view, that should load in index.html after the user types in their search items. I can only figure out how to search with an input if it's in the same page that the table of ng-repeat items is in. Is there a way to search the table outside of the view? I've created a plnkr. It doesn't work. I'm not sure how to make it work. http://plnkr.co/edit/nqChzn5OATNMeSZL7ItJ?p=preview
Here is some of my code:
navbar
<input type="text" class="form-control" placeholder="Search" ng-model="vm.query">
Here is my table where the data displays.
<table ng-if="query" class="table table-hover table-responsive" >
<thead>
<tr>
<th>
({{filteredResults.length}}) Results Found
</th>
</tr>
<tr>
<td>Acc. ID</td>
<td>Acc. Name</td>
<td>Acc Address</td>
<td>City</td>
<td>Zip</td>
<td>Phone</td>
<td>Parent Name</td>
<td>Account Type</td>
<td>Account Status</td>
<td>Credit Term</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="result in vm.results | filter:query as filteredResults">
<td>{{ result.accountId }}</td>
<td>{{ result.accountName }}</td>
<td>{{ result.address }}</td>
<td>{{ result.city }}</td>
<td>{{ result.state }}</td>
<td>{{ reuslt.zip }}</td>
<td>{{ result.phone }}</td>
<td>{{ result.parentName }}</td>
<td>{{ result.accountType }}</td>
<td>{{ result.accountStatus }}</td>
<td>{{ result.accountStatus }}</td>
</tr>
</tbody>
</table>
Is it possible to do what I want to do?
I've looked at your plunker and I don't believe that your code hasn't initialized angular. I can't see an ng-app tag anywhere in your code.
That a side, you will be able to use any input to filter/search (via. various implementations) so long as the input and table are contained with your ng-app and controller parts of the DOM. Otherwise you won't be able to access it the controller.
Can I suggest that you distill your question down? give the smallest amount of code that demonstrates your problem.
here's a rough outline:
<body ng-app="app" ng-controller="cntrl">
<!-- nav bar -->
<div>
<input ng-model="filterVal"/>
</div>
<!-- table -->
<div>
<table>
<tr ng-repeat="r in data.rows | filter:filterVal">....</tr>
</table>
</div>
</body>
Here's a plunker where the default filter functionality is working: http://plnkr.co/edit/GDJs5xTCpqq48SDFTk67
If you need to have your nav bar outside of your app/controller or in an different controller (etc.) then there are solutions to this.
Assuming you are using ui-route, this is how to use a service to communicate between controllers:
functioning example:
http://plnkr.co/edit/fZZLUvlHO9zUFwQYd1an?p=preview
Eggheads video:
https://egghead.io/lessons/angularjs-sharing-data-between-controllers