NoReverseMatch at /main/insert_num/ Django - python

I'm trying to make to make a django web app which has a form that asks a user to input a phone number and stores that number in a postgres database. The following code is giving me the error:
NoReverseMatch at /main/insert_num/
Reverse for '' not found. '' is not a valid view function or pattern name.
And I can't figure out what the issue is, can someone help?
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="{% url 'insert_my_num' %}" method="post" autocomplete="off">
{% csrf_token %}
<!-- {{ form.as_p }} -->
<input type="submit" value="Send message">
</form>
</body>
</html>
forms.py
from django import forms
from phone_field import PhoneField
from main.models import Post
class HomeForm(forms.ModelForm):
phone = PhoneField()
class Meta:
model = Post
fields = ('phone',)
models.py
from django.db import models
from phone_field import PhoneField
class Post(models.Model):
phone = PhoneField()
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('insert_num/', views.insert_my_num,name='insert_my_num')
]
project/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('main/',include('main.urls'))
]
views.py
def insert_my_num(request: HttpRequest):
phone = Post(request.POST.get('phone'))
phone.save()
return redirect('')

Your views.py is a little off - you aren't rendering your form anywhere. I drafted up a quick app (which I think does what you're looking for) - let me know if this works:
main/templates/index.html
Here, I just set the form's action to "" (that's all you need here) and uncommented the form.as_p line
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>
</body>
</html>
main/views.py
Note the differences here, we are testing the request type and taking appropriate action based on what kind of request is coming in. If it's a POST request we process the form data and save to the database. If not, we need to display a blank form for the user to complete.
from django.shortcuts import render, redirect
from .forms import HomeForm
def insert_my_num(request):
# Check if this is a POST request
if request.method == 'POST':
# Create an instance of HomeForm and populate with the request data
form = HomeForm(request.POST)
# Check if it is valid
if form.is_valid():
# Process the form data - here we're just saving to the database
form.save()
# Redirect back to the same view (normally you'd redirect to a success page or something)
return redirect('insert_my_num')
# If this isn't a POST request, create a blank form
else:
form = HomeForm()
# Render the form
return render(request, 'index.html', {'form': form})
Let me know if that works!

Related

Why Django from in Invalid?

I create a django form. I am also inserting the valid values in the form field but still getting form not valid error. I used the same code yesterday and it was working fine, but I don't know why its giving the not valid error, What might be the reason for this?
Here is My Code:
View.py
from django.shortcuts import render,redirect
from django.views.generic import View,TemplateView
from .forms import Registration_Form
from .models import User_Registration
from django.contrib import messages
# Create your views here.
class MainPageView(TemplateView):
template_name='main.html'
class LoginView(TemplateView):
template_name='login.html'
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
print(request.POST)
if form.is_valid():
form.save()
print("Valid")
return redirect('login_view')
else:
print("Not Valid")
# messages.error(request,"Form is Invalid!")
return redirect('registration_view')
else:
return render(request,'registration.html',{'form':form})
# template_name='registration.html'
forms.py
from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
class Meta:
model=User_Registration
fields=('company_name','username','password','email')
widgets={
'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
'username':forms.TextInput(attrs={'class':'form-control'}),
'password':forms.PasswordInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
}
registration.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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="form-group">
<br><br><br>
<h2 style="padding-left: 480px;">Registration Form</h2>
<br>
<form method="POST" action="">
{{form.as_p}}
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
A form is always invalid if no data is passed. You thus need to pass the request.POST (and perhaps request.FILES) when constructing the form:
def RegistrationView(request):
if request.method == 'POST':
form = Registration_Form(request.POST, request.FILES)
if form.is_valid():
form.save()
print('Valid')
return redirect('login_view')
else:
print('Not Valid')
else:
form = RegistrationForm()
return render(request,'registration.html',{'form':form})
You forgot to initialize your form with the POST data :
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
print(request.POST)
form = Registration_Form(request.POST) # line added
if form.is_valid():
form.save()
...

form action not working to redirect in django v2

