When I try to login through the login page of my django project, there is the message User with this Username already exists. Here I used my own authentication view:
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect('/logger/bad_login/')
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/logger/bad_login/')
else:
form = LoginForm()
return render(request, 'logger/login.html', {'form': form})
Later I found django stock auth views and forms. But still want to know why my view doesnt work properly.
urls.py of my logger app, which used also for saving data of users activity
from django.conf.urls import patterns, include, url
from logger import views
urlpatterns = patterns('',
url(r'^$', views.logger_view, name='log'),
url(r'^login/$', views.login_view, name = 'login'),
url(r'^bad_login/$', views.bad_login_view, name = 'bad_login'),
)
And template
{% extends "base.html" %}
{% block title %}Login {% endblock title %}
{% block content %}
<form action="/logger/login/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
LoginForm
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password')
You are using a ModelForm and those will only valid if both the form and the model validation pass.
As you are using the User model, your form does not validate at the model level which is why your view fails.
If you change your login form thus, your view will work as intended:
class LoginForm(forms.Form): # A normal form, not a model form
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
You might also want to fix your view, so your form errors are displayed correctly, and you are utilizing the form correctly as well:
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect('/logger/bad_login/')
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/logger/bad_login/')
return render(request, 'logger/login.html', {'form': form})
Related
How can I show errors like email or username is already taken in this page Aaccounts/sign-up.html because when try to to put a username and this username is already taken the page only refresh without any message.
Before:
After:
Code:
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'Aaccounts/sign-up.html'
def login (request) :
if request.method=='POST':
passwordtest=request.POST ['password']
usernametest=request.POST ['username']
user=auth.authenticate(username=usernametest,password=passwordtest)
if user is not None :
auth.login(request,user)
current_user = request.user
correctUSER = get_object_or_404(CustomUser, pk=current_user.id)
need_to_cheack=correctUSER.main_affilitee
kain=False
if need_to_cheack !="":
objs=CustomUser.objects.all()
for aleratwar in objs:
if kain==False:
if aleratwar.username==need_to_cheack and aleratwar.afilliteuser==True and aleratwar.username !=correctUSER.username :
kain=True
if kain== False:
correctUSER.main_affilitee=''
correctUSER.save()
return redirect('home')
else:
return render(request,'Aaccounts/login.html',{'eroor':True})
else:
return render(request,'Aaccounts/login.html')
This is the simple example of showing the message. In your view you can In this way
from django.contrib import messages
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')
else:
messages.error(request,'username or password not correct')
return redirect('login')
else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})
{{ message }}
</div>
{% endfor %}
and In your template:
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}
I'm really new to Django and I want to teach myself my making a simple note. But I don't understand how django forms work. I made simple template when I can display the user's notes and now I am trying to make a view when the user can add new notes to account using a simple form.
Here is my views.py file
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from .forms import CreateUserForm, CreateNoteForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import *
# Create your views here.
def loginPage(request):
if 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('home')
else:
messages.info(request, 'Username or pasword is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for '+ user)
return redirect('home')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
def home(request):
if request.user.is_authenticated:
username = request.POST.get('username')
context = {'username': username}
return render(request, 'accounts/home.html', context)
def notes(request):
username = None
if request.user.is_authenticated:
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
context = {
'user_notes': user_notes,
'username': username,
#'user_id' : user_id,
}
return render(request, 'accounts/notes.html', context)
def createNote(request):
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
form = CreateNoteForm()
if request.method == 'POST':
form = CreateNoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('notes')
context = {'user_notes': user_notes, 'form': form}
return render(request, 'accounts/create_note.html', context)
forms.py:
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Note
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class CreateNoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['user', 'title', 'text']
and create_note.html:
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<br>
<div class="container">
<div class="card text-white bg-dark mb-3">
<div class="container">
<form action="{% url 'notes' %}" method="POST">
<div class="card-body">
{% csrf_token %}
{{form}}
<input type="Submit" name="Submit">
</div>
</form>
</div>
</div>
</div>
{% endblock %}
The problem is the new note isn't added when I submit the data. And also if anyone have other suggestions for structuring my views or making this app better I am happy to read them and learn new ways of improving my project. Sorry for long post. I am really noob.
I have a registration form and am adding a user profile to add another field.
after the registration form is filled and submitted the form details are not submitted
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Assigned_Group = models.CharField(max_length=500)
def __str__(self):
return self.user.username
views.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('index')
else:
form = RegistrationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form':profile_form}
return render(request, 'registration/register.html', context )
def index(request):
if request.user.is_authenticated:
username = request.user.username
else:
username = 'not logged in'
context = {'username':username}
return render(request, 'index.html', context)
urls.py
path('Register/', views.register, name='register'),
in your html page in body you have to insert {% csrf_token %} like:
<html>
<body>
{% csrf_token %}
</body>
Inside your html form you will need to have inserted {% csrf_token %}.
See the django docs on CSRF for more information or if you are using AJAX.
For example your html will then look something like.
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Side note from the django docs (which is important).
In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.
I use UserCreationForm to render registration form in Django.
class RegisterForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields
The registration view is defined as follows:
def register(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
context = {'form': form}
return render(request, 'registration/register.html', context)
And the template for this:
{% if form.errors %}
<p>Some Errors occured</p>
{% endif %}
<form action="{% url 'register' %}" method="POST">
{% csrf_token %} {{ form.as_p }}
<input type="submit" value="Register">
</form>
When I submit invalid data, it does not show <p>Some Errors occured</p>, but throws
Exception Type: ValueError
Exception Value:
The view myapp.views.register didn't return an HttpResponse object. It returned None instead.
which means I have to return HttpResponsein the 2nd if/else statement. The other forms work fine and show form.error messages, except this one. What is the problem? Thanks.
form = RegisterForm(request.POST or None, request.FILES or None)
first of all you dont wanna an empty field in your register form so you dont wanna user or None . second you are using request.FILES while you have no FileField in your form . i fixed your form
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
form = RegisterForm()
return render(request, 'registration/register.html',{'form': form})
You need to move the last line back one indent, so it is run both in the case that the request is not a POST and also when it is a POST but the form is not valid.
So I just created a form and keep getting this error, why? I correctly use the Cleaned_data after I checked if the form is valid, right?
This is my forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
username = forms.CharField(max_length=10)
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password']
This is my views.py:
class UserFormView(View):
form_class = UserForm
template_name = 'Home/index.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.Cleaned_data['username']
password = form.Cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('Home:Dashboard')
return render(request, self.template_name, {'form': form})
My urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register$', views.UserFormView.as_view(), name='register'),]
and the form location:
<form action="/register" method="post">
{% csrf_token %}
<ul class="contactList">
<li id="username1" class="contact">{{ form.username }}</li>
<li id="email1" class="contact">{{ form.email }}</li>
<li id="password1" class="contact">{{ form.password }}</li>
</ul>
<input type="submit" value="Submit">
</form>
There are other topics about this issue but I could not get any help out of them, as most people didn't include the if form.is_valid(), but in my case I do.
Use form.cleaned_data.get('username') instead of form.Cleaned_data
Edit
Use FormView
from django.views.generic.edit import FormView
class UserFormView(FormView):
form_class = UserForm
template_name = 'Home/index.html'
def form_valid(self, form):
user = form.save(commit=False)
username = form.cleaned_data.get('username')
...
get_form_class returns the class of the form i.e UserForm. You need is a object of that class. The class does not have any attribute cleaned_data.