数据库为什么在成功的Django POST请求时没有收到数据?

huangapple go评论99阅读模式
英文:

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 &#39;%s -%s&#39; % (self.ticket.name, self.ticket)

forms.py

class TicketCommentAddForm(forms.ModelForm):
    class Meta:
        model = TicketComment
        fields = &#39;__all__&#39;

urls.py

    # Support Tickets
    path(&quot;support-tickets/list&quot;, view=apps_tickets_list_view, name=&quot;tickets.list&quot;),
    path(&quot;support-tickets/edit/&lt;str:pk&gt;&quot;, view=apps_tickets_edit_view, name=&quot;tickets.edit&quot;),
    path(&quot;support-tickets/delete/&lt;str:pk&gt;&quot;, view=apps_tickets_delete_list_view, name=&quot;tickets.delete_list&quot;),
    path(&quot;support-tickets/details/&lt;str:pk&gt;&quot;, view=apps_tickets_details_view, name=&quot;tickets.details&quot;),
    path(&quot;support-tickets/details/&lt;str:pk&gt;/comment&quot;, view=apps_tickets_comments_view, name=&quot;tickets.comments&quot;),

views.py

def apps_tickets_comments_view(request,pk):
    tickets = TicketList.objects.get(pk=pk)
    comments = TicketComment.objects.all()
    context = {&quot;tickets&quot;:tickets,&quot;comments&quot;:comments}
    if request.method == &quot;POST&quot;:
        form = TicketCommentAddForm(request.POST or None,request.FILES or None,instance=tickets)
        if form.is_valid():
            form.save()
            print(form.cleaned_data[&#39;technician&#39;])
            messages.success(request,&quot;Comment inserted Successfully!&quot;)
            return redirect(&quot;apps:tickets.list&quot;)
            
        else:
            print(form.errors)
            messages.error(request,&quot;Something went wrong!&quot;)
            return redirect(&quot;apps:tickets.list&quot;)
            
    return render(request,&#39;apps/support-tickets/apps-tickets-details.html&#39;,context)

ticket-details.html

&lt;form action=&quot;{% url &#39;apps:tickets.comments&#39; tickets.identifier %}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; class=&quot;mt-3&quot;&gt;
                                            {% csrf_token %}
                                            {{ form.as_p }}
                                            &lt;div class=&quot;row g-3&quot;&gt;
                                                &lt;div class=&quot;col-lg-12&quot;&gt;
                                                    &lt;label for=&quot;bodyTextarea1&quot; class=&quot;form-label&quot;&gt;Leave a Comment&lt;/label&gt;
                                                    &lt;textarea class=&quot;form-control bg-light border-light&quot; id=&quot;bodyTextarea1&quot; rows=&quot;3&quot; placeholder=&quot;Enter comment&quot; name=&quot;body&quot;&gt;&lt;/textarea&gt;
                                                    &lt;input name=&quot;technician&quot; type=&quot;hidden&quot; name=&quot;technician&quot; value=&quot;{{user.pk}}&quot;&gt;
                                                    &lt;input name=&quot;ticket&quot; type=&quot;hidden&quot; value=&quot;{{tickets.pk}}&quot;&gt;
                                                &lt;/div&gt;
                                                &lt;div class=&quot;col-lg-12 text-end&quot;&gt;
                                                    &lt;button type=&quot;submit&quot; class=&quot;btn btn-success&quot; id=&quot;add-btn&quot;&gt;Post Comment&lt;/button&gt;
                                                &lt;/div&gt;
                                            &lt;/div&gt;
                                        &lt;/form&gt;

数据库为什么在成功的Django POST请求时没有收到数据?

数据库为什么在成功的Django POST请求时没有收到数据?

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

数据库为什么在成功的Django POST请求时没有收到数据?

答案1

得分: 1

你正在将 tickets.identifier 传递到你的URL中,但我看不到这是一个任何地方的值,这意味着你有一个无效的URL。

此外,对于这种问题,我建议从表单外部单独测试视图(编写一个测试用例,或者使用Postman或类似工具),这样更容易知道哪个部分出了问题。

第二个选项:

你的URL名称有点奇怪。尝试在 urls.py 中设置 app_name,而不是强制命名为 tickets.something,然后你的URL名称可以只是 listeditcomments 等等,你的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.

&lt;form action=&quot;{% url &#39;apps:tickets.comments&#39; tickets.identifier %}&quot;

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 == &quot;POST&quot;:
        form = TicketCommentAddForm(request.POST or None,request.FILES or None,instance=tickets)
        if form.is_valid():

Should be

    if request.method == &quot;POST&quot;:
        form = TicketCommentAddForm(request.POST or None,request.FILES or None)
        if form.is_valid():

huangapple
  • 本文由 发表于 2023年5月29日 08:50:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定