views:

796

answers:

2

I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?

One idea: Adding the request to a models method would do the trick. Is that possible?

Edit: I meant in templatecode: {{ lesson.get_status }}, with get_status(self, request). Is it possible? It does not work (yet).

A: 

Yes, you can add a method to your model with a request paramater:

class MyModel(models.Model):
    fields....

    def update_status(self, request):
        make something with the request...
Andrea Di Persio
is it possible to call this method from a view? that's the goal and it does not work (yet)!
Jack Ha
i meant from templatecode, like {{ lesson.update_status }}
Jack Ha
You cannot pass arguments to a method from a template.
S.Lott
Maybe you can try using some template tag.On template:{% upd_status status="New Status" %}on templatetags code:@register.simple_tagdef upd_status(status): ...do something with status
Andrea Di Persio
You can if you use Cheetah templates.
orokusaki
+2  A: 

If your status is a value that changes, you have to break this into two separate parts.

  1. Updating the status. This must be called in a view function. The real work, however, belongs in the model. The view function calls the model method and does the save.

  2. Displaying the status. This is just some string representation of the status.

Model

class MyStatefulModel( models.Model ):
    theState = models.CharField( max_length=64 )
    def changeState( self ):
        if theState is None:
            theState= "viewed"
        elif theState is "viewed":
            theState= "learning"
        etc.

View Function

 def show( request, object_id ):
     object= MyStatefulModel.objects.get( id=object_id )
     object.changeState()
     object.save()
     render_to_response( ... )

Template

 <p>Your status is {{object.theState}}.</p>
S.Lott