首页 > 解决方案 > 如何将参数传递给视图函数

问题描述

我正在阅读一本关于 Django 的书,并blog使用以下文件查看此示例:

views.py

def post_share(request, post_id):
    # Retrieve post by id
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False

    if request.method == 'POST':
        # Form was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # Form fields passed validation
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = f"{cd['name']} recommends you read {post.title}"
            message = f"Read {post.title} at {post_url}\n\n" \
                      f"{cd['name']}\'s comments: {cd['comments']}"
            send_mail(subject, message, 'admin@myblog.com', [cd['to']])
            sent = True

    else:
        form = EmailPostForm()
    return render(request, 'blog/post/share.html', {'post': post,
                                                    'form': form,
                                                    'sent': sent})

urls.py

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

    path('<int:post_id>/share/', views.post_share, name='post_share'),

]

template

{% extends "blog/base.html" %}

{% block title %}Share a post{% endblock %}

{% block content %}
  {% if sent %}
    <h1>E-mail successfully sent</h1>
    <p>
      "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}.
    </p>
  {% else %}
    <h1>Share "{{ post.title }}" by e-mail</h1>
    <form method="post">
      {{ form.as_p }}
      {% csrf_token %}
      <input type="submit" value="Send e-mail">
    </form>
  {% endif %}
{% endblock %}

我正在努力理解参数是如何post_id传递到views.py. 我看到它出现在urls.py路径中,但无法理解它是如何通过的。

如果有人可以指出一些相关的文件来阅读这个?谢谢。

标签: djangodjango-viewsdjango-templates

解决方案


推荐阅读