SURYA VISWANATHAN SURYA VISWANATHAN - 1 month ago 7
AngularJS Question

Pass Value from View to controller and display in template

I need to pass the latest value from a database field to the controller. I'm also in due to perform certain calculations with respect to the value I get from the view in the controller. I'm not aware how to use the value from the view to the controller. I'm new to django. Any help would be appreciated. Below is my code,

In my views.py

class SiverifyAddReviewView(JSONResponseMixin, TemplateView):
template_name = "siverify_add_review.html"

def get_context_data(self,*args, **kwargs):
latest_id = SiverifyVerificationSiteRevision.objects.order_by('-id').first().id
context = super(SiverifyAddReviewView, self).get_context_data(*args, **kwargs)
print 'latest_id', latest_id
context['reviewtit'] = 'Review_' + latest_id + '_' + time.strftime(%Y%m%d)
context['ngapp'] = 'ReviewMod'
return context


In the below line, SiverifyVerificationSiteRevision is the model name and I need to the latest value of the field id.

l_id = SiverifyVerificationSiteRevision.objects.latest('id')


Is this the right method to get the latest value from the model? And Over to controller, I need to perform the below function.

Controller:

{{ngapp}}.controller(
"SiVerifyAddReviewController",
function($scope, $http, $modalInstance, r_header, context){
$scope.today= function dat() {
var d = new Date();
return 'Review_' + **l_id** + ((d.getFullYear() + ' ' + (d.getMonth() + 1) + ' ' + d.getDate()).replace(/ /g, ''));}
$scope.arform['revtitle']= $scope.today();}


As in the return statement( l_id), I need to get the latest value from the views and get in the template. My template code is,

Template:

<tr>
<td><label>Review Title/Purpose*</label></td></br>
<td><input type="text" class="col-md-10" maxlength="256" ng-model="arform.revtitle" required/></td>
</tr>


I'm sure there should be a way to get the value from the view to the controller, I had gone through several Question tags such as Passing Value from View to Controller. But none of them seem to correlate with my need. Any methods are welcome. Thanks.

Answer

Do you need just the latest by date or latest by insert into DB? That's kinda different.

def get_context_data(self, **kwargs):

   latest_id = SiverifyVerificationSiteRevision.objects.latest('date').id  # `latest` method works on date fields.

   # This one gives you latest ID by insert.
   # latest_id = SiverifyVerificationSiteRevision.objects.order_by('-id').first().id

   kwargs['latest_id'] = latest_id
   kwargs['ngapp'] = 'ReviewMod'

   return kwargs
Comments