How to store user_id in admin of wagtail (non page model)?

142 views Asked by At

I have some model like below in my blog-like website, I hope different user can query their own data. SO, I need save user id in my model.

However, modeladmin of wagtail only has get_queryset() but no save_model()

class Info(Orderable):
    user = models.ForeignKey('auth.User', 
                          on_delete=models.CASCADE,
                          blank=False, null=True,
                          related_name='+',)

Is there any way to store user id in wagtail admin panel?

2

There are 2 answers

1
Distroyer On

if you mean (from) admin, yes you can, but if you mean to admin panel from the model class, no you can't, handling the request is job of Views(the controllers) once the URL been requested, the view evaluate many things, one of them is request.user, and this one is an object of User model, you can then ask for id by (requested.user.id).. but of course in the views.py, or wagtail_hooks.py

0
Karl Jhan On

The other way is pre-populate it, I try to do this and it's work well.

def create_view(self, request):
    view = super().create_view(request)
    self._set_username(view, request)
    return view

def _set_username(self, view, request):
    if hasattr(view, 'context_data'):
        form = view.context_data['form']
        form.fields['name'].widget.attrs['value'] = request.user