I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.
Related
1.views.py
from django.shortcuts import render
from . models import User
from .forms import Userform
def Home(request):
if request.method == "POST":
form = Userform(request.POST or None,request.FILES or None)
if form.is_valid():
form.save()
else:
form = Userform()
return render(request,"home.html",{"form":form})
def read(request):
read = User.objects.all()
return render(request,"read.html",{"read":read})
2.models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=12)
rollno = models.IntegerField()
# files = models.FileField()
3.form.py
from django import forms
from .models import User
class Userform(forms.ModelForm):
class Meta:
model = User
fields = ('name','rollno')
urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("",views.Home,name="Home"),
path("read/",views.read, name="read"),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4.home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="read/" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{%block containt%}
{%for i in read%}
{{i.name}}
{{i.rollno}}
{%endfor%}
{%endblock%}
</body>
</html>
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
Problem is in the action of your form, you have entered the wrong URL in the action
You have to put home URL instead of read/, because you are handling your form submission in your home function so replace your form action by this
<form method="POST" action="{% url 'Home' %}" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
I’m trying to write a web app which accepts a website visitor’s input which is a 12 digit “Chuckee Cheese” membership card number and then redacts the first 8 digits and presents the redacted number. I’ve got my template written and the basic logic inside my app’s views.py. The problem now is that after the user enters his or her card number, Django is not processing the user input properly. Like, the redacted number is not being presented and served in the template as intended.
Here is a pic on imgur showing my website running on my dev server now. As you can see in that pic, in the web address bar Django receives the ‘ccEntry’ GET Request with ‘123456789102’ as user input. So I guess that kind of works. But below the two h1 elements (in lime green), Django should show the card number ‘123456789102’ as well as the redacted card number ‘xxxx xxxx 9102’ but instead it’s blank. What is wrong here? As far as I can tell, I believe the problem involves either the first two functions inside my redactors views.py or the way my app’s urls.py is arranged.
Here is my views.py :
from django.shortcuts import render
# Create your views here.
def redactors(request):
return render(request, 'alls/landings.html')
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx {}'.format(number[-4:])
return render(request, 'alls/landings.html', {'number':number, 'redacted_num':redacted_num})
else:
return render(request, 'alls/landings.html')
def results(request):
return render(request, 'alls/landings.html')
Here is my app’s urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('home', views.home, name='home'),
path('results', views.results, name='results'),
]
Those are the two scripts where I believe the problem is.
For what it is worth, here are some other related configuration files and scripts that are in play:
Lightly abbreviated alls/landings.html template:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="The HTML5 Herald">
<meta name="robots" content="noindex,nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
{% block content %}
<div class="card-processor">
<h3>Enter your fake Chuckee Cheese Neptune membership card number!</h3>
<form action="{% url 'posts' %}" method="get">
<div>
<label for="password">Enter Card Number:</label>
<input type="text" id="password" name="ccEntry" pattern="[0-9]{12}" maxlength="12"/>
<div class="requirements">Must be a 12 digit number and no letters. </div>
<input type="submit" value="Redact!" class="button"/>
</div>
</form>
<h1>Here is your fake Chuckee Cheese Neptune memnership card number!</h1>
<h3 style="color:lime">This was the original number that you entered:</h3>
<div class="field">{{ number }}</div>
<h3 style="color:lime">Here it is redacted:</h3>
<div class="field">{{ redacted_num }}</div>
<div class="field"><strong>Again? Click here!</strong></div>
</div> <!--- END card-processor -->
<div class="post-content">
{% for post in posts %}
<h1> Blog post title: <em>{{ post.title }}</strong></em>
<h4>Publication Date: {{ post.pub_date_preference }}</h4>
<img src="{{ post.image.url }}" class="authors-pic" style="" />
<!-- Body text should go here : -->
<p>{{ post.body|safe }}</p>
{% endfor %}
{% endblock %}
</body>
</html>
Parent urls.py router:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('posts.urls')),
path('', include('redactors.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I believe those are all the relevant files in play. However in case the problem is elsewhere, if you want to see the rest of my source code, here is a static snapshot tagged as v.0.7.0 on my GitHub.
It's also worth noting that I'm not getting a trace back and my server is not crashing so I don't have many leads in terms of searching on Google for other developers resolving similar or related issues.
It seems like the 'form' in landings.html is being submitted to the path with name "posts", But there is no path with this name in your app's urls.py.
Use this <form action="{% url 'home' %}" method="get"> instead of <form action="{% url 'posts' %}" method="get">.
I created feedback form using form module in django. i wrote the code for printing form data entered by user when submitting form. But when i submit the form post is not working as a result user data is not printing . I am beginner in django .I tried lots to solve this .but i couldn't. please help me if anyone know what is my wrong in code
forms.py
from django import forms
class feedbackForm(forms.Form):
Name=forms.CharField()
RollNo=forms.IntegerField()
Email=forms.EmailField()
feedback=forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render
from .import forms
def feedback_view(request):
form=forms.feedbackForm()
if request.method=='POST':
form=forms.feedbackForm(request.POST)
if form.is_valid():
print('form validation success and printing feeback info')
print('student name :',form.cleaned_data['Name'])
print('student RollNo:',form.cleaned_data['RollNo'])
print('student Email :',form.cleaned_data['Email'])
print('student feedback :',form.cleaned_data['feedback'])
return render(request,'testapp/feedback.html',{'form':form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^feed/', views.feedback_view),
]
feedback.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="{%static "css/demo1001.css"%}">
<title></title>
</head>
<body>
<div class="container" align=center>
<h1>ShefJaz Student 2feedbackform </h1><br>
<form method="post">
{{form.as_p}}
{%csrf_token%}
<button type="button" class="btn btn-primary">sumbit feedback</button>
</form>
</div>
</body>
</html>
You are using a function as a API view so, It should be mentioned in the method decorator like shown below
from rest_framework.decorators import api_view
#api_view(['POST'])
def feedback_view(request):
.....
your code
.....
Hope it will give you the solution.
more than one HTTP methods can be used like shown here.
#api_view(['POST', 'GET'])
How is going? I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table.
Now I'm try to add a delete button in each row of my table but, beside I have tried a lot of solutions, I didn't find one that works correctly.
Below my code:
urls
from django.urls import path
from app import views
app_name = 'main'
urlpatterns = [
path('', views.homepage, name='homepage'),
path('delete_item/<int:pk>', views.delete_item, name="delete_item"),
]
forms
from django import forms
from .models import Income
class IncomeModelForm(forms.ModelForm):
class Meta:
model = Income
fields = "__all__"
tables
import django_tables2 as tables
from django_tables2.utils import A
from .models import Income
class PersonTable(tables.Table):
delete = tables.LinkColumn('main:delete_item', args=[A('delete-id')], attrs={'a': {'class': 'btn'}})
class Meta:
model = Income
template_name = "django_tables2/bootstrap.html"
views
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from .models import Income
from .tables import PersonTable
from .forms import IncomeModelForm
def homepage(request):
table = PersonTable(Income.objects.all())
if request.method == 'POST':
form = IncomeModelForm(request.POST)
if form.is_valid():
print("Il form è valido")
new_input = form.save()
else :
form = IncomeModelForm()
context= {"form": form,
"table":table }
return render(request, "app/base.html", context)
def delete_item(request, pk):
Income.objects.filter(id=pk).delete()
items = Income.objects.all()
context = {
'items': items
}
return render(request, 'app/base.html', context)
html
{% load static %}
{% load render_table from django_tables2 %}
<!doctype html>
<html lang="it">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello, world!</title>
</head>
<div class="container">
<form class="" action="" method="post">
{% csrf_token %}
{{form|crispy}}
<input type="submit" class="btn btn-danger" value="INVIA">
</form>
</div>
<br>
<br>
<div class="container">
{% render_table table %}
</form>
</div>
</body>
</html>
My table disply the column "Delete" but no buttoms, only a "-". Why? Where is my error?
Please add this
text='static text', argument like delete = tables.LinkColumn('main:delete_item',text='Delete', args=[A('delete-id')], attrs={'a': {'class': 'btn'}})
.
Hope it will work
I'm getting this error when trying to click on the "New Color Set" button:
NoReverseMatch at /colorsets/new/
Reverse for 'user_logout' not found. 'user_logout' is not a valid view function or pattern name.
I've looked extensively through StackOverflow and elsewhere on other sites and can't seem to find what the issue is. As far a I can tell all my code is right but clearly there is an issue.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Colors</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<nav>
<div class="container">
<a class="btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="btn" href="{% url 'colorsets:new_color' %}">New Color Set</a>
<a class="btn" href="{% url 'accounts:user_logout' %}">Logout</a>
{% else %}
<a class="btn" href="{% url 'accounts:user_login' %}">Login</a>
<a class="btn" href="{% url 'accounts:register' %}">Register</a>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
Views.py
from django.shortcuts import render
from accounts.forms import UserForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Your username and/or password are not correct")
else:
return render(request,'accounts/login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'accounts/register.html',{'user_form':user_form,'registered':registered})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
accounts app urls.py
from django.conf.urls import url
from accounts import views
app_name = 'accounts'
urlpatterns = [
url(r'^register/$',views.register,name='register'),
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/',views.user_logout,name='user_logout'),
]
project urls.py
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index,name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
]
Let me know if you need to see anything else.
The problem is in the template under the url named new_color in your colorsets namespace. You definitely used it as {% url 'user_logout' %}, while you should use it like {% url 'accounts:user_logout' %}. Just add the namespace.
Check these two things in your project:
-In settings file you should have these two codes
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
-Must have a path in project's urls.py file (as shown below)
path('users/', include('django.contrib.auth.urls')),