0

admin.py

class PromoAdmin(admin.modelAdmin)
      list_display = ( 'name', 'id', 'category', 'promo_type', 'store', 'brand', 'date_start' )
      form = SampleForm

forms.py

class SampleForm(forms.ModelForm):
class Meta:
     model = Promo

def __init__(self, request *args, **kwargs):
    super(PromoAdminForm, self).__init__(*args, **kwargs)
    self.fields["store"].queryset = Store.objects.filter(onwer=request.user)

got an error on request

Django Version: 1.3.1 Exception Type: TypeError Exception Value:
init() takes at least 2 arguments (1 given)

user683742
  • 80
  • 2
  • 8

1 Answers1

1

You cannot initiate the store field with request.user in the field declaration. You can try the following:

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)

While instantiating the form you can pass the request.user object.

myform = MyAwesomeForm(request.user)

If you want to achieve this in the admin you might try this For providing only the objects related to the logged-in user in the admin provides the possibility to overwrite ModelAdmin.queryset function:

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

Note that store__owner only works if you have a foreign key field stored in your promo model as such:

class Promo(models.Model):
    store = models.ForeignKey(Store)

class Store(models.Model):
    owner = models.ForeignKey(User)

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.

Thomas Kremmel
  • 14,575
  • 26
  • 108
  • 177
  • thanks for answering tom, followup question, this form will be use in the django admin. So we will override the the admin form. How do i pass request.user – user683742 Aug 31 '12 at 09:48
  • I got reference to solve this problem https://docs.djangoproject.com/en/1.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey – user683742 Aug 31 '12 at 11:19
  • this is better if you need request in admin model form class-> http://stackoverflow.com/a/6062628/758202 – zzart Mar 07 '13 at 09:17