Answer the question
In order to leave comments, you need to log in
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)
{% 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 %}
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
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):
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.
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...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question