Django Creating User Basics - python

I am new to Django (1.5) and got stucked at assumingly basic stuff. I try to create a User using following code.
VIEW:
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
def sign_up(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.create_user(username=username, password=password)
user.save()
return HttpResponseRedirect(reverse('account:login'))
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('account/sign_up.html', args, context_instance=RequestContext(request))
ACCORDANT TEMPLATE:
<html>
...
<div id="sign_up"> {% block extension1 %}
</form action="/account/sign_up/" method="post"> {% csrf_token %}
{{ form }} <br/>
<input type="submit" value="Sign up"/>
</form> {% endblock %}
</div>
If I hit the 'Sign up' button just nothing happens. What basic thing am I missing. I would appreaciate a tiny lesson about this. Thanks.

Related

'Logging in' error, in Django framework

when I insert username and password, it doesn't redirect to home page and stays on the login page, and its URL displays such messages
http://localhost:8000/login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24
in Powershell, it shows like this
System check identified no issues (0 silenced).
May 25, 2018 - 11:50:07
Django version 2.0.5, using settings 'a.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[25/May/2018 11:50:10] "GET /login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24 HTTP/1.1" 200 446
Performing system checks...
there is no error though, but it doesn't behave the way i want it to..
models.py
from django.db import models
# Create your models here.
class login_model(models.Model):
username = models.CharField(max_length=200)
password = models.CharField(max_length=200)
forms.py
from django import forms
from .models import login_model
class LoginForm(forms.ModelForm):
class Meta:
model = login_model
fields = ['username','password']
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('login/',views.login_view,name = 'login_url' ),
path('',views.home, name = 'home_url'),
]
views.py
from django.shortcuts import render,redirect
from .forms import LoginForm
from django.contrib.auth import authenticate,login
# Create your views here.
def home(request):
return render(request,'home.html')
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST or None)
if form.is_valid():
uusername = form.cleaned_data.get('username')
ppassword = form.cleaned_data.get('password')
user = authenticate(request,username=uusername,password=ppassword)
if user is None:
login(request,user)
return redirect('home url')
else:
print('Error')
else:
form = LoginForm()
return render(request,'login.html',{'form':form})
templates
login.html
<form>
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
home.html
{% if user.is_authenticated %}
<h1>Hi {{user.username}} </h1>
{% else %}
<h1> Hi Ola Amigo </h1>
<p>Please Login Login </p>
{% endif %}
You should set form's method as POST, otherwise it's GET by default:
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>

Django - UPDATE user fields in two different views (forms)

I have hard time with such a easy thing (I guess).
My aim is to create two subpages with 2 different forms yet connected with the same user model:
/account/register.html - page only to manage registration (create user with login,email,password)
/account/questionnaire.html - page for UPDATING the same user information such as age,weight,height etc.
I've got 'POST' communicates in server log but nothing appears when I'm checking up django admin site.
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.PositiveIntegerField(blank=False)
weight = models.PositiveIntegerField(blank=False)
height = models.PositiveIntegerField(blank=False)
forms.py
from django import forms
from django.core import validators
from django.contrib.auth.models import User
from account.models import UserProfile
class RegisterUserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','email','password')
class RegisterUserInfoForm(forms.ModelForm):
class Meta():
model = UserProfile
fields = ('age','weight','height')
views.py
from django.shortcuts import render
from account.forms import RegisterUserForm, RegisterUserInfoForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def register(request):
registered = False
if request.method == 'POST':
user_form = RegisterUserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = RegisterUserForm()
return render(request,'account/register.html',{
'user_form':user_form,
'registered':registered,
})
#login_required
def questionnaire(request):
if request.method == 'POST':
profile_form = RegisterUserInfoForm(request.POST, instance=request.user)
if profile_form.is_valid():
profile_form.save()
else:
print(profile_form.errors)
else:
profile_form = RegisterUserInfoForm(instance=request.user)
return render(request,'account/questionnaire.html',{
'profile_form':profile_form,
})
register.html
{% extends 'base.html' %}
{% block body_block %}
<div class="container">
<h1>Register</h1>
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="btn btn-primary" value="Save">
</form>
</div>
{% endblock %}
questionnaire.html
{% extends 'base.html' %}
{% block body_block %}
<div class="container">
<h1>questionnaire</h1>
<form method="post">
{% csrf_token %}
{{ profile_form.as_p }}
<input type="submit" name="" value="Save">
</form>
</div>
{% endblock %}
Your view doesn't receive a POST request because you didn't provide an action attribute to your form tag. So, your form passes your POST request nowhere. Try it like this:
<form action="" method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="btn btn-primary" value="Save">
</form>
Also, you should definitely check django's built-in generic views: CreateView and UpdateView. They serve exactly for such purposes and makes almost everything for you.

Django Form request.POST.get() always returns empty

Sorry if this is a noob question. I'm creating a login form for a Django app, but I'm having trouble getting it to work. request.POST.get() doesn't return anything, so the authentication always fails. Am I missing something obvious?
login.html:
{% extends "base.html" %}
{% block content%}
<h2>Welcome! Please login to continue.</h2> <br>
<form action="{% url 'account:authenticate' %}" method="post">
{% csrf_token %}
<div >
<label for='username'> Username: </label>
<input type='text' name='Username' id='username'> <br><br>
<label for='password'>Password: </label>
<input type='password' name='Password' id='password'><br><br>
<input type='submit' value='Login'>
</div>
</form>
relevant part of views.py:
from django.shortcuts import render, get_object_or_404
from datetime import datetime
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from random import randrange
from django.contrib.auth import authenticate
def login(request):
return render (request, 'login.html')
def authenticate(request):
usern = request.POST.get('username', '')
passw = request.POST.get('password', '')
user = authenticate(username = usern, password = passw)
if user is not None:
authenticate.login(request, user)
return HttpResponseRedirect('/voters/instructions')
else:
return HttpResponseRedirect('/account/loginfail')
def loginfail(request):
return render (request, 'loginfail.html')
I'm using Django 1.10. Thanks!
Check out the names in the form input fields they are case sensitive. in Django do this
usern = request.POST.get('Username', '')
passw = request.POST.get('Password', '')
or in html form make them lowercase the input name field

