django - 如何将参数传递给视图函数
问题描述
我正在阅读一本关于 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
路径中,但无法理解它是如何通过的。
如果有人可以指出一些相关的文件来阅读这个?谢谢。
解决方案
推荐阅读
- slick.js - 非无限自动播放的 Slick Slider (v1.8.0) 问题
- r - 对 238 列重复相同的 3 个命令,df$X1 到 df$X238
- python - 在 python 中对 postgresql 执行多个查询的更快方法
- java - 尝试运行基本的 sse grizzly/jersey 服务器时总是出现相同的警告
- php - 使用魔术常量访问对象属性
- firebase - TypeError: this.f 不是构造函数 | firebase.auth()
- python - AttributeError: 'str' object has no attribute 'descendants' 使用 BeautifulSoup 时出现错误
- java - ListCell 中的 JavaFX 自定义节点