简体   繁体   中英

Filtering Data Based On Foreign Key - Django

I am having an issue dynamically populating form data based on the previous selected field. In my case I have two models one which contains different types of memberships associated to different clubs. Then I have another model which handles registrations for individual clubs.

My problem - when the end-user is ready to sign up the form renders (I already filter out members based on the club they originally selected) but I need to filter the price based on the membership selected (foreign key) of player model.

Below is my model for the membership types:

Model to store clubs available memberships so members can select and pay on registration page

class ClubMemberships(models.Model):

club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
title = models.CharField(max_length=30, default='')
price = models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
description = models.TextField()

def __str__(self):
    return self.title

Here is the model for the registration:

Model to store player information to be used for membership registration

class Player(models.Model):

club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
membership_title = models.ForeignKey(ClubMemberships, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
dob = models.DateField(max_length=8)
email = models.EmailField(max_length=50)
phone = models.CharField(max_length=12)
mobile = models.CharField(max_length=15)
emergency_contact_name = models.CharField(max_length=40)
emergency_contact_mobile = models.CharField(max_length=15)
address1 = models.CharField(max_length=30)
address2 = models.CharField(max_length=30, default='')
address3 = models.CharField(max_length=30, default='')
town = models.CharField(max_length=30)
county = models.CharField(max_length=30)
country = models.CharField(max_length=30)

def __str__(self):
    return "%s %s" % (self.first_name, self.last_name)

Form for player registration:

Form to accept details for members to register

class PlayerRegistrationForm(forms.ModelForm):

class Meta:
    model = Player
    fields = '__all__'
    labels = {
        'dob': 'Date of Birth'
    }
    widgets = {
        'dob': forms.DateInput(attrs={'id': 'datepicker'})
    }

def __init__(self, *args, **kwargs):
    super(PlayerRegistrationForm, self).__init__(*args, **kwargs)
    self.fields['club_id'].widget = forms.HiddenInput()

def load_price(self, request):
    membership = request.GET.get('membership_title')
    title = ClubMemberships.objects.filter(title=membership)
    self.fields['price'].queryset = ClubMemberships.objects.filter(price=title.price)

The load_price is an example of what I am trying to accomplish but cannot get it working. I want the form to check the membership selected in the form then filter the price of that membership and display it in the form.

Here is my form in the browser:

Form

Would really appreciate any help as I cannot incorporate PayPal until I can correctly display the price.

Thanks

This is an example based on car manufacturer and models.

This javascript is looking for when a manufacturer changes in the dropdown list

$("#id_car_make").change(function () {
    var url = $("#searchForm").attr("data-models-url");  // get the url of the `load_cities` view
    var carMakeId = $(this).val();  // get the selected country ID from the HTML input

    $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
            'car_make': carMakeId       // add the country id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_cities` view function
            $("#id_car_model").html(data);  // replace the contents of the city input with the data that came from the server
        }
    });

});

it calls this url

    path('ajax/load-models/', views.load_models, name="ajax_load_models"),

which calls this view

def load_models(request):
    car_make_id = request.GET.get('car_make')
    car_models = CarModel.objects.filter(car_make_id=car_make_id).order_by('name')
    return render(request, 'leases/partials/car_model_dropdown_list_options.html', {'car_models': car_models})

which uses this template to pass the model drop down to the javascript

    <option value="">Model</option>
    {% for car_model in car_models %}
    <option value="{{ car_model.pk }}">{{ car_model.name }}</option>
    {% endfor %}

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