0

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.

SURYA VISWANATHAN
  • 187
  • 1
  • 3
  • 12

1 Answers1

1

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
Andrey Shipilov
  • 1,986
  • 12
  • 14
  • 'id' is a field in SiverifyVerificationSiteRevision table in db. I need to get the latest value of the id field from the db and include in the below function. I'm already getting today's date in the function specified controller. My Ultimate aim is to get 'Review_id(latest value from db)_today's date' in the template I mentioned in the Question. – SURYA VISWANATHAN Oct 19 '16 at 05:02
  • That's not exactly what I asked :) Look at my code. Uncommented line with `latest_id` will give you ID of an object latest by date. The commented line — latest inserted in the DB. – Andrey Shipilov Oct 19 '16 at 05:08
  • I need the latest ID by insert. Will use the commented line. Can I use 'latest_id' directly in my controller? return 'Review_' + **l_id** + ((d.getFullYear() + ' ' + (d.getMonth() + 1) + ' ' + d.getDate()).replace(/ /g, ''));} – SURYA VISWANATHAN Oct 19 '16 at 05:19
  • return 'Review_' + **latest_id**+ ((d.getFullYear() + ' ' + (d.getMonth() + 1) + ' ' + d.getDate()).replace(/ /g, ''));} – SURYA VISWANATHAN Oct 19 '16 at 05:19
  • `{{ latest_id }}` — yes, it will be in context by then. – Andrey Shipilov Oct 19 '16 at 05:20
  • I’m getting this, AttributeError: 'QuerySet' object has no attribute 'id' Any issues in using order_by('-id').id? Just for your reference, Using the below code In Views: def get_context_data(self,*args, **kwargs): latest_id = SiverifyVerificationSiteRevision.objects.order_by('-id').id context = super(SiverifyAddReviewView, self).get_context_data(*args, **kwargs) context['latest_id'] = latest_id print 'latest_id', latest_id context['ngapp'] = 'ReviewMod' return context – SURYA VISWANATHAN Oct 19 '16 at 06:02
  • Oops, my bad. I've fixed the answer. You need to get `.first()` element after querying. Assuming that you have more than 0 objects in database of course. – Andrey Shipilov Oct 19 '16 at 06:05
  • I'm able to get the value. But the controller part is not working. It is not even taking {{latest_id}} from the controller. Any idea why? I could see in my front end console that it is not displaying the part {{latest_id}} of my code. – SURYA VISWANATHAN Oct 19 '16 at 06:23
  • Is `latest_id` in the context at all? Is it printed in terminal if you do `print 'latest_id', latest_id `? – Andrey Shipilov Oct 19 '16 at 06:25
  • Yes it prints in the terminal! – SURYA VISWANATHAN Oct 19 '16 at 06:26
  • Then it should be in the template for sure. – Andrey Shipilov Oct 19 '16 at 06:42
  • My template(html) and controller are in different files. Guess the problem is with the linkage. – SURYA VISWANATHAN Oct 19 '16 at 08:49
  • Ah well yeah. Template context is not passed to static files. – Andrey Shipilov Oct 19 '16 at 08:51
  • Is there any different approach to get in the controller? – SURYA VISWANATHAN Oct 19 '16 at 08:54
  • Of course. One way is to include JS code in your template and then compress it using Django-compressor. Other way is to put variables in global scope again in your template before any of other JS is called. For example into window object. – Andrey Shipilov Oct 19 '16 at 08:56
  • Oh Thanks! If possible, Could you refer me any examples in putting variables in global scope method? Feel, Django-compressor method would be complex. – SURYA VISWANATHAN Oct 19 '16 at 09:02
  • In your case it literally would be window.latest_id = {{ latest_id }}; in the head tag before all other JS. – Andrey Shipilov Oct 19 '16 at 09:05
  • Means you ask me to do like this in my controller? {ngapp}}.controller( "SiVerifyAddReviewController", function($scope, $http, $modalInstance, r_header, context, window.latest_id = {{latest_id}}) – SURYA VISWANATHAN Oct 19 '16 at 09:16
  • No. Put this in the head of your template: `` then in your ng-controller just use window.latest_id as usual variable. – Andrey Shipilov Oct 19 '16 at 09:22
  • Getting my O/p like this Review_NaN20161019. It should actually be Review_window.latest_id_20161019. I also need to add plus 1 to the value I get in window.latest_id. Trying out with this code, $scope.l_id = window.latest_id + 1; $scope.today= function dat() { var d = new Date(); return 'Review_' + $scope.l_id + ((d.getFullYear() + ' ' + (d.getMonth() + 1) + ' ' + d.getDate()).replace(/ /g, ''));} $scope.arform['revtitle']= $scope.today(); – SURYA VISWANATHAN Oct 19 '16 at 09:40
  • This one is just JS task now. Debug and you'll make it. – Andrey Shipilov Oct 19 '16 at 09:44
  • Fact of the matter is, I'm not able to get the value in the controller. When I tried to console window.latest_id in the controller I'm getting undefined. Means it is not taking the value from the template probably. – SURYA VISWANATHAN Oct 19 '16 at 10:37
  • Do you get something like this in your browser, in source code? ``. Number could be anything. – Andrey Shipilov Oct 19 '16 at 10:41
  • Nope. I'm not seeing it in the source code. Not sure why. – SURYA VISWANATHAN Oct 19 '16 at 10:50
  • You sure you put this – Andrey Shipilov Oct 19 '16 at 10:56
  • This is how I declared in my template file. – SURYA VISWANATHAN Oct 19 '16 at 10:57
  • In the . Before all JS tags. – Andrey Shipilov Oct 19 '16 at 10:58
  • I'm able to see in the browser console when I check the value of window.latest_id – SURYA VISWANATHAN Oct 19 '16 at 10:59
  • Of course. Cause it gets executed at some point. But you need to call before all your Angular code. – Andrey Shipilov Oct 19 '16 at 11:01
  • Tried giving before class="modal-header container-fluid">. Din't work even then. Same NaN error:( – SURYA VISWANATHAN Oct 19 '16 at 11:03
  • Hello. How about passing the entire string value which I have in the controller from the views itself? I mean to say, 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'] = raw_input('Review_' + latest_id + '_' + time.strftime(%Y%m%d)) context['ngapp'] = 'ReviewMod' return context – SURYA VISWANATHAN Oct 20 '16 at 03:01
  • Yeah you can do that. – Andrey Shipilov Oct 20 '16 at 03:03
  • Have edited my views code in Question. Getting a syntax error. Any suggestions? – SURYA VISWANATHAN Oct 20 '16 at 03:15
  • Indentation. http://dpaste.com/3XTCYFT use PEP8 at any time https://www.python.org/dev/peps/pep-0008/ – Andrey Shipilov Oct 20 '16 at 03:20
  • Corrected Indent error. Now, TypeError: cannot concatenate 'str' and 'long' objects – SURYA VISWANATHAN Oct 20 '16 at 03:37
  • What's a long object here? latest_id. So you have to convert it to str: `context['reviewtit'] = 'Review_' + str(latest_id) + '_' + time.strftime(%Y%m%d)`. – Andrey Shipilov Oct 20 '16 at 03:50
  • No problems. :) – Andrey Shipilov Oct 20 '16 at 05:27
  • could you check this one too? Initialize two values with an if in template-django http://stackoverflow.com/q/40154178/6837857?sem=2 – SURYA VISWANATHAN Oct 21 '16 at 03:18
  • Could you give your ideas on this? http://stackoverflow.com/questions/40358942/modal-opens-only-after-clicking-twice-when-submitted-for-the-first-time-from-a-b – SURYA VISWANATHAN Nov 02 '16 at 03:34
  • http://stackoverflow.com/questions/41054755/search-choice-field-by-the-name-in-django-python – SURYA VISWANATHAN Dec 09 '16 at 08:00