reset form method value to default when page refreshes - html

login.html
<form action="/login" method="post" name="login" id="login">
<input autocomplete="off" id="username" name="username" value="{{ hold }}" type="text">
<input id="password" name="password" type="password">
<button type="submit">Log In</button>
</form>
In above I have press submit button, while username is empty.
Then form submit with the post method and return render_template("login.html", xvalue=2) have executed.
After that I have refresh the login web page and I expect the request.method been assumed as default (get) and return render_template("login.html", xvalue=4) get executed.
But xvalue=2 passed, while the form method value is remained post.
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
if not request.form.get("username"):
return render_template("login.html", xvalue=2)
else:
return render_template("login.html", xvalue=3)
else:
return render_template("login.html", xvalue=4)
How can form method variable gets default get value, in case of page refreshed?

This is what i tried and it seemd to work
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
if not request.form.get("username"):
return render_template("login.html", xvalue=2)
else:
return render_template("login.html", xvalue=3)
elif request.method == "GET":
return render_template("login.html", xvalue=3)
hope this helps

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.

after submit the views functions do nothing

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.

Adding data into the database with django by pressing enter

I do not see what I am doing wrong when trying to add data into the database. When I am pressing the button Submit, nothing is entered in the database. The same happens when pressing the key enter.
Here is my html file.
<script>
$(document).keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
alert('enter key is pressed');
event.preventDefault();
}
});
</script>
<div class="col-md-6 col-md-offset-3">
<form method="POST" action="">
<p>
{% csrf_token %}
<input type="hidden" value="{{post.id}}" />
<div class="col-xs-16" style="margin: 0; 0;padding: 3%;">
<label for="inputsm">Oracle</label>
<input class="form-control input-md" type="text" value="{{ post }}">
<input type="submit" value="Submit" style="display: none" /> {{ form.body }}
<button type="submit" value="Submit" class="btn btn-success">Submit</button>
</p>
</div>
</form>
</div>
Here is the views.py
def post_list(request):
posts = Post.objects.all()
category = Category.objects.all()
context = {
'posts':posts,
'cat':category,
}
return render(request, 'journal/post_list.html', context)
def add_post(request):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST or None)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_details', pk=post.pk)
return render(request, 'journal/post_list.html', {'post': post})
else:
form = PostForm()
context = {
"form": form,
}
return render_to_response('journal/post_list.html', context)
Does the form get submitted? If not, maybe try adding some javascript to submit the form, when the key is pressed
$("form").submit();

Passing context on an html with both POST and GET options

I have a html page with various submit buttons:
<h3>Add Address</h3>
<form method="post">
{% csrf_token %}
...
<input type="submit" value="Add" name="_add_add">
</form>
<h3> Update values </h3>
<form method="post">
{% csrf_token %}
...
<input type="submit" value="Add" name="_update">
</form>
<h3>Address</h3>
<form method="get">
...display...
My view.py is:
def property(request):
if request.method == 'POST':
if '_update' in request.POST:
...update values...
elif '_add_add' in request.POST:
...add addres....
Context = {"name_for_template":"value"}
else:
... graph default values...
Context = {"name_for_template":"value"}
return render(request, 'address.html', context)
When there isn't a POST and simply a GET (like being redirected to the page), I get an CSRF error in the context (and it asked me to use request_context). Is it possible (and how) to automatically send a default context for the GET, and send a different context for POST without incurring the CSRF error?
you can try this edit code
def property(request):
context = {}
if request.method == 'POST':
if '_update' in request.POST:
...update values...
elif '_add_add' in request.POST:
...add addres....
context["name_for_template"]= "value"
else:
... graph default values...
context["name_for_template"]= "value"
return render(request, 'address.html', context)
if it doesn't work, share your code

Email sending in django code is not working

Email sending in django code is not working,
it display error "[Errno 10061] No connection could be made because the target machine actively refused it"
these are my VIEWS.PY
def send_email(request):
username = request.POST.get('username', '')
from_email = request.POST.get('from_email', '')
message = request.POST.get('message', '')
if username and message and from_email:
try:
send_mail(username, from_email, message, ['canonizadocharm#ymail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return HttpResponseRedirect('/contact/thanks/')
else:
# In reality we'd use a form class
# to get proper validation errors.
return HttpResponse('Make sure all fields are entered and valid.')
these are my contact.html
<FORM METHOD="POST" ACTION="/send_email/" >
{% csrf_token %}
Name: <INPUT TYPE="text" NAME="username"><BR>
Email: <INPUT TYPE="text" NAME="from_email"><BR>
Message: <BR>
<TEXTAREA NAME="message" ROWS="10" WRAP="hard">
</TEXTAREA>
<INPUT NAME="redirect" TYPE="hidden">
<INPUT NAME="NEXT_URL" TYPE="hidden">
<BR>
<INPUT TYPE="submit" VALUE="Send">
<INPUT TYPE="reset" VALUE="Clear">
</FORM>
these are my URLS.PY
url(r'^send_email/', views.send_email),
url(r'^contact/', views.contact),
url(r'^thanks/', views.thanks),
and my SETTINGS.PY
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = True
Your action value of form must direct to view's url, mailto:canonizadocharm#ymail.com is not a valid path on your server.
UPDATED:
For example, add a new rule to urls.py like,
url(r'^mail/', views.send_mail),
Then change action value to mail.
Have your action value point to a URL, which in turn points to one of your views. For instance, your urls.py can do this.
url(r'^email/', 'project.views.send_email')
This will route your contact form to your send_mail view.
Your form in the templates has no csrf that's why you get an error of "CSRF verification failed".
<FORM METHOD=POST ACTION="/send_email/" ENCTYPE="text/plain">{% csrf_token %}
...........
</FORM>
If you want to know what is csrf just go to this link:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
Create email setting in your settings.py, like this for example:
settings.py
# Sending mail
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'
views.py
from django.core.mail import send_mail
def send_email(request):
if request.method == 'POST':
username = request.POST.get('username')
message = request.POST.get('message')
from_email = request.POST.get('from_email')
send_mail(username, message, from_email, ['canonizadocharm#ymail.com',])
return HttpResponseRedirect('/contact/thanks/')
else:
return HttpResponse('Make sure all fields are entered and valid.')