skip to Main Content

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>

Successful 302 with printing data from the form:

No Data In Database...

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

Postman submission with output and DB

2

Answers


  1. Chosen as BEST ANSWER

    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():
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search