after submit the views functions do nothing - html

hello this my html formulaire
<div id="Admin" class="tabcontent">
<form method="POST" action="">
{% csrf_token %}
<h2> Vous ètes un Admin ?</h2>
<div class="container" action >
<input type="hidden" name="user_type" value="1">
<label for ="id_email"><b>Votre Email</b></label>
<input id="id_email" type="text" placeholder="Entrer Votre Email" name="email" required>
<label for ="id_password" ><b>Mot de Passe</b></label>
<input id="id_password" type="password" placeholder="Entrer Votre Mot de passe" name="password" required>
<button type="submit" >Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> souviens de moi
</label>
</div>
and this the views function called login
def login(request):
context = {}
user = request.user
if user.is_authenticated:
return render(request, "login.html")
if request.POST:
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data.POST['email']
password = form.cleaned_data.POST['password']
user = authenticate(request, email=email, password=password)
if user:
login(request, user)
if user.user_type == '1':
return render(request, "administrateur.html")
elif user.user_type == '2':
return render(request, "entrepreneur.html")
else:
print("errors")
form = AuthenticationForm()
context['login_form'] = form
return render(request, "entrepreneur", context)
and i create in form files this class
class LoginForm(forms.ModelForm):
email = forms.EmailField()
password = forms.PasswordInput()
this my 3 user class in model:
class CustomUser(AbstractUser):
user_type=((1,"admin"),(2,"entrepreneur"))
user_type=models.IntegerField(default=1,choices=user_type)
email=models.EmailField(unique=True,blank=True)
objects = UserManager()
def __str__(self):
return self.first_name
#admin-----------------------------------------------------------------------
class Admin(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,primary_key=True)
date_naissance = models.DateField(default=timezone.now)
adresse = models.CharField(max_length=20, blank=True)
def __str__(self):
return self.user.first_name
# Entrepreneur----------------------------------------------------------------
class Entrepreneur(models.Model):
user= models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True)
date_naissance=models.DateField()
adresse_entr=models.CharField(max_length=20,blank=True)
telephone=models.IntegerField()
occupation=models.CharField(max_length=50)
annnee_exp=models.IntegerField()
def __str__(self):
return self.user.first_name
when i submit it stay in the login.html and dont redirect to any other html's page
i did not find where is my problem
maybe i have a problem on passing data from htm to views??
maybe in my models class???
or in form or views
what is my errors!!!!!????? plesae help me
thank you

try to put this
<form method="POST" action="{% url 'login' %}">
Also I am not sure if you have properly closed your form with a <\form>.
Please check it.

Related

I am trying to create authentication system in Django. My code is failing to authenticate the user

<form method="post" action="/" class="mb-2">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Your Username" Required>
</div>
<div class="form-group">
<label for="pass1">Password</label>
<input type="password" class="form-control" id="pass1" name="pass1" placeholder="Enter Your Password" Required>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
This is the form from home.html
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
this is home view from views.py in 'main' app.
so as u can see from the home view if user is present or signuped it should redirect user to room.html page but when i try to do it it redirects to signup page which shouldnt happen if user is already present in data base. i am kind of lost here as i dont know what kind of solution i should search for. from what i have observed i think home view is not able to get data from the form in home.html
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns=[
path("",views.home,name="home"),
path("signup",views.signup,name="signup"),
path("rooms",views.rooms,name="rooms"),
]
for reference here is the urls.py from 'main' app
Change this,
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
to this:
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
auth = authenticate(username=username, password=pass1)
if auth:
login(request, auth)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
You should be go to go.

Post method is not working in my HTML forms

my form is like this
<h1>Signup below</h1>
<form action="result" method="post">
{% csrf_token %}
<h3>Username</h3>
<input type="text" name="username" />
<h3>Email</h3>
<input type="email" name="email">
<h3>Password</h3>
<input type="password" name="password">
<h3>Rententer your password</h3>
<input type="password" name="password2">
<input type="button" />
</form>
and in my view folder code for this url is this
def register(request):
username=request.POST['username']
email=request.POST['username']
password=request.POST['username']
verify_password=request.POST['verify_password']
return render(request,'result.html')
but whenever I run this code it shows
screenshot of the error message
you should add in def
def register(request):
if request.method == 'POST':
.....
also when you want to return a response check this valid response form django
finally make sure you are using a valid URL in urls.py
<h1>Signup below</h1>
<form action="/result/" method="post">
{% csrf_token %}
<h3>Username</h3>
<input type="text" name="username" value="{{form.username}}" />
<h3>Email</h3>
<input type="email" name="email" value="{{form.email}}">
<h3>Password</h3>
<input type="password" name="password" value="{{form.password}}">
<h3>Rententer your password</h3>
<input type="password" name="password2" value="{{form.password2}}">
<input type="button" />
</form>
Note: form is context name from view so that's why I have written
{{form.username}}
And in views.py:
try this:
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid:
form.save()
username = form.cleaned_data.get('username')
# messages.success(request,f'Welcome { username }')
return HttpResponseRedirect('/users/')
else:
form = RegisterForm()
return render(request,'users/register.html',{'form':form})

