C
C
Cyril2014-05-25 18:14:13
Django
Cyril, 2014-05-25 18:14:13

How to use request.user in Django models?

I need to do a validation in the model, something like:

Class Action(models.Model):
...
    def voted(self):
        RedisCache = redis.StrictRedis()
        return RedisCache.sismember("ph_real:%i" % self.id, self.request.user.id)

But I can't get self.request.user.id. Is it possible to somehow get it in the model? Maybe we can create def voted(self, id): and pass the id from the template?
The background of the task, in general, it is not really needed to solve the issue:
I have an event feed with a vote for each
Stream.html event:
{% for action in action_list %}   
        {% if action.voted%}
            <p>You have already voted</p>
        {% else %}
            <form action="{% url "vote" action.id %}" method="post">{% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Submit" />
            </form>
        {% endif %}

The voting itself works, the {% if action.voted%} check doesn't work, I can't figure out how to organize it. Data about those who have already voted is in the cache, I managed to check through the context, it works:
context["voted"] = RedisCache.sismember("ph_real:%i" % self.object.id, self.request.user.id)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
leclecovich, 2014-05-25
@leclecovich

The model, as well as the logic contained in it, does not know anything about the request. If you call the voted method from a view, then pass request as a parameter: def voted(self, request):ordef voted(self, user_id):

R
Rostislav Grigoriev, 2014-05-25
@crazyzubr

Why is it so important to do it through the model method? If this does not suit the context, then you can create a filter for the template. You can also use the django-pandora
package as an alternative . It allows you to get a request anywhere in the code, whether it's a method in the model or somewhere in the form.

C
Cyril, 2014-05-26
@aeHarkonnen

I would love to make a kiss method, but I get the action_list from the wonderful django-acivity-stream application. In which it is defined as:
I have:
In the django-activity-stream app:

user_stream = Action.objects.user

class Action(models.Model):
...
objects = actstream_settings.get_action_manager()

class ActionManager(GFKManager):

    @stream
    def user(self, object, **kwargs):

        q = Q()
        qs = self.filter(public=True)
        actors_by_content_type = defaultdict(lambda: [])
        Еще строк 20...

For me, adding something there is ass pain x10. Therefore, I was looking for such a solution, apparently I will have to stop at the filter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question