1👍
When you write a model method you pass on self
as parameter, which obviously refers to instance itself. Change your model method to something like this
class Task(models.Model):
fields
def is_finished(self):
return appropriate boolean from here
Now in your template you can use this simply as {{ task.is_finished }}
. Notice that I am not passing any id
as a parameter. This is because, when writing a model method you pass self
as parameter which refers to instance on which method is being called.
I hope this makes sense to you and helps you understand model methods in a simple way.
0👍
I don’t fully understand your question, why can’t you just sent in task_id as a parameter?
class Task(models.Model):
...
def check_if_finished(self, task_id):
resp = requests.get(
'http://my.rest.api/tasks/view/{}'.format(task_id))
resp_data = resp.json()
resp_finished = resp_data['task']['started_on']
if resp_finished is None:
return False
else:
return resp_finished
then call it anytime:
{{ task.check_if_finished(task.task_id) }}
Could also make task_id an optional parameter.
def check_if_finished(self, task_id=None):
task_id = task_id or self.task_id
resp = requests.get...
I’m not sure why you wouldn’t want to use the task_id on the instance though. If you never will then maybe it should be a static method?
@staticmethod
def check_if_finished(cls, task_id):
...
I don’t think Django models prevent any of these options. Hopefully something there was helpful, else I need a bit more information and what you are trying to accomplish.
Edit: Django templates don’t allow calling function/methods with arguments. You need to create a custom template tag or just call the function in the view and send the result to the template. See previous question.
- Django not searching for translation messages
- Throttling based on authentication class
- Python/Django: How to delete an instance automatically after an action?