To pass a parameter through a URL in Django, you can use URL patterns with placeholders. Here's an example:

  1. In your urls.py file, define a URL pattern with a placeholder:
from django.urls import path
from . import views

urlpatterns = [
    path('article/<int:pk>/', views.article_detail, name='article_detail'),
]

In this example, the URL pattern is article/<int:pk>/, where <int:pk> is a placeholder for an integer value. The article_detail view function will handle requests to this URL pattern.

  1. In your view function, use the parameter passed in the URL:
from django.shortcuts import render, get_object_or_404
from .models import Article

def article_detail(request, pk):
    article = get_object_or_404(Article, pk=pk)
    return render(request, 'article_detail.html', {'article': article})

In this example, the pk parameter is passed to the article_detail view function as an argument. It is then used to retrieve the corresponding Article object from the database using the get_object_or_404 shortcut function.

  1. In your template, use the parameter passed in the view function:
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>

In this example, the article object passed from the view function is used to display the title and content of the article in the template.

  1. Finally, to generate a URL with the parameter, use the url template tag:
<a href="{% url 'article_detail' pk=article.pk %}">{{ article.title }}</a>

In this example, the url template tag generates a URL for the article_detail view function with the pk parameter set to the pk attribute of the article object. This URL can be used in a link to the article detail page.

django pass param through url

原文地址: http://www.cveoy.top/t/topic/bcIM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录