1

I am trying to create a Model Form in Django that includes Foreign Key fields from the Athlete Table.

Normally when referring to the Foreign Key fields I can use the field name 'athlete' then.followed by the field name. This does not seem to be working.

I have tried using a queryset using the ModelChoiceField but think I am not setting this up correctly.

Thanks in advance for any help.

This is the main Model (ASP Bookings) including the Foreign Key Athlete

class ASPBookings(models.Model):

asp_booking_ref = models.CharField(max_length=10, default=1)
program_type = models.CharField(max_length=120, default='asp')
booking_date = models.DateField()
booking_time = models.CharField(max_length=10, choices=booking_times)
duration = models.CharField(max_length=10, choices=durations, default='0.5')
street = models.CharField(max_length=120)
suburb = models.CharField(max_length=120)
region = models.CharField(max_length=120, choices=regions, default='Metro')
post_code = models.CharField(max_length=40)
organisation_type = models.CharField(max_length=120,choices=organisation_types, default='Government School')
audience_number = models.CharField(max_length=10)
presentation_form = models.CharField(max_length=120, choices=presentation_form_options, default='Face to Face')
contact_name = models.CharField(max_length=80)
email = models.EmailField()
phone_number = models.CharField(max_length=120)
comments = models.TextField()
status = models.CharField(max_length=80, choices=statuses, default='TBC')
email_sent = models.BooleanField(default=False)
athlete = models.ForeignKey(Athlete, default= '1', on_delete=models.CASCADE)

def __str__(self):
    return self.contact_name

# return URL after the POST has been submitted.
def get_absolute_url(self):
    return reverse('vistours:success')

Athlete Model

class Athlete(models.Model):


athlete_ref = models.CharField(max_length=10, default=1)
athlete_name = models.CharField(max_length=80)
email = models.EmailField()
phone_number = models.CharField(max_length=120)
home = models.CharField(max_length=120)
education = models.CharField(max_length=120)
sport = models.CharField(max_length=120, choices=sports, default='1500m Runner')
notes = models.TextField(default='None')
gender = models.CharField(max_length=120, choices=genders, default='Not Specified')
para_athlete = models.BooleanField(blank=True)
working_with_children = models.BooleanField(blank=True)
expiry_date = models.DateField(blank=True, null=True)
available = models.BooleanField(blank=True)
available_from = models.DateField(blank=True, null=True)
bfbw = models.BooleanField(blank=True)
latest_bfbw_session = models.DateField(blank=True, null=True)
number_bfbw_sessions = models.CharField(blank=True, null=True, max_length=10)
asp = models.BooleanField(blank=True)
latest_asp_session = models.DateField(blank=True, null=True)
number_asp_sessions = models.CharField(blank=True, null=True, max_length=10)
tours = models.BooleanField(blank=True)
latest_tours_session = models.DateField(blank=True, null=True)
number_tours_sessions = models.CharField(blank=True, null=True, max_length=10)

def __str__(self):
    return self.athlete_name

# return URL after the POST has been submitted.
def get_absolute_url(self):
    return reverse('home')

**Below is the form I have tried to create, I need the form to show the following fields. asp_booking_ref, program_type, athlete id, athlete_name.) I am trying to display these as widgets as well but when trying to add this only the asp_booking_ref and program_type fields shows.

class ASPAssignAthleteForm(forms.ModelForm):
athlete = forms.ModelChoiceField(queryset=Athlete.objects.all())


class Meta():
    model = ASPBookings
    fields = '__all__'
    widgets = {

            'asp_booking_ref': TextInput(attrs={'id':'booking_id', 'name': 'booking_id'}),
            'program_type': TextInput(attrs={'id': 'program_type', 'name': 'program_type'}),
            
    }



 <!-- Assign ASP Athlete Modal -->
