I want to make a staff user by default - python

I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)?
this is my registration function...
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
context = {'form':form}
return render(request, 'pages/register.html', context)

You can alter the .instance wrapped in the form before saving it to the database:
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.instance.is_staff = True
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
return render(request, 'pages/register.html', {'form':form})

Related

How to redirecting to a page after registering a user in - Django

After a user successfully registers an account, the webpage redirected to some other locations...
I want it to redirect to a specific path, 'products/index' (products is myapp) after successful registration the user logged in automatically. I am here using function based view..
views.py
def register(request):
if request.method == 'GET':
form = RegisterForm()
context = {'form': form}
return render(request, 'register.html', context)
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('index.html')
else:
print('Form is not valid')
messages.error(request, 'Error Processing Your Request')
context = {'form': form}
return render(request, 'register.html', context)
return render(request, 'register.html', {})
#login_required
def index(request):
products = product.objects.all()
return render (request,'index.html',{'products':products})
def register(request):
if request.method == 'GET':
form = RegisterForm()
context = {'form': form}
return render(request, 'register.html', context)
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('index')
else:
print('Form is not valid')
messages.error(request, 'Error Processing Your Request')
context = {'form': form}
return render(request, 'register.html', context)
You can do something like this to redirect user
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('products:index')

Populate Django username field with generated username

I would like the user name field for my Django registration to populate with the following function -
def generateUsername():
username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr()
return username
I am currently using the UserRegisterForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also.
views.py -
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('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
forms.py -
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
firstname = forms.CharField(max_length=20)
middlename = forms.CharField(max_length=20)
lastname = forms.CharField(max_length=20)
class Meta:
model = User
fields = ['email', 'firstname', 'middlename', 'lastname']
You can set this to the user object wrapped in the form:
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
username = f"{data['firstname'][0]}{data['middlename'][0]}{data['lastname'][0]}{randomStringDigits(6)}"
form.instance.username = username
form.save()
messages.success(request, f'Account created for {username}')
return redirect('login')

Invalid syntax error in view.py in django

I can't figure out what i've done wrong here. In my views.py.
def register(request):
if request.method == 'POST'
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
def register(request):
if request.method == 'POST': #The colon is missing here
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
You are missing a colon on the following line
if request.method == 'POST'
It should look like this
if request.method == 'POST':
Your current second line needs a : statement in the end, so it should be:
if request.method == 'POST':

RelatedObjectDoesNotExist at / User has no customer

RelatedObjectDoesNotExist at / User has no customer.
I am getting this error after I register a user and attempt to sign in. I am only able to sign in with a superuser I created but not with a new user I register.
views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
form.save()
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
#THIS IS THE ERROR IT LEADS ME TO
def store(request):
data = cartData(request)
cartItems = data['cartItems']
products = Product.objects.all() # getting all the products
context = {
'products': products,
'cartItems': cartItems
} # allows us to use in our template
return render(request, 'store/store.html', context)
models.py
class Customer(models.Model):
user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name=models.CharField(max_length=50, null=True)
email=models.CharField(max_length=200)
def __str__(self):
return self.name #this will show on our admin panel
Change your model class user field like this:
user=models.OneToOneField(
User,
null=True,
blank=True,
on_delete=models.CASCADE,
related_name="customer"
)
and your register view:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
Customer.objects.create(
user = user,
name = user.username,
email = user.email
)
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
When you create user, you should create a customer for this user, for example:
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
username= form.cleaned_data.get('username')
#create customer
Customer.objects.create(user=user, name=username, email=user.email)
...

Django save() not sending to database

my from is not sending data to database
here is my view.py and form.py
And yet they are no error reported on my console
views.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
return redirect('../login/')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'account/register.html', args)
forms.py
class RegistrationForm(UserCreationForm):
# first_name forms.CharField(... that i cut here to win some space
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
You forgot to call form.save() in your view. That's why your form is never saved.
Fix:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
form.save() # <- ATTENTION.
return redirect('../login/')
else:
form = RegistrationForm()
return render(request, 'account/register.html', {
'form': form,
})
Side notes
Don't hardcode the redirect path (i.e. ../login). In your urls.py file, give the url a name (e.g. path('login/', views.my_login, name='my_login')), and use the name to do the redirect (e.g. return redirect('my_login').

Categories

Resources