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>
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')
Related
I am totally new to Django, but currently I want to deploy my model.
I am working on a Django project where users should be able to upload one image using Dropzone.js. Althoung I don't want to save these files anywhere, just have it for further processing with ML.
I want to replace current ImageUploadForm to have dropzone for one image on website,
Current views.py:
import base64
import io
import json
import os
from PIL import Image
from django.shortcuts import render
from .forms import ImageUploadForm
import matplotlib.pyplot as plt
from io import StringIO
def index(request):
image_uri = None
graph = None
quantity = 0
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
image = form.cleaned_data.get('image')
#some image processing
else:
form = ImageUploadForm()
context = {
'form': form,
'image_uri': image_uri,
'quantity': quantity,
'graph': graph
}
return render(request, 'image_classification/index.html', context)
Current index.html:
<!DOCTYPE html>
<html lang="en">
<style>
body {
width: 100% !important;
margin: 0 auto;
background-color:DarkGray !important;
text-align: center !important;
}
</style>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</head>
<body>
<br>Uploaded images are not saved.</p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% if image_uri is not None %}
<div class="alert" role="alert">
quantity: <b>{{ quantity }}</b>
</div>
{{ graph|safe }}
{% endif %}
</body>
</html>
and current forms.py:
from django import forms
class ImageUploadForm(forms.Form):
image = forms.ImageField()
Only tutorials I found show how to upload multiple files to directory using Dropzone.js
I am quite new in Django and stuck at specific point. I want to take user input from html that goes into database, process it with specific python script and return result to the same html page.
I want Users to enter score in "exam_score" line, then process that input with specific python script and then to output result to "uni_name_1_result". For now, python script that just prints 'Hello world' is enough, just want to understand the mythology of how it can be done.
Would appreciate any help.
models.py
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=254,unique=True)
exam_score = models.FloatField(null=True, validators=[MinValueValidator(0.0),MaxValueValidator(700)])
uni_name_1 = models.CharField(max_length=254)
uni_name_1_result = models.CharField(max_length=254)
forms.py
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = '__all__'
views.py
from django.shortcuts import render
# from ielts_app import forms
from ielts_app.forms import NewUserForm
# from django.http import HttpResponseRedirect
def index(request):
return render(request,'ielts_app/index.html')
def users(request):
form = NewUserForm()
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
variable:form.cleaned_data
form.save(commit=True) # to save forum data (user data), commit=True to database
# return HttpResponseRedirect('/THANKS/')
return index(request) # return back to homeage after getting user data
else:
print("ERROR!")
return render(request,'ielts_app/users.html',{'form':form})
users.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
You can do following way.
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = ('exam_score',)
And in your user.html do this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{% for field in form %}
{{ form.as_p }}
{{ field }}
{% endfor %}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
It is better you rename your model to some other model name as it may collide with User Model given by django.
Hi Everyone i want to go on detail view but i get this error while paste the url
NoReverseMatch at /
Reverse for 'test' with no arguments not found. 1 pattern(s) tried: ['test/(?P<pk>[0-9]+)/$']
Here is my Models.py
from django.db import models
# Create your models here.
class article(models.Model):
Title = models.CharField(max_length=200)
Content = models.CharField(max_length=1000)
Here is my Views.py
from django.shortcuts import render
from django.views.generic import (ListView,DetailView)
from .models import *
# Create your views here.
class Article(ListView):
model = article
class Test(DetailView):
model = article
Here is my Urls.py
from django.contrib import admin
from django.urls import path
from cbs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Article.as_view(),name="Article"),
path('test/<int:pk>/', views.Test.as_view(),name="test"),
]
Here is my Article_list.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for article in article_list %}
<h1>{{ article.Title }}</h1>
{% endfor %}
</body>
</html>
in your Article_list.html file you must change the href attribute on a tag to:
<h1>{{ article.Title }}</h1>
to send id as parameter to the below url:
path('test/<int:pk>/', views.Test.as_view(),name="test"),
I am trying to create an addform to take input from a user and add it to my model, however, the form is not showing on the page, can someone tell me what I am doing wrong? Here is the code for the forms.py, views.py and add.html:
forms.py
class AddForm(forms.Form):
vehicle = forms.CharField(max_length=10)
carrier = forms.FloatField()
location = forms.ChoiceField(choices=[(1, 'Mathura Installation')])
customer_code = forms.FloatField()
zone = forms.ChoiceField(choices=[('NW', 'North West'),
('NCR', 'North Central'),
('SCR', 'South Central'),
('S', 'South'), ('N', 'North'),
('W', 'West'), ('E', 'East')
])
quantity = forms.FloatField()
load = forms.FloatField()
rtkm = forms.FloatField(label='RTKM')
rate = forms.ChoiceField(label='Rate ', widget=forms.RadioSelect, choices=[('avg', 'Average Rate'),
('user', 'User Rate')])
views.py
def add(request):
addform = forms.AddForm()
dict = {'addform': addform}
return render(request, 'add.html', dict)
urls.py
from django.contrib import admin
from django.urls import path
from searchapp import views
urlpatterns = [
path('', views.search, name='search'),
path('add/', views.add, name='add'),
path('admin/', admin.site.urls),
]
html - add.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<head>
<meta charset="UTF-8">
<title>Transport Portal - Add Page</title>
</head>
<body>
<div class="header">
<img src="{% static 'images/hpcl_logo.png' %}">
<h1>Transportation Portal</h1>
</div>
<div class="topnav">
<ul>
<li>Home</li>
<li>Search</li>
<li><a class="active" href="add.html">Add</a></li>
</ul>
</div>
<div class="add">
<form method="POST">
{% csrf_token %}
{{ addform.as_p }}
</form>
</div>
</body>
</html>
I think the problem is how you're getting there.
You have the following in your html
<li><a class="active" href="add.html">Add</a></li>
This is going to pick up the html page but you want href="{% url 'add' %}" which will pick up the django url.
Instead of dict use context
def add(request):
addform = forms.AddForm()
context= {'addform': addform}
return render(request, 'add.html', context)
Please read this. context
Very new to django. I would like to have each field in a modelform in a new row on the html page. I've tried to use but that doesn't work. How can I do this? Here is the html I have for the page that displays my form for capturing data:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<table>
<thead><th>{{title}}</th>
{% for record in record_list%}
<tr><td>{{record.county}}</td></tr>
<tr><td>{{record.route}}</td></tr>
<tr><td>{{record.pmb}}</td></tr>
<tr><td>{{record.pme}}</td></tr>
<tr><td>{{record.map_sheet_desc}}</td></tr>
<tr><td>{{record.drawingdate}}</td></tr>
<tr><td>{{record.index_map_filepath}}</td></tr>
<tr><td>{{record.grantor_box_filepath}}</td></tr>
<tr><td>{{record.control_map_filepath}}</td></tr>
<tr><td>{{record.info_sheet_filepath}}</td></tr>
<tr><td>{{record.mapdatum}}</td></tr>
{% endfor %}
</table>
<form method="POST" action="/update/">
<fieldset>
<legend>Create Map Index Record</legend>
{% csrf_token %}
{{form_mapindex}}
<br><button type="submit">Create Record</button>
</fieldset>
</form>
</body>
</html>
And here is the code in my views.py:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
from .models import Mapindex as MapIndexModel
from .forms import MapIndexForm
class MapIndexView(View):
template_name = 'add.html'
def get(self, request):
record_list = []
form_mapindex = MapIndexForm()
records = MapIndexModel.objects.all()[:50]
for record in records:
record_list.append({'county': record.county, 'route': record.route, 'pmb': record.pmb, 'pme': record.pme,
'map_sheet_desc': record.map_sheet_desc, 'drawingdate': record.drawingdate,
'index_map_filepath': record.index_map_filepath, 'grantor_box_filepath': record.grantor_box_filepath,
'control_map_filepath': record.control_map_filepath, 'info_sheet_filepath': record.info_sheet_filepath,
'mapdatum': record.mapdatum})
return render(request, self.template_name, {
'title': 'Map Index Update Form',
'mapindex_list': record_list,
'form_mapindex': form_mapindex
})
def post(self, request):
form_mapindex = MapIndexForm(request.POST)
if form_mapindex.is_valid():
form_mapindex.save()
return HttpResponseRedirect('/update/')
and here is forms.py:
from django import forms
from .models import Mapindex
class MapIndexForm(forms.ModelForm):
class Meta:
model = Mapindex
fields = ['county', 'route', 'pmb', 'pme', 'map_sheet_desc', 'drawingdate', 'index_map_filepath',
'grantor_box_filepath', 'control_map_filepath', 'info_sheet_filepath', 'mapdatum']
You're returning record_list but assigning it to mapindex_list. Either iterate through mapindex_list in the template or change the name in the render function to match:
return render(request, self.template_name, {
'title': 'Map Index Update Form',
'record_list': record_list,
'form_mapindex': form_mapindex
})