<form method="post" action='assign_athlete/' id="asp_assign_athlete_form">
  {% csrf_token %}
  {{ form.non_field_errors }}

  {{ form.source.errors }}
  {{ form.source }}


  <div class="modal fade" id="asp_assign_athlete_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header card-header">
          <h5 class="modal-title" id="asp_assign_athlete_modal_header" > <i class="fa fa-address-card-o mx-1"></i> Assign athlete</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="card text-dark bg-light mb-3">
            <div class="card-body">
              <div class="btn-group d-grid gap-2" role="group" aria-label="Basic outlined example">
                {% for athlete in ath_data %}
                {% for booking in asp_bookings %}
               
                {% if forloop.first %}
                {% if athlete.available == 1 %}
                
                 <form>
                  {{asp_assign_athlete_form.asp_booking_ref}}
                  {{asp_assign_athlete_form.program_type}}
                  {{asp_assign_athlete_form.athlete_name}}
                  {{asp_assign_athlete_form.athlete.id}}
                  {{asp_assign_athlete_form.athlete_id}}
                    <input type="submit" name="submit" value="{{athlete.athlete_name}}" class="btn btn-outline-primary w-100">
                    <input class="booking_id " type="text" name="booking_id" value="{{booking.id}}">
                    <input class="" type="text" name="program_type" value="{{booking.program_type}}">
                    <input class="" type="text" name="athlete_id" value="{{booking.athlete_id}}">
                    <input class="" type="text" name="athlete_ref" value="{{athlete.id}}">



                  </form>
                
          
                <!-- <a href="{% url 'vistours:assign_athlete' id=booking.id program_type=booking.program_type athlete_id=booking.athlete_id ath_id=athlete.id %}" class="data-vis-booking btn btn-outline-primary" data-vis-booking="{{booking.id}}">{{athlete.athlete_name}}</a> -->

          
                {% endif %}
                {% endif %}
                {% endfor %}
                {% endfor %}
              

            

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>
<!-- END Assign ASP Athlete Modal -->

VIEW CODE (Assigning Athlete - Process)

def assign_athlete(request, id, program_type, athlete_id, ath_id):

    if request.method == 'POST':
        booking_id = request.POST.get('booking_id')
        asp_data = ASPBookings.objets.get(id=booking_id)
        asp_data.athlete_id = request.POST.get('athlete_ref')
        print(booking_id)
        print(athlete_ref)
        asp_data.save()

    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

VIEW CODE for Page

class admin_booking(View):
def get(self, request):

    # check whether the user is logged in.
    context = initialize_context(request)
    token = get_token(request)
    session = request.session
    if session.get('user') == None:
        return redirect('vistours:signin')

    # get the model data.
    asp_data = ASPBookings.objects.all()
    bfbw_data = BFBWBookings.objects.all()
    tour_data = SchoolTourBookings.objects.all()
    ath_data = Athlete.objects.all()

    # add the model data to a context dictionary
    context = {
            'asp_bookings': asp_data,
            'bfbw_bookings': bfbw_data,
            'tour_bookings': tour_data,
            'ath_data': ath_data,
            'ath_form': AthleteForm(),
            'asp_form': ASPBookingsForm(),
            'edit_asp_form': EditASPBookingsForm(),
            'bfbw_form': BFBWBookingsForm(),
            'edit_bfbw_form': EditBFBWBookingsForm(),
            'tours_form': SchoolTourBookingsForm(),
            'edit_tours_form': EditSchoolTourBookingsForm(),
            'asp_assign_athlete_form': ASPAssignAthleteForm(),
           
        }

    # Check for completed bookings
    completed_bookings(request)


    # Serialise the data to JSON output file.
    with open("vistours/static/vistours/json/asp.json", "w") as out:
        json_serializer = serializers.get_serializer('json')()
        json_serializer.serialize(asp_data, stream=out, indent=4)

    with open("vistours/static/vistours/json/bfbw.json", "w") as out:
        json_serializer = serializers.get_serializer('json')()
        json_serializer.serialize(bfbw_data, stream=out, indent=4)

    with open("vistours/static/vistours/json/tours.json", "w") as out:
        json_serializer = serializers.get_serializer('json')()
        json_serializer.serialize(tour_data, stream=out, indent=4)

    with open("vistours/static/vistours/json/athlete.json", "w") as out:
        json_serializer = serializers.get_serializer('json')()
        json_serializer.serialize(ath_data, stream=out, indent=4)
    
    return render(request, 'vistours/admin_bookings.html', context)
Mark
  • 135
  • 1
  • 12
  • 1
    Can you add your template code as well when you display the form? Also, have you tried removing your athlete declaration in the model form and setting `fields = ['asp_booking_ref', 'program_type', 'athlete']` to see if it works? – getup8 Jul 01 '21 at 04:20
  • Thanks getup8, Just tried that but the fields still do not display. Would I need to then add the athlete fields as widgets as athlete.athlete_name? Also added the template code above. – Mark Jul 01 '21 at 04:49
  • You should probably add your view code as well.. (and maybe fix the formatting). In the template, did you try just putting `{{ form }}` and seeing if it outputs properly? – getup8 Jul 01 '21 at 05:36
  • Just added my view code. Essentially what we are trying to do is too to first filter down the ASPBooking using the Booking ID and then change the athlete_id (Foreign Key) with the Athlete ID of the available athlete. I hope I am not confusing this, but the program will allow us to change an athlete we have assigned to the booking to a new athlete using this process. – Mark Jul 01 '21 at 07:03

1 Answers1

0

Thanks for the help, we managed to resolve this issue using JQuery to alter the submit button link to add the values we needed.

Mark
  • 135
  • 1
  • 12