I have a model for Advertisements and I display a list of them on a page. The user is to click the advertisement that they want added to their profile. When a user clicks one of the advertisements they would like added they are redirected to a page that lets them add that advertisement object to their profile. However I would like to filter the advertisements in the drop down form displayed on that page to only show the advertisement object that they selected from the list. How would I filter the results to just one option (i.e the advertisement they selected.)

ad_update view

def ad_update(request, my_id):

obj = Advertisement.objects.get(id=my_id)
profile = get_object_or_404(Profile, user=request.user)
amount = getAddressAmountUSD(request.user.profile.advertisement.ethAddress)


if request.method == 'POST':
    ad_form = AdvertisementUpdateForm(request.POST, instance=profile)
    if ad_form.is_valid():
        ad_form.save()
        messages.success(request, f'Your account has been Updated!')
        return redirect('profile')
else:
    ad_form = AdvertisementUpdateForm(instance=profile)
context = {
    'ad_form':  ad_form,
    'object': obj,
    'amount': amount,
}
return render(request, 'users/advertisement_update.html', context)

form

class AdvertisementUpdateForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ['advertisement']

model

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ethAddress = models.CharField(max_length=42, default='')
    advertisement = models.ForeignKey(Advertisement, 
        on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return f'{self.user.username} Profile'

1 Answers

0
PyMaster On

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model queryset.

You can filter field options like below.

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['foo'].queryset = ...

You can filter query set from view also like below.

form.foo.queryset = Foo.objects.filter(...)

I hope this will help you :)