Home > Software engineering >  Displaying Comment Form in Django 401 Error
Displaying Comment Form in Django 401 Error

Time:08-24

I am trying to build a CRM in Django and in doing so I am trying to add a place to add comments to a lead. I created a form and upon submitting a comment I get directed to the 401 page where I am greeted with an error. On the 401 page it references my form.save() in my views. Please help.

401 Error

"Field 'id' expected a number but got 'some'."

. I will post my code below

Below is my info view which is used to display information about a particular lead

def info(request, pk):
info = lead.objects.get(id=pk)

form = lead_comment()
if request.method == 'POST':
    form = lead_comment(request.POST)
    if form.is_valid():
        form.save()
        return redirect('info.html')
        
context={'info':info, 'form': form}
return render(request, 'info.html', context)

My URLS

from django.urls import path
from . import views

urlpatterns = [
    path('', views.dashboard, name='dashboard'),
    path('leads/', views.leadsPage, name='leads'),
    path('docs/', views.docsPage, name='docs'),
    path('add-lead/', views.addLead, name='add-lead'),
path('leads/<str:pk>/', views.info, name='description'),
]

My info.html

{% include 'navbar.html' %}

<body >
    <div >
        <div >
            <div >
                <h2>{{ info.first }} {{ info.last }}</h2>
                <h5>Phone number: {{ info.phnum }}</h5>
                <h5>Email: {{ info.email }}</h5>
            </div>
            <body>
                <form method="POST" action="">
                    {% csrf_token %}
                    {{ form }}
                    <input type = "submit" value = "Submit" />
                </form>
            </body>
        </div>
    </div>
</body>

My lead model where I have am initializing comment

class lead(models.Model):
    first=models.CharField(max_length=20)
    last=models.CharField(max_length=20)
    email=models.CharField(max_length=30)
    phnum=models.CharField(max_length=10)
    associate=models.ForeignKey(agent, on_delete=models.CASCADE, default='some' )
    comment=models.CharField(max_length=500, blank=True, null=True)

    def __str__(self):
        return self.first   ' '   self.last

My Form

class lead_comment(ModelForm):

class Meta:
    model=lead
    fields=['comment']

CodePudding user response:

Try adding the following lines to your info views:

def info(request, pk):
    i = lead.objects.get(id=pk)
    form = lead_comment(instance=i)

    if request.method == 'POST':
        form = lead_comment(request.POST, instance=i)
        if form.is_valid():
            form.save()
            return redirect('info.html')
            
    context={'i':i, 'form': form}
    return render(request, 'info.html', context)
  • Related