我使用djnago-tables2来显示我的事件模型中的数据。我需要将当前请求用户放入表的render方法中(进一步调用模型函数以获取当前用户的响应)。
我该怎么做?
我的模特
class Event(models.Model):
name=models.CharField(max_length=254)
start=models.DateTimeField()
end=models.DateTimeField()
invited_user=models.ManyToManyField(User,blank=True)
def getResponseFromUser(self, user):
try:
return Response.objects.filter(event=self, user=user).order_by('-pk')[0]
except Exception:
return None
class Response(models.Model):
user=models.ForeignKey(User)
event=models.ForeignKey(Event)
timestamp=models.DateTimeField(auto_now_add=True)
SEEN=0
YES=1
PROBABLY_YES=2
PROBABLY_NO=3
NO=4
RESPONSE=(
(SEEN, _('seen but undecided')),
(YES, _('Yes')),
(PROBABLY_YES, _('probably yes')),
(PROBABLY_NO, _('probably no')),
(NO, _('No')),
)
response=models.IntegerField( choices=RESPONSE, default=SEEN)
@property
def getResponseText(self):
return self.RESPONSE[self.response][1]
表
class EventTable(tables.Table):
requestUser=None # to be set from request (externally)
eventResponse = tables.Column(empty_values=(), verbose_name="Response", orderable=False)
class Meta:
model = Event
# add class="paleblue" to <table> tag
attrs = {"class": "table"}
exclude=['id', 'user_can_invite', 'description', 'organizer']
def render_eventResponse(self, record):
responseObject=record.getResponseFromUser(self.requestUser)
if not responseObject:
return ''
else:
return responseObject.getResponseText
查看
class PersonalEventTableView(SingleTableView):
model = Event
table_class = EventTable
template_name = 'list_events.html'
paginate_by = 50
在urls.py中,视图使用PersonalEventTableView.as_view()
呈现有人可以帮忙吗?
答案 0 :(得分:2)
你可以在这里使用这个插件:https://github.com/Alir3z4/django-crequest
像这样使用:
def render_eventResponse(self, record):
from crequest.middleware import CrequestMiddleware
current_request = CrequestMiddleware.get_request()
user = current_request.user
responseObject=record.getResponseFromUser(user)
if not responseObject:
return ''
else:
return responseObject.getResponseText
答案 1 :(得分:0)
您可以非常简单地将请求添加到表上下文中。
class PersonalEventTableView(SingleTableView):
model = Event
table_class = EventTable
template_name = 'list_events.html'
paginate_by = 50
def get_context_data(self, **kwargs):
""" From the code itself """
context = super(SingleTableMixin, self).get_context_data(**kwargs)
table = self.get_table(**self.get_table_kwargs())
# add the request directly to your table
table.request = self.request
context[self.get_context_table_name(table)] = table
return context
现在将在您的Table类中使用它。
class EventTable(tables.Table):
eventResponse = tables.Column(empty_values=(), verbose_name="Response", orderable=False)
class Meta:
model = Event
attrs = {"class": "table"}
exclude=['id', 'user_can_invite', 'description', 'organizer']
def render_eventResponse(self, record):
# self.request.user is available
responseObject=record.getResponseFromUser(self.request.user)
return responseObject.getResponseText if responseObject else ""