gcc
gcc

Reputation: 75

How to pass a variable from a template to a view in Django

I am not able to GET a variable from a template into another view.

I have a table with some records. Each row has a button which I would like to click and retrieve more details about the record in another page. I have been looking online but I cannot figure out how I should implement this. Everything I have tried either crashed or gave back None.

list.html

{% for trainee in trainees_list %}
          <tr>
            <td>{{ trainee.last_name }}</td>
            <td>{{ trainee.first_name }}</td>
            <td><a class="btn btn-primary" href="{% url 'traineedetails'%}" value="{{ trainee.pk }}" >View</a></td>
          </tr>
{% endfor %}

view.py

def traineedetails(request):
    if request.method == 'GET':
        trainee_details = request.POST.get('trainee.pk')
        print(trainee_details)
        return render(request, 'trainee_details.html')

def listoftrainees(request):
    trainees_list = UserTraining.objects.all()
    return render_to_response('list.html', {'trainees_list': trainees_list})

url.py

urlpatterns = [
    path('traineedetails', views.traineedetails, name='traineedetails'),
    path('listoftrainees', views.listoftrainees, name='listoftrainees'),
]

form.py

class UserTrainingForm(forms.ModelForm):

    scope_requirements = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=microscopes.MICROSCOPES)

    class Meta:
        model = UserTraining

        fields = (
        'first_name',
        'last_name',
        )

model.py

class UserTraining(models.Model):
    first_name = models.CharField('first name', max_length = 100)
    last_name = models.CharField('last name', max_length = 100)

I would like to be able to click on the button in the row of the table and retrive more information about the record.

Upvotes: 0

Views: 47

Answers (1)

Ben Boyer
Ben Boyer

Reputation: 1234

You pass the value directly in the url like : traineedetails/<pk>

In the template:

{% for trainee in trainees_list %}
          <tr>
            <td>{{ trainee.last_name }}</td>
            <td>{{ trainee.first_name }}</td>
            <td><a class="btn btn-primary" href="{% url 'traineedetails' trainee.pk%}">View</a></td>
          </tr>
{% endfor %}

Edit your urls.py:

path('traineedetails/<pk>', views.traineedetails, name='traineedetails'),

Then you can retrieve it in your view like this:

from django.shortcuts import get_object_or_404
def traineedetails(request, pk):
    if request.method == 'GET':
        #try to get your objet or throw a 404 error
        trainee = get_object_or_404(UserTraining, pk=pk)
        #pass it back to the template
        return render(request, 'trainee_details.html',{'trainee':trainee})

Upvotes: 4

Related Questions