the login field is not visible after implementing it

I am trying to implement the login field using django's authenticationForm.
the problem im having is that,because im trying to display two different forms inside one page (post_list) it seem to cause many errors.
one is for login field, and one is for the posting articles.
i also seem to have problem with duplicate forms as the two forms use the samename for the form which i do not know how to change.
also, there an error occurring when i try to post something using the post form.
to blatantly put, how do i make the login field visible?
i refer you to the working site : http://mtode.com( this is just a representation site, and do not contain login field part)
this is my views py which contains the definitions
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm, AuthenticationForm
from .models import Post
from django.contrib.auth import authenticate, login
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
def post_detail(request, id=None):
#instance = Post.objects.get(id=1)
instance = get_object_or_404(Post, id=id)
context = {
"title": instance.title,
"instance": instance,
}
return render(request, "post_detail.html", context)
def post_list(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
login(request, form.get_user())
return HttpResponseRedirect('/post-list/')
else:
form = AuthenticationForm(request)
return TemplateResponse(request, 'login.html', {'form': form})
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
print (form.cleaned_data.get("title"))
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get())
#else:
#messages.error(request, "Not Successfully Created")
queryset = Post.objects.all()#.order_by("-timestamp")
context = {
"object_list": queryset,
"title": "List",
"form": form,
}
return render(request, "post_list.html", context)
#return HttpResponse("<h1>List</h1>")
def post_update(request, id=None):
instance = get_object_or_404(Post, id=id)
form = PostForm(request.POST or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form,
}
return render(request, "post_form.html", context)
def post_delete(request, id=None):
instance = get_object_or_404(Post, id=id)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
and this is the forms.py that contains the forms
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content"
]
from django.contrib.auth import authenticate
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=254)
password = forms.CharField(widget=forms.PasswordInput)
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is None:
raise forms.ValidationError('invalid_login')
return self.cleaned_data
and this is the post_list.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="">
{% csrf_token %}
Username: {{ form.username }} {{ form.username.errors }}<br>
Password: {{ form.password }} {{ form.password.errors }}<br>
{{ form.errors }}<br>
<input type="submit" value="login" />
</form>
<div class='two columns right mgr'>
<h1>Form</h1>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input class="button-primary" type='submit' value='Create Post' />
</form>
</div>
<div class='four columns left'>
<h1>{{ title }}</h1>
{% for obj in object_list %}
<div class="row">
<div>
<a href='{{ obj.get_absolute_url }}'>
<div class="thumbnail">
<!--<img src="..." alt="...">!-->
<div class="caption">
<h3>{{ obj.title }}<small> {{ obj.timestamp|timesince }} ago</small></h3>
<p>{{ obj.content|linebreaks|truncatechars:120 }}</p>
<!-- <p>View </p>-->
</div>
</div></a>
</div>
<hr />
</div>
{% endfor %}
</div>
{% endblock content %}
Thank you.
When your page is initially displayed, request.method is GET. Therefore the post_list view is creating a PostForm instance and passing that into your template as the form element.
PostForm does not have username or password attributes, so those items are treated as empty strings and do not render at all.
If you want a template to render two forms, you need to pass them as separate names. You can't call them both "form".

Django : CSRF token missing or incorrect [duplicate]

This question already has answers here:
Django: CSRF token missing or incorrect
(4 answers)
Closed 9 years ago.
Django noob here ! I've tried basically every solution online and I still have the error (one Chrome) "CSRF token missing or incorrect" while Opera and Firefox return "CSRF cookie not set" instead...? Here are my files :
views.py
# views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.template import RequestContext
from django.core.context_processors import csrf
def dashboard(request):
state = "log in"
if request.user.is_authenticated():
return render_to_response('memberbrd.html')
elif request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
error = "inactive"
else:
error = "wrong username or password"
render_to_response('visitorbrd.html', {'errors': error}, context_instance = RequestContext(request)) # I've also tried without context_instance, without passing errors...
else:
return render_to_response('visitorbrd.html')
urls.py
#urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from mission.views import *
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', dashboard),
)
visitorbrd.html
{% extends "base.html" %}
{% block content %}
{% if state %}
<p>{{ state }}</p>
{% endif %}
<form action="." method="POST">{% csrf_token %}
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
{% endblock %}
Thanks !
You're not using RequestContext for the final render_to_response which is responsible for actually showing the form.
The previous answer is absolutely correct. A RequestContext is not required to output the form itself, though. This is handled by the Form class. The problem is that a new CSRF Token needs to be generated via the request and this is done through Django's middleware. The middleware only has access to the context variables and so by that logic, it needs the RequestContext to do this.
On a side note, I prefer Django's "render" function over "render_to_response." There are some times in which this function is too generic, but for a newer user, the savings on typing are nice and the code looks a lot cleaner. I copied the example from Django's site (I'll include a permalink below as well).
from django.shortcuts import render
def my_view(request):
# View code here...
return render(request, 'myapp/index.html', {"foo": "bar"},
content_type="application/xhtml+xml")
Django Documentation: Shortcut Functions : render

Categories