简体   繁体   中英

Django Foreign Key Dropdown Filter

I have a model called Listing which is basically a job listing posted by my users. One of the fields is a Foreign Key called Address (since a user can have multiple addresses). Here is my models.py:

class JobListing(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    customer = models.ForeignKey('CustomerAuth.CustomerProfile')
    address = models.ForeignKey('CustomerAuth.Address')

Here is my forms.py:

class JobListingForm(forms.ModelForm):
    class Meta:
        model = JobListing
        fields = ['title', 'description', 'address', 'customer']

and finally the relevant parts of my views.py:

def create_listing(request):
    form = JobListingForm(request.POST or None)

    if form.is_valid():
        listing = form.save(commit=False)
        listing.save()

        current_user = CustomerProfile.objects.get(user=request.user)
        listing.customer = current_user
        listing.save()

        return HttpResponseRedirect('/listings/id/%s' % listing.id)

    context_dict = {'form': form}
    return render(request, 'listing/create-listing.html', context_dict)

As it currently stands when a user selects an address from the dropdown it shows everyones address. Is there anyway I can filter it so that only the addresses entered by that user is shown.

尝试这样的事情

model1.objects.get(pk=1).model2_set.all() 

forms.py

class JobListingForm(forms.ModelForm):
    class Meta:
        model = JobListing
        fields = ['title', 'description', 'address', 'customer']

    def __init__(self, user, *args, **kwargs):
    super(JobListingForm, self).__init__(*args, **kwargs)
    self.fields['address'].queryset = Address.objects.filter(user=user)

in your views file

def create_listing(request):
    user = request.user
    form = JobListingForm(user, request.POST or None) #pass request.user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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