python - 如何在python django中获取和保存页面中最近元素的数据
问题描述
我需要在 django python 的主页上添加评论模块 - 每个帖子下的简单文本区域。在将其保存在表单中之前,我需要获取最近的帖子 ID,以便我的评论知道与哪个帖子相关。
我的表格.py
class newPost(forms.ModelForm):
class Meta:
model = Post
exclude = ['author', 'date_posted']
fields = ('content', 'date_posted', 'author')
class newComment(forms.ModelForm):
class Meta:
model = Comment
exclude = ['author', 'date', 'post']
fields = ('content', 'date', 'author', 'post')
我的观点.py
def home(request):
newPostForm = newPost()
newCommentForm = newComment()
if request.is_ajax():
newPostForm = newPost(request.POST)
newCommentForm = newComment(request.POST)
if newPostForm.is_valid():
instance = newPostForm.save(commit=False)
instance.author = request.user
instance.date_posted = timezone.now()
instance.save()
data = {
'message': 'post is added'
}
return JsonResponse(data)
if newCommentForm.is_valid():
instance = newCommentForm.save(commit=False)
instance.author = request.user
instance.date = timezone.now()
instance.save()
data = {
'message': 'comment is added'
}
return JsonResponse(data)
context = {
'newPostForm': newPostForm,
'newCommentForm': newCommentForm,
'posts': Post.objects.all().order_by('-date_posted'),
'comments': Comment.objects.all().order_by('-date_posted')
}
和我的 home.html
<div class="leftcolumn">
<div class="new_post_form">
<form METHOD="POST" class="new_post" id="new_post">
{% csrf_token %}
{{ newPostForm }}
<button type="submit">Publish</button>
</form>
</div>
<div id="posts">
{% for post in posts %}
<div class="container">
<a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }}
<img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}" style="width:100%;">
<p>{{ post.content }}</p>
{% for comment in post.comments.all %}
<div class="comment">
<p>{{ comment.content }}</p>
<form METHOD="POST" class="new_comment" id="new_commentt">
{% csrf_token %}
{{ newCommentForm }}
</form>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</div>
我什至不知道从什么开始......我正在考虑将这个帖子 ID 放入请求中的 javascript,但我不知道如何。你可以帮帮我吗?
解决方案
request.is_ajax():
执行此指令:如果if request.method == 'POST':
推荐阅读
- javascript - TypeScript 解构对象数组,包括第一个对象和其中的值
- reactjs - React-Autosuggest,使用 Yup 进行验证
- powerbi - 是否可以在 SSAS 表格模型中分离命名和标识符或使用别名?
- php - 通过 WooCommerce 3+ 中特定类别的挂钩更改产品价格
- python - 检查字符串变量列表是一个特定的字符串
- delphi - 如何从 Virtual Listview 获取 OnData 索引的范围
- ssl-certificate - 如何在 Azure 数据工厂的复制数据活动中传递 SSL 证书以从 Rest Api 检索数据?
- swift - 通过另一个数组过滤(可编码)数组
- kotlin - 无法创建可变同步 TreeMap
- android - 在 EditText Android 中插入的右对齐字符串,未按预期显示