英文:
Why does database receive no data on a successful Django POST?
问题
我在提交表单时会收到一个成功的302重定向POST请求,但数据不会填入数据库。我试图创建一个简单的评论发布。获取评论,提交评论,重定向到上一页('lists'页面),显示新的评论 - 这相当简单 - 但我无法弄清楚为什么数据库中没有任何数据。
我正在使用postgres后端
models.py
class TicketComment(models.Model):
ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE)
technician = models.ForeignKey(TechnicianUser, on_delete=models.CASCADE)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s -%s' % (self.ticket.name, self.ticket)
forms.py
class TicketCommentAddForm(forms.ModelForm):
class Meta:
model = TicketComment
fields = '__all__'
urls.py
# Support Tickets
path("support-tickets/list", view=apps_tickets_list_view, name="tickets.list"),
path("support-tickets/edit/<str:pk>", view=apps_tickets_edit_view, name="tickets.edit"),
path("support-tickets/delete/<str:pk>", view=apps_tickets_delete_list_view, name="tickets.delete_list"),
path("support-tickets/details/<str:pk>", view=apps_tickets_details_view, name="tickets.details"),
path("support-tickets/details/<str:pk>/comment", view=apps_tickets_comments_view, name="tickets.comments"),
views.py
def apps_tickets_comments_view(request,pk):
tickets = TicketList.objects.get(pk=pk)
comments = TicketComment.objects.all()
context = {"tickets": tickets, "comments": comments}
if request.method == "POST":
form = TicketCommentAddForm(request.POST or None, request.FILES or None, instance=tickets)
if form.is_valid():
form.save()
print(form.cleaned_data['technician'])
messages.success(request, "Comment inserted Successfully!")
return redirect("apps:tickets.list")
else:
print(form.errors)
messages.error(request, "Something went wrong!")
return redirect("apps:tickets.list")
return render(request, 'apps/support-tickets/apps-tickets-details.html', context)
ticket-details.html
<form action="{% url 'apps:tickets.comments' tickets.identifier %}" method="POST" enctype="multipart/form-data" class="mt-3">
{% csrf_token %}
{{ form.as_p }}
<div class="row g-3">
<div class="col-lg-12">
<label for="bodyTextarea1" class="form-label">Leave a Comment</label>
<textarea class="form-control bg-light border-light" id="bodyTextarea1" rows="3" placeholder="Enter comment" name="body"></textarea>
<input name="technician" type="hidden" name="technician" value="{{user.pk}}">
<input name="ticket" type="hidden" value="{{tickets.pk}}">
</div>
<div class="col-lg-12 text-end">
<button type="submit" class="btn btn-success" id="add-btn">Post Comment</button>
</div>
</div>
</form>
我确保了method=POST
,在HTML中有一个name
属性,并且甚至可以在控制台中打印出表单数据,但无法将其保存到数据库中。我忽略了什么?
编辑:
我尝试使用Postman,结果仍然相同...我设置了CSRF,GET和POST请求都返回200。我可以打印出表单数据(技术人员姓名)...我快要疯了。
英文:
I am getting a successful 302 redirect POST when submitting my form, but data is not populating in the database. I am trying to create a simple comments post. Take the comment, submit it, redirect to the one page back ('lists'), display new comments - fairly straightforward - but I cannot figure out why I am not getting any data in the database
I am using a postgres backend
models.py
class TicketComment(models.Model):
ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE)
technician = models.ForeignKey(TechnicianUser, on_delete=models.CASCADE)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s -%s' % (self.ticket.name, self.ticket)
forms.py
class TicketCommentAddForm(forms.ModelForm):
class Meta:
model = TicketComment
fields = '__all__'
urls.py
# Support Tickets
path("support-tickets/list", view=apps_tickets_list_view, name="tickets.list"),
path("support-tickets/edit/<str:pk>", view=apps_tickets_edit_view, name="tickets.edit"),
path("support-tickets/delete/<str:pk>", view=apps_tickets_delete_list_view, name="tickets.delete_list"),
path("support-tickets/details/<str:pk>", view=apps_tickets_details_view, name="tickets.details"),
path("support-tickets/details/<str:pk>/comment", view=apps_tickets_comments_view, name="tickets.comments"),
views.py
def apps_tickets_comments_view(request,pk):
tickets = TicketList.objects.get(pk=pk)
comments = TicketComment.objects.all()
context = {"tickets":tickets,"comments":comments}
if request.method == "POST":
form = TicketCommentAddForm(request.POST or None,request.FILES or None,instance=tickets)
if form.is_valid():
form.save()
print(form.cleaned_data['technician'])
messages.success(request,"Comment inserted Successfully!")
return redirect("apps:tickets.list")
else:
print(form.errors)
messages.error(request,"Something went wrong!")
return redirect("apps:tickets.list")
return render(request,'apps/support-tickets/apps-tickets-details.html',context)
ticket-details.html
<form action="{% url 'apps:tickets.comments' tickets.identifier %}" method="POST" enctype="multipart/form-data" class="mt-3">
{% csrf_token %}
{{ form.as_p }}
<div class="row g-3">
<div class="col-lg-12">
<label for="bodyTextarea1" class="form-label">Leave a Comment</label>
<textarea class="form-control bg-light border-light" id="bodyTextarea1" rows="3" placeholder="Enter comment" name="body"></textarea>
<input name="technician" type="hidden" name="technician" value="{{user.pk}}">
<input name="ticket" type="hidden" value="{{tickets.pk}}">
</div>
<div class="col-lg-12 text-end">
<button type="submit" class="btn btn-success" id="add-btn">Post Comment</button>
</div>
</div>
</form>
I have made sure that method=POST
, I have a name
attribute in html, and can even print form data back in the console, but cannot get it in database. What am I overlooking?
EDIT
I took the route to try postman and still same thing... I set up CSRF, have a 200 on the GET and POST request. I can print back form data (tech name).... I am losing my marbles
答案1
得分: 1
你正在将 tickets.identifier
传递到你的URL中,但我看不到这是一个任何地方的值,这意味着你有一个无效的URL。
此外,对于这种问题,我建议从表单外部单独测试视图(编写一个测试用例,或者使用Postman或类似工具),这样更容易知道哪个部分出了问题。
第二个选项:
你的URL名称有点奇怪。尝试在 urls.py
中设置 app_name
,而不是强制命名为 tickets.something
,然后你的URL名称可以只是 list
、edit
、comments
等等,你的URL快捷方式将是 tickets:comments
。
在这里查看有关 app_name
的更多信息:https://docs.djangoproject.com/en/4.2/topics/http/urls/#url-namespaces-and-included-urlconfs
英文:
You're passing tickets.identifier
to your url, but I can't see that this is a value anywhere, which means you have an invalid url.
<form action="{% url 'apps:tickets.comments' tickets.identifier %}"
Also, for this kind of issue, I suggest testing the view seperately from the form (write a test case, or use postman or something), so it's easier to know which part is going wrong.
2nd option:
Your url name is a little odd. Try setting app_name
in the urls.py
instead of forcing your names to be tickets.something
as you are.
Then your url names can be just list
, edit
, comments
etc. and your url shortcut would be tickets:comments
.
See here for more info on app_name
: https://docs.djangoproject.com/en/4.2/topics/http/urls/#url-namespaces-and-included-urlconfs
答案2
得分: 0
应该是:
if request.method == "POST":
form = TicketCommentAddForm(request.POST or None, request.FILES or None)
if form.is_valid():
英文:
The form was the line... I was referencing the instance tickets
but this is the comments model.
if request.method == "POST":
form = TicketCommentAddForm(request.POST or None,request.FILES or None,instance=tickets)
if form.is_valid():
Should be
if request.method == "POST":
form = TicketCommentAddForm(request.POST or None,request.FILES or None)
if form.is_valid():
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论