I am working on creating a page for each user, how do i lookup a username in my django user model
views.py
def user_page(request,user):
user = User.objects.filter(user =user.username)
return render_to_response('user_page.html',"user":user,context_instance=RequestContext(request))
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
def user_page(request, username):
user = get_object_or_404(User, username=username)
return render_to_response('user_page.html',{"user":user},context_instance=RequestContext(request))
def user_page(request,username):
user = User.objects.filter(username=username)
return render_to_response('user_page.html',{"user":user},context_instance=RequestContext(request))
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 am trying to implement a custom user model. Whenever I try to log in for a user (created using the registration form), it returns no user.
but if I create a user using the admin panel then the login function works perfectly.
I think the problem is with password hashing. Tried some solve from here and there but seems like I can't find what I am looking for.
The problem I am having :
email: yeamin21#outlook.com
pass: 1234 works (created using admin panel)
but, email: yeamin21#outlook.com
pass: hashed(1234) does not (created using the registration form)
models.py
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractBaseUser):
username = models.CharField(max_length=30,unique=True)
email = models.EmailField(verbose_name='Email',unique=True)
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
def __str__(self):
return self.name
class Restaurant(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
location = models.CharField(max_length=200)
def __str__(self):
return self.user.email
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from Customer.models import User, Restaurant
class RestaurantSignUpForm(UserCreationForm):
class Meta(UserCreationForm):
model = User
fields = ['email','name','username']
#transaction.atomic
def save(self, commit=True):
user = super().save(commit=False)
user.is_restaurant=True
user.is_active=True
user.save()
restaurant = Restaurant.objects.create(user=user)
restaurant.save()
return user
backend.py
from django.contrib.auth.backends import BaseBackend, ModelBackend
from Customer.models import User
class CustomBackend(ModelBackend):
def authenticate(self,email=None,password=None):
try:
user=User.objects.get(email=email)
print('active')
if user.check_password(password) is True:
return user
except User.DoesNotExist:
return None
return User.objects.get(email=User.email)
def get_user(self, email):
try:
return User.objects.get(email)
except User.DoesNotExist:
return None
views.py
from django.contrib.auth import login, authenticate
from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
from Customer.forms import RestaurantSignUpForm
from Customer.models import User
def login_page(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
print(user)
if user is not None:
login(request, user)
return HttpResponse("Logged in")
else:
print(user)
context = {}
return render(request, 'login.html', context)
The problem is fixed
thanks to this https://stackoverflow.com/a/48971226/10602634
def authenticate(self, request, email=None, password=None):
try:
user= User.objects.get(email=email)
if check_password(password, user.password):
return user
except User.DoesNotExist:
return None
I'm trying to login a user who was previously registered in a database, but the form.is_valid() returns False and the login() function doesn't work. I extended the User class with a Client class that is inheriting from User, and I think this is what is causing the issue, because I tried almost the same code before, but without the extended User class, and it worked perfectly. What am I doing wrong?
My models.py:
from django.db import models
from django.contrib.auth.models import User
class Client(User):
address = models.CharField(max_length=255)
state = models.CharField(max_length=255, null=True)
city = models.CharField(max_length=255,null=True)
phone = models.IntegerField()
My forms.py:
from django.contrib.auth.models import User
class Auth(forms.ModelForm):
class Meta:
model = User #I tried here both User and Client and returns the same result (form isn't valid)
fields = [
'username',
'password',
]
labels = {
'username': '',
'password': '',
}
widgets = {
'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Usuario', 'style':'margin-bottom:15px'}),
'password': forms.PasswordInput(attrs={'class':'form-control','placeholder':'Contraseña'}),
}
My views.py:
from django.shortcuts import render
from .models import Cart
from .forms import Auth
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
def main(request):
productos = Cart.objects.all()
users=User.objects.all()
if request.method == 'POST':
if request.user.is_authenticated:
messages.warning(request,'Ya existe un usuario autenticado')
return redirect('main')
else:
form = Auth(request.POST)
if form.is_valid():
user=form['username'].value()
password=form['password'].value()
authuser=authenticate(request,username=user,password=password)
if authuser is not None:
login(request, authuser)
messages.success(request, 'Bienvenido')
return redirect('main')
else:
messages.error(request, 'Credenciales no válidas')
return redirect('main')
else:
form = Auth()
return render(request, 'index.html', {"form": form, 'productos':productos,'users':users})
The authenticate() function returns the right value, so the authuser variable is not None. But I don't know why the login() function does nothing, even when I try to login the user from the admin interface.
First you shouldn't use inherit of the Django base User:
from django.contrib.auth.models import User
If you whant extand the django user classe, use this one:
from django.contrib.auth.models import AbstractUser
Here is the link from the django docs: link
Here is an other link if find useful: link
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
I have a model called Employee for the registration. When I run the code I go the
username' is an invalid keyword argument for this function
error.
employee=Employee(user=user, username= form.cleaned_data['username'], email= form.cleaned_data['email'], password=form.cleaned_data['password'])
this is my view.py code
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from Employee_Details.forms import RegistationForm
from Employee_Details.models import Employee
def EmployeeRegistation(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method=='POST':
form=RegistationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username= form.cleaned_data['username'],email= form.cleaned_data['email'],password=form.cleaned_data['password'])
user.save()
employee=Employee(user=user, username= form.cleaned_data['username'],email= form.cleaned_data['email'],password=form.cleaned_data['password'])
employee.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('registation.html',{"form":form}, context_instance=RequestContext(request))
else:
'''user is not submitting the form show a blank Registation Form'''
form=RegistationForm();
context={'form':form}
return render_to_response('registation.html',context,context_instance=RequestContext(request))
This is my model:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Employee(models.Model):
user=models.OneToOneField(User)
name=models.CharField(max_length=100)
address=models.CharField(max_length=200)
designation=models.CharField(max_length=100)
email=models.CharField(max_length=100)
role=models.CharField(max_length=10)
#image=models.ImageField()
project=models.CharField(max_length=50)
task=models.CharField(max_length=50)
def __unicode(self):
return self.name
This is my form.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from Employee_Details.models import Employee
class RegistationForm(ModelForm):
username=forms.CharField(label=(u'User Name'))
email=forms.EmailField(label=(u'Email Address'))
password=forms.CharField(label=(u'Password'))
password1=forms.CharField(label=(u'Verfy Password'))
name=forms.CharField(label=(u'Name'))
address=forms.CharField(label=(u'Address'))
designation=forms.CharField(label=(u'Designation'))
role=forms.CharField(label=(u'Role'))
#image=models.ImageField()
project=forms.CharField(label=(u'Project'))
task=forms.CharField(label=(u'Task'))
class Meta:
model=Employee
exclude=('user',)
def clean_username(self):
username=self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('The username is already taken. Please try with another')
def clean(self):
if self.cleaned_data['password'] !=self.cleaned_data['password1']:
raise forms.ValidationError("The Password did not match. Please try again")
return self.cleaned_data
please someone help help me to resolve this matter. I’m referring some video tutorials.
You have no username field in your model and it's redundant because you have that field already in the User model:
user=User.objects.create_user(username=form.cleaned_data['username'],email= form.cleaned_data['email'],password=form.cleaned_data['password'])
user.save()
employee=Employee(user=user, email=form.cleaned_data['email'], password=form.cleaned_data['password'])
(...)
try modelformset_factory instead!