How to pass data from a template to the Django side - python

I just started to code Python Django. I just wanted to make a basic login project. I tried to pass login variables from the HTML side to file views.py.
Here is my HTML code:
<form action="/index" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" type="email"/>
</div>
<div class="form-group">
<div class="d-flex justify-content-between">
<label for="password">Password</label><a class="fs--1">Forgot Password?</a>
</div>
<input class="form-control" id="password" type="password" />
</div>
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" id="card-checkbox" checked="checked"/>
<label class="custom-control-label" for="card-checkbox">Remember me</label>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block mt-3"
type="submit"
id= "login"
name="submit">Log in</button>
</div>
</form>
My urls.py file:
urlpatterns = [
path('', views.loginPage, name="login"),
path('index', views.home, name="index")
]
My forms.py file:
from django import forms
class LoginForm(forms.Form):
username = forms.EmailField(label="Username"),
password = forms.CharField(label="Password")
And my views.py file:
def home(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('niceee')
else:
return render(request, 'index.html', context)
else:
form = LoginForm()
I just want to see username and password values into views.py. However, I can't see variables into views.py. How can I fix this?

def home(request):
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('username:', form.cleaned_data.get('username'))
print('password:', form.cleaned_data.get('password'))
print('niceee')
else:
form = LoginForm()
context = {}
return render(request, 'index.html', context)
Check the server for username and password values.

You are a halfway there! Once the form has been validated by Django, you can access the form's variables in its cleaned_data attribute:
def home(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('You submitted this username:', form.cleaned_data['username'])
print('You submitted this password:', form.cleaned_data['password'])
else:
return render(request, 'index.html', context)
else:
form = LoginForm()
However, consider reusing django.contrib.auth.views.LoginView because then you won't have to write any Python code at all. Just customize the registration/login.html template.

Related

Django 2.1.4 Registration Form + Login Page

Hi I am new to Django and need help with registration form and login. I am able to register and able to see the user credentials registered under admin register model. However, i tried to take the user-credentials in the database and then want to do a login, but unable to do so. Can someone help please.
models.py
class register(models.Model):
name = models.CharField(max_length=250)
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
occupation = models.CharField(max_length=100)
def __unicode__(self):
return str(self.username)
Views.py
#register
def registerForm(request):
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('username') and request.POST.get('password') and request.POST.get('occupation'):
reg = register()
reg.name = request.POST['name']
reg.username = request.POST['username']
reg.password = request.POST['password']
reg.occupation = request.POST['occupation']
reg.save()
return render(request, 'login.html')
else:
return render(request, 'register.html')
#Login
def Login(request):
if request.method == 'POST':
if request.POST.get('username') and request.POST.get('password'):
usr_login = register()
usr_login.username = request.POST['username']
usr_login.password = request.POST['password']
usr_login.user = authenticate(username=username, password=password)
if usr_login.user:
login(request, usr_login.user)
return HttpResponseRedirect('/forum/')
else:
error = "Username and Password are invalid. Please try again."
return render(request, 'login.html')
else:
return render(request, 'login.html')
login.html
<form method="post" action="/forum/">
{% csrf_token %}
<div class="form-group">
<label for="username">Username:</label>
<input type="username" class="form-control" id="username" placeholder="Enter username" required="required">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" required="required">
</div>
<div class="row">
<div class="col" align="center">
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Remember me
</label>
</div>
<button type="submit" class="btn btn-primary" value="login">Submit</button><br><br>
Not yet registered? Register Here.
</form>
urls.py
# login
url(r'^login/$', views.Login, name='login'),
# register
url(r'^registeration/$', views.registerForm, name='registeration'),
You are trying to authenticate the user using the django builtin authentication backend but you are not using the django User model. In your case you have to create custom authentication logic. I strongly suggest you to hash the user's password.
If you want to use the builtin auth framework you check out the documentation for more information https://docs.djangoproject.com/en/2.1/ref/contrib/auth/

how to access Django form fields through HTML

I have created models.py, forms.py, views.py & registeration.html.
At the moment in registeration.html I am directly importing the django form like {{reg_form.as_p}}, I can also do it in following two ways: {{ form.as_table }} or {{ form.as_ul }}. what I want is to have a real control over the fields to be displayed. Meaning to say some fields may be tabular, some may be list etc with specific css.
What I tried in html to access the field is mentioned below:
id={{form.id_FullName}} name={{form.FullName}}
In models.py I have:
FullName = models.CharField(max_length = 100)
The above way didnt work, I want some way to access the django fields in HTML.
Add name and pass the modelname ,
Change like this,
<input type="text" id="id_FullName" value="" name="FullName" />.
and submit your form.
Example , lets say signup form :
forms.py,
class SignUpForm(forms.ModelForm):
email = forms.CharField(label='email', max_length=100)
password = forms.CharField(label='password', max_length=100)
def __init__(self, *args, **kargs):
super(SignUpForm, self).__init__(*args, **kargs)
class Meta:
model = User
fields = '__all__'
views.py,
def signup(request):
form = SignUpForm(request.POST or None)
if request.method == 'POST':
form = SignUpForm(request.POST or None)
if not form.is_valid():
print form.errors
return render(request, 'signup.html', {'form': form})
else:
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_user = User.objects.create_user(email=email,
password=password,
)
new_user.is_active = True
new_user.save()
return redirect('login')
else:
return render(request, 'signup.html', {'form': form})
urls.py
url(r'^signup', views.signup, name='signup'),
Finally in your templates ie signup.html,
<form action="." method="post"> {% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name="email" id="inputUsernameEmail" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<input type="submit" name="Sign up" value="Sign up" id="Sign_up" class="button_drop outline">
</form>
You can render the field manually.[Documentation]
Here is a sample taken from the docs for a subject field
<div class="fieldWrapper">
{{ form.subject.errors }}
{{ form.subject.label_tag }}
{{ form.subject }}
</div>

Django, form is_valid() is always false

I'm learning Django and have some troubles with forms. I try to create a simple form where I type a name and show it on another page. But is_valid() always returns false. Please, help me to find my error
forms.py
from django import forms
class OrderForm(forms.Form):
user=forms.CharField(max_length=100)
views.py
def order(request):
return render(request, 'myapp/order.html', {})
def contact(request):
username='not logged'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
else:
username='not worked'
else:
form=OrderForm()
return render(request, 'myapp/contacts.html', {'username':username})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
<input type="text" name="username" placeholder="Name">
<button type="submit">Login</button>
</form>
contacts.html
You are : <strong>{{ username }}</strong>
Your form control has the name username in HTML, while your form's field is named user in Django. Thus, nothing is set in the form field.
Normally you'd put the form into the context and then render it either as {{ form }} or the like, or render each field, rather than build your own form controls. The docs show how: https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates
views.py
from forms import OrderForm
def order(request):
form = OrderForm()
return render(request, 'myapp/order.html', {"form" : form})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
{{form.as_p}}
<button type="submit">Login</button>
</form>
At the time of rendering template {{form.as_p}} looks like
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="100" required /></p>

Disappearing {% csrf_token %} on website file

When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">
<p><label for="id_username">Login:</label> <input id="id_username" maxlength="30" name="username" type="text" required/></p>
<p><label for="id_email">Email:</label> <input id="id_email" name="email" type="email" required /></p>
<p><label for="id_password1">Hasło:</label> <input id="id_password1" name="password1" type="password" required /></p>
<p><label for="id_password2">Powtórz hasło:</label> <input id="id_password2" name="password2" type="password" required /></p>
<p><label for="id_phone">Telefon:</label> <input id="id_phone" maxlength="20" name="phone" type="text" /></p>
<p><label for="id_log_on">Logowanie po rejestracji:</label><input id="id_log_on" name="log_on" type="checkbox" /></p>
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
I was surprised of that, because in my files on Pythonanythere this fragment of code is present.
This is part of my file register.html on Pythonanythere:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
What am I doing wrong that my webpage don't see this piece of code? It is seamed on server but on webpage view-source It isn't.
EDIT:
This is view, which render my template:
def register(request):
if request.method == 'POST':
form = FormularzRejestracji(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
user.last_name = form.cleaned_data['phone']
user.save()
if form.cleaned_data['log_on']:
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
login(request, user)
template = get_template("osnowa_app/point_list.html")
variables = RequestContext(request, {'user': user})
output = template.render(variables)
return HttpResponseRedirect("/")
else:
template = get_template("osnowa_app/register_success.html")
variables = RequestContext(request, {'username': form.cleaned_data['username']})
output = template.render(variables)
return HttpResponse(output)
else:
form = FormularzRejestracji()
template = get_template("osnowa_app/register.html")
form = FormularzRejestracji()
variables = RequestContext(request, {'form': form})
output = template.render(variables)
return HttpResponse(output)
You should pass a plain dict and the request object to template.render(), not a RequestContext. The template engine will convert it to a RequestContext for you:
template = get_template("osnowa_app/register.html")
context = {'form': form}
output = template.render(context, request)
Right now, the template.render() function sees a dict-like object as the first argument, but no request as the second argument. Without a request as the second argument, it converts the dict-like RequestContext into a plain Context object. Since the Context object doesn't run context processors, your context is missing the csrf token.
Alternatively you can just use the render shortcut, which returns a HttpResponse object with the rendered template as content:
from django.shortcuts import render
def register(request):
...
return render(request, "osnowa_app/register.html", {'form': form})
This particular case is also being discussed in ticket #27258.
CSRF token gets included in HTML form by calling hidden_tag function on your form object.
For example check this gist, line number 6. This is how you add form and it's elements in jinja.

Django how to process content of either form or the other?

A user is able submit a POST request. Either by uploading a file or by using a sample on the server. Posting the file works perfect but I have trouble implementing the second part. This is my model:
class UploadFileForm(forms.Form):
file = forms.FileField()
from_server = forms.BooleanField(required=False,initial=False)
My template. I thought it best to use two forms. But I fail to check on the content/type/key of the incoming data in my view.
<div class="fieldWrapper">
<form action="flot" enctype="multipart/form-data" method="post">{% csrf_token %}
<label for="id_file">File:</label>
{{ form.file }}
<input id="upload" type="submit" value="Upload">
</form>
</div>
<div class="fieldWrapper">
<form action="flot" method="post">{% csrf_token %}
<label for="id_from_server">Gebuik een sample file op de server</label>
{{ form.from_server }}
<input id="server" type="submit" value="Go" name="Go">
<!--<input id="upload" type="submit" value="Go">-->
</form>
</div>
Here is my view. I don't know exactly how to check the incoming data on from which form they where submitted. See request.POST.getlist('Go') for my final attempt. Test-wise I will return a Http404.
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
if 'Go' in request.POST.getlist('Go'):
raise Http404
else:
err, line_z1, line_z2 = handle_uploaded_file(request.FILES['file'])
if err == None:
return render_to_response('flot.html',
{
'form': form,
'line1':simplejson.dumps(line_z1),
'line2':simplejson.dumps(line_z2)
},
context_instance=RequestContext(request))
else:
form = UploadFileForm()
return render_to_response('flot.html',
{'form': form,
'error': err
},
context_instance=RequestContext(request))
else:
form = UploadFileForm()
return render_to_response('flot.html',
{'form': form},
context_instance=RequestContext(request))

Categories

Resources