Я пытался добавить комментарий в блог, используя метод POST. Я хочу сохранить получить данные методом POST по имени, электронной почте, тексту и сохранить их в базе данных. Кроме того, поле даты должно получить date.now (), а поле блога должно получить блог или идентификатор блога. Код выглядит так -
models.py:
from django.db import models
class Blog......
class Comment(models.Model):
id = models.AutoField(primary_key=True, default=0)
blog = models.ForiegnKey(Blog_tables, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
email = models.EmailField()
Text = models.TextField()
date = models.DateField()
def __str__(self):
return self.Text
views.py
from .models import Blog, Comment
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader, RequestContext
from django.http import HttpResponse, HttpResponseRedirect
def blog_detail(request, blog_id):
blog = get_object_or_404(Blog, pk=blog_id)
return render(request, 'home/detail.html', {'blog': blog})
def post_comment(request, blog_id):
# Here's a post code to be implemented. Please read the commented text
# 'blog' field of models will get the id of the blog
# 'name' field will get the POST method value of input name="name"
# 'email' field will get the POST method value of input name="email"
# 'text' field will get the POST method value of input name="text"
# 'date' will get the current Date
# All the above data will be saved in the database
html template: blog_detail.html
<html>
<body>
<!--...Blog Text Here...-->
<!-- Comment Section -->
<form action="/blogs/{{blog_id}}/comment" method ="post">
{% csrf_token %}
<input type="text" name="name" id="name" placeholder="Enter Your Name"/>
<input type="text" name="email" id="email" placeholder="Enter Your Email"/>
<input type="text" name="comments" id="comments" placeholder="Comments here"/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
Пожалуйста, помогите мне решить проблему.
Структура формы следующая: ![enter image description here](https://i.stack.imgur.com/zAqhk.png)
Пожалуйста, помогите мне получить значение израздел комментариев в макете и сохраните его в базе данных
Я также пробовал это в views.py:
def post_comment(request, blog_id):
if request.method == 'POST':
data = request.POST.get("name", "email", "comment")
# blog = get_object_or_404(Blog_tables, pk=blog_id)
p = Blog_Comment_table(blog= data.name, comment_name=data.email,
comment_email= data.email, comment_Text= data.comment, comment_data =
timezone.now())
p.save()
return HttpResponseRedirect('/thanks/')
else:
return render(request, '/blogs/' + blog_id + '/comment', {'error_message': 'Error'})