简体   繁体   English

如何过滤使用下拉菜单放入django表单的foreignkey字段中可以看到的选项?

[英]How to filter the options that can be seen in a foreignkey field that has been put into a django form using drop down menu?

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 (ie the advertisement they selected.) 如何将结果过滤为一个选项(即他们选择的广告)。

ad_update view ad_update视图

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'

ForeignKey is represented by django.forms.ModelChoiceField , which is a ChoiceField whose choices are a model queryset. ForeignKey由django.forms.ModelChoiceField表示,它是一个ChoiceField,其选择是模型查询集。

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 :) 我希望这能帮到您 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM