Django用户会话混合。 [英] Django User's Sessions getting Mixed.
问题描述
这是我有的:
在App的admin.py:
151 class AdminForm(ModelForm):
152 class Meta:
153 model = PromotionalSlot
154 exclude = ['deal']
155
156 class NormalUserForm(ModelForm):
157 class Meta:
158 model = PromotionalSlot
159 exclude = ['site' ]
160
161 class PromotionalSlotAdmin(admin.ModelAdmin):
162 def get_form(self,request,obj = None,** kwargs):
163 if request.user。 is_superuser:
164 return AdminForm
165 else:
166 self.readonly_fields = ['start_date','end_date','level','city','status']
167 return NormalUserForm·
168
169 admin.site.register(models.PromotionalSlot,PromotionalSlotAdmin)
谢谢
问题是您的解决方案不是线程安全的。 Django会保留管理实例,因此您设置为 self.readonly_fields
的值也用于线程中的所有后续请求。这是如何使线程安全的:
class PromotionalSlotAdmin(admin.ModelAdmin):
def get_readonly_fields(self,request,obj = None):
如果request.user.is_superuser:
return []
else:
return ['start_date','end_date' 'level','city','status']
def get_form(self,request,obj = None,** kwargs):
if request.user.is_superuser:
返回AdminForm
其他:
返回NormalUserForm
In Django's admin interface, there is a form, of a specific model that I want to be rendered in different ways depending if the logged user accessing this form is a normal user or an admin. It's working find except one HUGE thing: it get's mixed. For instance, the fields that should be editable by the admin are read-only, after I immediately prior to that had been logged in as a "normal" user. If I try the exactly same thing immediately after restarting the server, works fine and all fields are editable. I guess that somehow the user's sessions are get mixed up. How to handle this?
Here is waht I have:
In the App's admin.py:
151 class AdminForm(ModelForm):
152 class Meta:
153 model = PromotionalSlot
154 exclude = ['deal']
155
156 class NormalUserForm(ModelForm):
157 class Meta:
158 model = PromotionalSlot
159 exclude = ['site']
160
161 class PromotionalSlotAdmin(admin.ModelAdmin):
162 def get_form(self, request, obj=None, **kwargs):
163 if request.user.is_superuser:
164 return AdminForm
165 else:
166 self.readonly_fields = ['start_date','end_date','level','city','status']
167 return NormalUserForm·
168
169 admin.site.register(models.PromotionalSlot, PromotionalSlotAdmin)
Thanks
The problem is that your solution isn't thread safe. Django keeps the admin instance around and so the value you set to self.readonly_fields
is used also for all subsequent requests in the thread. This is how you can make it thread safe:
class PromotionalSlotAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return []
else:
return ['start_date', 'end_date', 'level', 'city', 'status']
def get_form(self, request, obj=None, **kwargs):
if request.user.is_superuser:
return AdminForm
else:
return NormalUserForm
这篇关于Django用户会话混合。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!