Reputation: 3
I have a list of Hospitals on a web page and each Hospital has a link with it that should open a new page which shows all the reviews and feedbacks that people fill in the feedback form. The problem is that the list goes on for about 70-80 hospitals and creating a URL and a view for each one is a very tiring and long job. Also the number of hospitals may vary later on and then that new entry would require a new URL and view. I want to know if there's any easy way to create those 80 URLs without having to actually create even those 80 URLs (like maybe a loop or something). I'm very new to Django, Python and HTML so an easily understandable way is much appreciated. I'm using PyCharm community and Python 3 for this project. Thank you.
Upvotes: 0
Views: 51
Reputation: 9097
See Django URL dispatcher. You can define a single URL with a pattern in it. For example, the pattern could be pk of the Hospital
instance.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('reviews/<int:hospital_pk>/', views.hospital_reviews, name='hospital-reviews'),
]
models.py
from django.db import models
class Hospital(models.Model):
name = models.CharField(max_length=255)
class Review(models.Model):
hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE)
views.py
from django.shortcuts import render
from .models import Hospital
def hospital_reviews(request, hospital_pk):
hospital = Hospital.objects.get(pk=hospital_pk)
return render(request, 'reviews.html', {'reviews': hospital.review_set.all()})
Upvotes: 2