Django login form not keeping input after bad submit

I have a login form and if a user enters an invalid username or password, the page refreshes and removes the Username value they entered. I would like it so that the username field doesn't empty on failed submit.
views.py
def login_page(request):
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', {})
login.html:
<form id="login-form" action="" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 center" style="border-radius: 16px;">
<input type="submit" name="login-submit" id="login-submit" tabindex="5" class="form-control btn btn-login" value="Login">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="center">
Forgot Password?
</div>
</div>
</div>
</div>
</form>
It's all about passing the username in the context.
try this:
views.py
def login_page(request):
context = {}
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
context["username"] = username
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', context)
login.html:
...
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="{{ username }}">
...

django inserting data into db using html template

I'm new in django. I'm trying to connect already made an html file to django backend without rebuilding whole file.
Already created forms and views in python but have no idea what to put into html file.
view class:
class signup(View):
template = loader.get_template('signup.html')
form_class = UserRegistrationForm
def get(self, request):
form = self.form_class(None)
return render(request, 'signup.html', {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
current_user = form.save(commit=False)
email = form.cleaned_data['email']
password = form.cleaned_data['password']
current_user.set_password(password)
current_user.save()
userToAuthenticate = authenticate(email=email, password=password)
if userToAuthenticate is not None:
if userToAuthenticate.is_active:
login(request, userToAuthenticate)
return redirect('siteViews:index')
return render(request, 'signup.html', {'form': form})
form code:
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'password']
and html code:
<div id="registersquare">
<div id="panel">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="email">Email adress:</label>
<input type="email" id="username" name="email}">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<label for="password">Repeat password:</label>
<input type="password" id="password" name="repeatedpassword">
<label class="control-label col-sm-2" for="password">{{ field.label_tag }}</label>
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox"><a style="color: #999999;" href="#">I Accept Website Terms And Conditions.</a></label>
<input type="submit" value="Sign up">
</div>
</form>
</div>
</div>
anyone can explain how to do it?
cheers
You hav already created a Form, which is not Django's form, so you dont actually have to write anything in forms.py, as the purpose of it is to create an form based on the model structure and perform validations according to the fields defined.
Now you have to fetch data from form and perform the validation and checks by yourself in views. So the post would be
def post(self, request):
email = request.POST.get('email') # get value in name="email" field
password = request.POST.get('password')
repeatedpassword = request.POST.get('repeatedpassword')
if password == repeatedpassword: # manual validation to check if both string are same
# Other Validations code here and
# Register or Login etc functions here
return render(request, 'signup.html', {'form': form})
You need to delete the labels and inputs from your html file and add this tag after the {% csrf_token %}, {{form.as_p}}, that's a start. You are also using an older version of Django, the way I can tell is because when you defined your ModelForm you wrote forms.ModelForm when it has been changed to just ModelForm, to upgrade write
pip install -U Django
You essentially created two forms, one with just html and one with Django only you did not apply your ModelForm to your html file instead you just made a html form instead of a html rendered Django ModelForm.

Appear data in URL form bu using Django

I want to create a record and want to appear data in the form fields. How can I do that ? Do I need to write javascript for it. If you help me, really apprepriate it. Thanks for now.
Here is models.py;
class hesaplarim(models.Model):
hesap_id = models.AutoField(primary_key=True)
tc_no = models.IntegerField(unique=True)
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
phone_number = models.IntegerField()
gender = models.CharField(max_length=5)
Here is views.py;
def home(request):
form = HesapForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = HesapForm()
return render(request, 'home.html', {'form': form})
Here is forms.py;
class HesapForm(forms.ModelForm):
ERKEK = 'ERKEK'
KADIN = 'KADIN'
gender_choices = (
(ERKEK, 'ERKEK'),
(KADIN, 'KADIN')
)
tc_no = forms.IntegerField(widget=forms.NumberInput)
name = forms.CharField(widget=forms.TextInput)
surname = forms.CharField(widget=forms.TextInput)
phone_number = forms.IntegerField(widget=forms.NumberInput)
gender = forms.ChoiceField(choices=gender_choices)
class Meta:
model = hesaplarim
fields = ('tc_no', 'name', 'surname', 'phone_number',
'gender')
Here is html file;
<form method="post" class="form-horizontal" novalidate>
{% csrf_token %}
<div class="form-group">
<label for="id_tc_no">TC No:</label>
{{ form.tc_no }}
</div>
<div class="form-group">
<label for="id_name">Ad:</label>
{{ form.name }}
</div>
<div class="form-group">
<label for="id_surname">Soyad:</label>
{{ form.surname }}
</div>
<div class="form-group">
<label for="id_phone">Cep Telefonu:</label>
{{ form.phone_number }}
</div>
<div class="form-group">
<label for="id_gender">Cinsiyet:</label>
{{ form.gender }}
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Kaydet">
</div>
</form>
You need to initialize the form:
def home(request):
form = HesapForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = HesapForm(initial={'your_field': 'your_value'})
return render(request, 'home.html', {'form': form})
Dynamic initial values you can refer about the same here.
You can also initialize it with object as well.