Issue
I have a custom widget used to replace the dropdown for the ForeignKey
field with a list of images with radiobuttons. In my render
method I need to access the current user (the user who is currently logged in), like I would in a normal view with using request.user
.
I have read a lot of solutions to do this with Forms
, that you should pop the user object from **kwargs
in your __init__
method.
However widgets doesn't have **kwargs
in their __init__
method:
def __init__(self, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
How do I access the current user within a Widget
sub-class?
Solution
I found a solution by reading through the Django source: Pass the user object when setting the formfield_overrides
in the custom admin.
I have 2 models: News
and Image
. Image
contains a name field and an ImageField
. The News
model contains a ForeignKey
which points to image:
class News(models.Model):
... bunch of news related fields
image = models.ForeignKey(Image)
Then in my admin.py
I have a custom admin class for news:
class NewsAdmin(admin.ModelAdmin):
model = News
def get_form(self, request, obj=None, **kwargs):
self.formfield_overrides = {
models.ForeignKey : {'widget' : SelectForeign(user = request.user)}
}
return super(NewsAdmin, self).get_form(request, obj, **kwargs)
Then in my widget.py
I have a custom widget class:
class SelectForeign(widgets.Widget):
current_user = None
def __init__(self, attrs=None, choices=(), user = None):
self.current_user = user
super(SelectForegin, self).__init__(attrs, choices)
And that's it, now my widget contains the current logged in user. It's not pretty imo, but it works.
Note:
This replaces all ForeignKey
fields inside the News
model. To fix this, there should be a custom ForeignKey
sub-class used so that we can override that one only.
If anyone has a better solution which is cleaner, please share and I'll accept.
Answered By - rzetterberg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.