Tizu
Tizu

Reputation: 25

How to pass a pk of an object to a template form

the scenario is as follows: objects: race, racers, registration I am trying to use a form to offer users the possibility to register to race.

models:

class registration(models.Model):
    STATUS = [
    ('Registered','Registered'),
    ('Confirmed','Confirmed'),
    ]
    race_id = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='rrace')
    racer_id = models.ForeignKey(Racer, on_delete=models.CASCADE, related_name='rracer')
    registration_date = models.DateTimeField(auto_now_add=True)
    medals = models.BooleanField(default=False, help_text="do you wish it?")
    registration_status = models.CharField(choices=STATUS, default='Registered', max_length=15)

forms:

 class RegisterRace(forms.ModelForm):
    class Meta:
        model = registration
        fields = ("race_id", "racer_id"")

url:

path('register-race/', views.race_register, name='race_register'),

views:

def race_register(request):
    if request.method == "POST":
        c = request.POST.get('race') # this line is ONLY for debugging
        race = Race.objects.get(pk=request.POST.get('race'))
        form = RegisterRace(request.POST)
        if form.is_valid():
            form.save()
            return redirect('races')
    else:
        form = RegisterRace()
    return render(request, 'race_registration.html', {'form': form, 'rc': race})

race_detail template contain the following link :

<form action="/register-race/" method="POST">{% csrf_token %}
   <input type="hidden" name="race" value="{{event.pk}}"> # where event is the current race 
   <input type="submit"  value="REGISTRATION" class="btn btn-large btn-primary">
</form>

race_registration.html template contain:

<form action="/register-race/" method="POST" enctype="multipart/form-data" class="form-horizontal">{% csrf_token %}
        <input type = "hidden" name = "race_id" value="{{rc.pk}}"> # for debugging purpose here I have also tried with value="{{c}}"
        <input type = "hidden" name = "racer_id" value="{{request.user.pk}}">
        <button type="submit" class="btn btn-primary">REGISTER MYSELF</button>
</form>

When I hit the Registration button the following error occurs:

DoesNotExist at /register-race/ Race matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/register-race/ Django Version: 3.0.2 Exception Type: DoesNotExist Exception Value:
Race matching query does not exist. Exception Location: C:\Users-----\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py in get, line 415

Traceback:

..race\views.py in register-race
        race = Race.objects.get(pk=request.POST.get('race')) …
▼ Local vars
Variable    Value
c           None
request     <WSGIRequest: POST '/register-race/'>

Regardless of the above in the template race_registration.html I have put:

Register to race {{race.race_type}} which have the id {{race.pk}}

and the render is as expected -- Register to race INDIANAPOLIS 2020 which have the id 19

Therefore, I do not understand where is the mistake and why the form cannot receive the right value ...

Upvotes: 0

Views: 676

Answers (1)

Tartempion34
Tartempion34

Reputation: 602

I think you make it really complicated for nothing. Why using forms?

Why not doing this:

urls.py

path('register-race/<race_id>', views.race_register, name='race_register'),

race_detail_template

<a href="{%url 'race_register' race_id=event.pk %}">Register me on this race</a>

view

def race_register(request, race_id):
    try:
        race = Race.objects.get(pk=race_id)
        race.rracers.add(your_racer_object)
    except Race.DoesNotExist:
        #deal with the problem
    return redirect(wereveryouwant)

Upvotes: 1

Related Questions