def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("main:homepage")
else:
messages.error(request, "Invalid Username or Password!!")
else:
messages.error(request, "Invalid Username or Password!!")
form = AuthenticationForm
return render(request, "main/login.html", {"form": form})
I want to render 'form' on a modal for user login but as modal don't have their own URL, how can I render it, for above code I've taken 'main/login.html' as the template before using modal
Related
Function to let the user to login as follows=>
Obviously this error pops:
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password =password )
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
elif user is None:
return render(request, "covi/signin.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "covi/signin.html")
It's because
user = authenticate(request, username=username, password =password) runs only if request.method == 'POST'. If you do a GET request user won't be assigned.
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password =password )
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
elif user is None:
return render(request, "covi/signin.html", {
"message": "Invalid username and/or password."
})
return render(request, "covi/signin.html")
I was working on an e-commerce website using Django for which I created a customer model in models.py
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
and when I register a new user on my site using this view:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.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('store')
else:
form = SignUpForm()
return render(request, 'store/signup.html', {'form': form})
The user gets created but I get the error RelatedObjectDoesNotExist: User has no Customer
I know it's because the User model is created but not Customer, I'm new to Django and want to know a way to map these two models at the time of registration.
In views.py when you register the user you can also a create a customer modal ıf its what you want. If so try this:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
Customer.objects.create(user=user,name=username,email=email) // get the email from the form
login(request, user)
return redirect('store')
else:
form = SignUpForm()
return render(request, 'store/signup.html', {'form': form})
Also can add your customer modal ın admin panel and manually add your customer info just for demonstration.
How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view .
I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the
database.
(Dont use forms.py)
Accounts/views.py
def register(request):
if request.method == 'POST':
#get form values
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
#Check if passwords match
if password == password2:
#check username
if User.objects.filter(username = username).exists():
messages.error(request,'That username is taken')
return redirect('register')
else:
if User.objects.filter(email=email).exists():
messages.error(request,'That email is being used')
return redirect('register')
else:
#looks good
user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name)
#login after register
# auth.login(request, user)
# messages.success(request, 'You are now logged in')
# return redirect('index')
user.save()
messages.success(request, 'You are now registered and can log in')
return redirect('login')
else:
messages.error(request,'passwords do not match')
return redirect('register')
else:
return render(request, 'accounts/register.html')
I don't think there is a possible way to edit profile and change a password in the same view without use forms.py, but the django.contrib.auth.forms has a PasswordChangeForm and a UserChangeForm which you can use.
Se more in documentation: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
In your views.py
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
def edit_profile(request):
if request.method == "POST":
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.info(request, "Ok")
return redirect("main:homepage")
else:
messages.error(request, "Error")
return redirect("main:edit_profile")
else:
form = UserChangeForm(instance=request.user)
return render(request, "main/edit-profile.html", {'form': form})
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
messages.info(request, "ok")
update_session_auth_hash(request, form.user)
return redirect("main:edit_profile")
else:
messages.error(request, "error")
return redirect("main:change_password")
else:
form = PasswordChangeForm(user=request.user)
return render(request, "main/change-password.html", {'form': form})
I have a form that inherits from the UserCreationForm. The file looks like this:
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from main.models.users import MyUser
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
group = forms.CharField(max_length=50, required=True)
class Meta:
model = MyUser
fields = ("group", "email", "username", "email", "password1", "password2")
def save(self, commit=True):
user = super(MyUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
For some reason, when trying to fill up the form, I get a password mismatch error like so:
ERROR - {'password_mismatch': "The two password fields didn't match."}
I tried overriding the clean_password1 and clean_password2 with no help. Code:
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
# Method inherited from BaseForm
self.add_error('password1', error)
return password1
Any ideas why this is happening? Why is it thinking that both of my passwords are not identical? I'm sure they are, as I tried a million times and even copy and pasted.
view:
def register(request):
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
print(f"Valid form. Choosen group: {form.cleaned_data.get('group')}")
user = form.save()
group = Group.objects.get(name=form.cleaned_data.get('group'))
user.groups.add(group)
login(request, user)
messages.success(request, f"Thanks, {form.cleaned_data.get('username')}, "
f"for signing up as a {form.cleaned_data.get('group')} ")
return redirect('main:homepage')
else:
logger.error(form.error_messages)
for msg in form.error_messages:
messages.error(request, f'{msg}: {form.error_messages[msg]}')
return render(request,
template_name='main/register.html',
context={'form': form})
else:
form = MyUserCreationForm()
return render(request,
template_name='main/register.html',
context={'form': form})
i am not sure about code but you can try this
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
#inhereting Usercreation form
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
#validating the password match while creating the user.
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('home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
this is my signup view ->
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
print('hello')
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
account = Account(user=user)
account.save()
login(request, user)
return redirect('/gallery/index')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})
this is my accounts model ->
class Account(models.Model):
user = models.OneToOneField(User,
related_name="profile",on_delete=models.CASCADE)
following=models.ManyToManyField(User,related_name="followers",null=True,blank=True)
this is the error I am getting -
The view accounts.views.signup didn't return an HttpResponse object.
It returned None instead.
I am getting this error whenever I submit the form. I am using the django admin signup form by default
Try
def signup(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
print('hello')
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
account = Account(user=user)
account.save()
login(request, user)
return redirect('/gallery/index')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})