Django queryset calling only objects belonging to User

495 views Asked by At

I'm unable to figure out how to only call a queryset of items that belong to a specific User in the django forms.

dropoffs/models.py

class DropoffItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
    dropoff = models.ForeignKey('Dropoff', null=True, blank=True)
    product = models.ForeignKey(Product)
    location = models.CharField(max_length=120, choices=LOCATION_CHOICES, default="Customer")

    def __str__(self):

        return str('%s' + " " + "(" + '%s' + ")") %(self.product.title, self.product.sku)

    def sku(self):
        return self.product.sku

    def title(self):
        return self.product.title

    def dropoff_id(self):
        return str(self.dropoff.id)

forms.py

class AddPickupItemForm(forms.ModelForm):
    dropoffitem = forms.ModelChoiceField(queryset=DropoffItem.objects.none())

    class Meta:
        model = PickupItem
        # fields = ["product", "quantity"]
        fields = ['dropoffitem']

    def __init__(self, user, *args, **kwargs):
        # self.request = kwargs.pop("request")
        the_user = kwargs.pop('user', None)
        super(AddPickupItemForm, self).__init__(*args, **kwargs)
        if the_user is not None:
            self.fields["dropoffitem"].queryset = DropoffItem.objects.filter(user=the_user)

views.py

def add_item_to_pickup_order(request):
    request.session.set_expiry(120000)

    try:
        user = request.user
        the_id = request.session['pickup_id']               
        pickup = Pickup.objects.get(id=the_id)          
    except:
        user = request.user                                 
        new_pickup_order = Pickup(user=user)                
        new_pickup_order.save()
        request.session['pickup_id'] = new_pickup_order.id          

        the_id = new_pickup_order.id
        pickup = Pickup.objects.get(id=the_id)                  

    try:
        dropoffitem = DropoffItem.objects.filter(user=user)
    except DropoffItem.DoesNotExist:
        pass
    except:
        pass

    form = AddPickupItemForm(request.POST, user=request.user)
    if request.method == "POST":

        dropoffitem_id = int(request.POST['dropoffitem'])
        pickup_item = PickupItem.objects.create(pickup=pickup, dropoffitem_id=dropoffitem_id)

        pickup_item.save()


        return HttpResponseRedirect('%s'%(reverse('add_item_to_pickup_order')))

    context = {

        "pickup": pickup,
        "form": form,

    }
    return render(request, 'pickups/create_pickup_order.html', context)

With the modifications to init, I'm getting a TypeError of: init() got multiple values for keyword argument 'user'.

Could that be because of how I'm requesting a 'session'?

1

There are 1 answers

4
professorDante On
class AddPickupItemForm(ModelForm):

    def __init__(self,*args,**kwargs)
        the_user = kwargs.pop('user',None)
        super(AddPickupItemForm, self).__init__(*args,**kwargs)
        if the_user is not None:
            self.fields['dropoffitem'].queryset = DropOffItem.objects.filter(user=the_user)

In other words, pass your user to the form when instantiating, if you need to.