Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You cannot initiate the store field with request.user in the field declaration. You can try the following:</p> <pre><code>class MyAwesomeForm(forms.ModelForm): store = forms.ModelChoiceField(Store.objects) class Meta: model = Promo def __init__(self, user, *args, **kwargs): super(MyAwesomeForm, self).__init__(*args, **kwargs) self.fields['store'].queryset = Store.objects.filter(owner=user) </code></pre> <p>While instantiating the form you can pass the request.user object. </p> <pre><code>myform = MyAwesomeForm(request.user) </code></pre> <p>If you want to achieve this in the admin you might try <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.queryset" rel="nofollow">this</a> For providing only the objects related to the logged-in user in the admin provides the possibility to overwrite ModelAdmin.queryset function:</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): form = MyAwesomeAdminForm() def queryset(self, request): qs = super(MyModelAdmin, self).queryset(request) if request.user.is_superuser: return qs return qs.filter(store__owner=request.user) class MyAwesomeAdminForm(forms.ModelForm): class Meta: model = Promo </code></pre> <p>Note that store__owner only works if you have a foreign key field stored in your promo model as such:</p> <pre><code>class Promo(models.Model): store = models.ForeignKey(Store) class Store(models.Model): owner = models.ForeignKey(User) </code></pre> <p>I assume it should also be possible to somehow pass the request to the init method of the form. But did not find a suitable approach to do it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload