I am new to django . here I want to register user and I have a problem , the user form doesnt show in registration html page
here is my code:
views.py :
enter code here
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import View
from .forms import UserForm
from .models import Album
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
# display blank form
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)
# cleaned (Normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# return user objects if info r correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('music:index')
return render(request, self.template_name, {'form': form})
form.py :
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
I think there is nothing wrong with url.py as long as the page pops up, I dunno where I'm mistaken
Related
iam new to django.Can anyone send me the code of signup and login page to get particular details of the username without using django.contrib.auth.models import User.
(i.e if we login with some usename then it should only give details of that username not remaining).
Find view you want manipulate user in, declare user like current_user = request.user. I will provide you my login and register views below. In examples shown below I had from django.contrib.auth.models import User, but you can modify it as shown above.
Register:
def registerPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
email = request.POST.get('email')
if form.is_valid():
if check_does_email_already_exist(email):
form.save()
messages.success(request, "User is registered sucessfully")
return redirect('todoapp:login')
else:
messages.warning(
request, "User with same email already exist")
else:
messages.warning(
request, "That username already exist or your password is too short")
context = {
'form': form,
}
return render(request, 'register.html', context)
Login:
def loginPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
if request.method == 'POST':
username = request.POST.get('uname')
password = request.POST.get('passwd')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('todoapp:home')
else:
messages.warning(
request, "Your password or username isn't valid")
return redirect('todoapp:login')
else:
pass
return render(request, 'login.html')
These are my imports:
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import CreateUserForm
And this is my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.forms import fields
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
I hope my answer will help you.
i have setup the forms in the frontend what i want is that any User if gives his username for example username-> helloworld then it is interpreted as #helloworld and then this form with changed #username should be saved in the database so that i can use it afterwards.....
i am a noob in django framework .
i have been trying since last 2 days to find a answer here and by using google but unable to find a helpful answer
here is my ->forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
this is my -> views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import SignUpForm
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
UserModel = get_user_model()
#index and signin def have been removed because it is out of context of question
def signup(request):
if request.user.is_authenticated:
return redirect('index')
else:
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
User.username = "#{}".format(User.username)
user.is_active = False
user = form.save
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('activation_mail.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
Just override your form's save method to alter the data before saving.
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
def save(self, *args, **kwargs):
self.instance.username = f"#{self.instance.username}"
return super().save(*args, **kwargs)
I was just watching a tutorial in youtube and i was just following what was indicated buti still got those errors.
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(max_length = 50)
class Meta:
model : User
fields = ['username', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('home')
else:
form = UserRegisterForm()
return render (request, 'users/register.html', {'form':form})
I am trying to achieve two different views: one for registration purpose and one for login purpose.
Now, the registration process works perfectly but the authentication process does not.
Here's the code:
in forms.py the first form called UserForm is used to sign up users, the second form called LoginForm is used to log in users.
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password']
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
in views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Step, Cycle, Program, MotorSetting, GeneralSetting
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .forms import UserForm
from .forms import LoginForm
class UserFormView(View):
form_class = UserForm
template_name = 'programs/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
#storing the data but NOT SAVING them to db yet
user = form.save(commit=False)
#cleaning and normalizing data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
#saving to db
user.save()
#if credentials are correct, this returns a user object
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('programs:index')
return render(request, self.template_name, {'form': form})
class LoginFormView(View):
form_class = LoginForm
template_name = 'programs/login_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
#storing the data but NOT SAVING them to db yet
user = form.save(commit=False)
#if credentials are correct, this returns a user object
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('programs:index')
return render(request, self.template_name, {'form': form})
in app/urls.py
from django.conf.urls import include, url
from . import views
app_name = 'programs'
urlpatterns = [
#register page
url(r'^register/$', views.UserFormView.as_view(), name='register'),
#login page
url(r'^login/$', views.LoginFormView.as_view(), name='login'),
]
The registration process goes smoothly, the authentication/login does not. When I fill in the form to login and press send, nothing happens apart from the form getting blank again.
Is there any error I'm not seeing in the code?
Many thanks!
my views.py:
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.generic import View
from .forms import LoginForm, RegistrationForm
class Login(View):
form_class = LoginForm
initial = {'key': 'value'}
template_name = 'web/login.html'
def get(self, request):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request):
if request.method == 'POST':
form = self.form_class(initial=self.initial)
if form.is_valid():
email=form.cleaned_data['email']
password=form.cleaned_data['password']
auser = User.objects.get(email=email)
username = auser.username
buser = authenticate(username, password)
if buser:
if buser.is_active:
login(request, buser)
return HttpResponse('Good to Go...')
else:
return HttpResponse('your account is disabled...')
else:
print "Invalid login details: {0}, {1}".format(email, password)
HttpResponse('invalid login details...')
else:
return HttpResponse('Form is not valid!')
else:
form = self.form_class()
Here above I'm trying to login a user using email as unique field in class based views. But It raises 'Form is not valid!' as I specified in my views. I don't know what's going wrong with it exactly. Please Help me how to fix it?
Thanks in Advance
You need to change the post method of this class:
def post(self, request):
if request.method == 'POST':
form = self.form_class(data=self.request.POST)
if form.is_valid():
.....