gpt4 book ai didi

django-tables2:在渲染方法中使用请求用户

转载 作者:行者123 更新时间:2023-12-04 00:41:20 25 4
gpt4 key购买 nike

我正在使用 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 中, View 使用 PersonalEventTableView.as_view() 呈现

任何人都可以帮忙吗?

最佳答案

您可以非常简单地将请求添加到表的上下文中。

class PersonalEventTableView(SingleTableView):
model = Event
table_class = EventTable
template_name = 'list_events.html'
paginate_by = 50

def get_context_data(self, **kwargs):
""" Override SingleTableView class method """
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 类中使用它。
类 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 ""

关于django-tables2:在渲染方法中使用请求用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com