Issue
I am an absolute beginner in Django development & I am unable to send the data to my database via the POST method. Please guide me on what is wrong with my approach. My model worked perfectly and I can now access my desired table on my Django admin. The function that I have created in views.py always executes the else condition.
From views.py:
from django.shortcuts import render, HttpResponse, redirect
from app.models import Tbl_Feedback
def myform(request):
return render(request, 'form.html')
def getfeedback(request):
if request == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(a="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
From models.py:
from django.db import models
# Create your models here.
class Tbl_Feedback(models.Model):
fdbk = models.CharField(max_length=120)
From urls.py(app):
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('',views.myform,name="form"),
path('getfeedback', views.getfeedback, name="feedback")
]
From urls.py(project):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("app.urls"))
]
Html:
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
{% load static %}
<link rel="stylesheet" href="{%static 'css.css'%}">
</head>
<body>
<form action="getfeedback" method="post" >
{% csrf_token %}
<div class="frame">
<div class="frame-header">FeedBack Please !</div>
<div class="frame-body">
<div class="form-element">
<div class="element-label"><label for="a">FeedBack</label></div>
<div class="element-controller">
<textarea name="a" id="a" cols="30" rows="5" class="controller-input"
autofocus="autofocus" maxlength="120"></textarea>
</div>
</div>
</div>
<div class="frame-footer"><button type="submit">Submit</button> </div>
</div>
</form>
</body>
</html>
Solution
In your getfeedback view there are two issues.
- You need to write
if request.method == 'POST':
- "a" is not a field in your model
def getfeedback(request):
if request.method == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(fdbk="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
Answered By - yagus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.