The form action is not redirecting from home.html to password.html in Django 2 even I recheck everything including URL pattern
Below I am sharing the basic code. My apologies if it's a basic question as I am very new to Django that's why I may not able to detect the issue.
urls.py code
from django.urls import path
from generator import views
urlpatterns = [
path('', views.home),
path('password/', views.password),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request, 'generator/home.html')
def password(request):
return render(request, 'generator/password.html')
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Password Generator</h1>
<form action="password" method="get">
<select name="length">
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<input type="button" value="Generate Password">
</form>
</body>
</html>
password.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password</title>
</head>
<body>
<h1>Password page</h1>
</body>
</html>
Error Log
File Structure
First of all give names in urls.py so you can access it by name.
urlpatterns = [
path('', views.home,name="index"),
path('password/', views.password,name="password"),
]
in home.html remove form's action
in views.py
from django.urls import reverse
def home(request):
if request.method == 'POST':
#you can access input items of form by `request.POST.get('attribute_name')`
# your logic
return redirect(reverse('password')
else:
return render(request, 'generator/home.html')
if still not getting error then please share whole code and what you want to achieve

Django: is_valid() method is always return why?

I'm just practicing django and creating simple app that take user name and profile pic and then save it in database.is_valid() method is always return false when i do form validation.
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import student,photo
from .forms import student_data
# Create your views here.
def my_data(request):
check=0
myform=student_data()
if (request.method=="POST"):
myform=student_data(request.POST,request.FILES)
if (myform.is_valid()):
stu_name=myform.cleaned_data['name']
stu_image=myform.cleaned_data['image']
d=photo.objects.filter(name=stu_name)
myform.save()
if not d:
new_data=photo(image=stu_image,name=stu_name)
photo.save(self=new_data)
else:
check=1
else:
myform=student_data
return render(request,'show.html',{'student':stu_name,'check':check})
forms.py
from django import forms
#from .models import student
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20)
image=forms.ImageField()
models.py
from django.db import models
class photo(models.Model):
image=models.ImageField()
name=models.CharField(max_length=20)
class Meta:
db_table='photo'
html file for form.
<!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>
<div>
<form name="form" action="/payment/show/" method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
If you submit both data and files, the encoding type of the form should be multipart/form-data, so:
<form name="form" action="/payment/show/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add Me</button>
</form>
Note: It is normally better to make use of the {% url … %} template tag [Django-doc]
than to write hardcoded urls. It makes it easier to understand to what view you
are referring, if you later change the URL, the url resolution will change as
well, and it will encode the url values if necessary.

Django - Update User instance by form

Befor all :
Djano VERSION = 1.8, and it's obligatory that I use this version
Question
I do not know why I cannot update the User instance by a form.
I mean by updating: changing the value in the database and in the request
The User model is not created by me but I use django.contrib.auth.models.User
Code
This is my code
app/forms.py
from django import forms
from django.contrib.auth.models import User
class ModificationForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']
app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from app.forms import ModificationForm
#login_required
def profil(request):
if request.method == "POST":
form = ModificationForm(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = ModificationForm()
return render(request, "profil.html", {'form':form})
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profil</title>
</head>
<body>
<h1>Profil</h1>
<a href='/deconnexion'> Logout </a>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enregistrer" />
</form>
</body>
</html>
Your posting to the wrong link!
If you do not know it, just leave the action empty in the html insted of action="." !

in my project how can i set http session tracking login time for 30 second only

In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from .models import Reg
from .forms import LoginForm
from .forms import RegForm
def reg(request):
if request.method == 'POST':
form = RegForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse('reg success')
else:
print(form.errors)
return HttpResponse("error")
else:
form = RegForm()
return render(request,'reg.html', {'form': form})
def login(request):
if request.method == "POST":
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Reg.objects.filter(user=un,pwd=pw)
if not dbuser:
return HttpResponse('opppppss login faield')
else:
return HttpResponse('login success')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def home(request):
return render(request,'home.html')
models.py
from __future__ import unicode_literals
from django.db import models
class Reg(models.Model):
user = models.CharField(primary_key=True,max_length=20)
pwd = models.CharField(max_length=20)
fname=models.CharField(max_length=10)
lname=models.CharField(max_length=10)
dob=models.DateField()
mobno=models.IntegerField()
forms.py
from django import forms
from .models import Reg
class RegForm(forms.ModelForm):
class Meta:
password = forms.CharField(widget=forms.PasswordInput)
model = Reg
widgets = {'pwd': forms.PasswordInput(),}
fields = ['user', 'pwd','fname','lname','dob','mobno']
class LoginForm(forms.Form):
user = forms.CharField(max_length=20)
pwd = forms.CharField(widget=forms.PasswordInput())
home.html
<!DOCTYPE html>
</html>
<html>
<body bgcolor="#00ffff">
<h1>welcome </h1>
click here to register<br>
click here to login
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
reg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try adding this to your settings.py
SESSION_COOKIE_AGE = 30

Categories