Having an option of switching roles and status in a form - python

I have an employee model entailing the below
class Employee(models.Model):
STATUS = (
('Active', 'Active'),
('Blocked', 'Blocked'),
)
ROLE = (
('Employee', 'Employee'),
('User', 'User'),
)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
password = models.CharField(max_length=200, null=True)
status = models.CharField(max_length=200, null=True,choices=STATUS)
role = models.CharField(max_length=200, null=True, choices=ROLE)
def __str__(self):
return self.first_name
views shown below the update and new form of employee
#login_required(login_url='login')
def deleteProfile(request, pk):
employee = Employee.objects.get(id=pk)
if request.method == "POST":
employee.delete()
return redirect('/')
return render(request, 'accounts/delete_profile.html', 'employee':employee)
#login_required(login_url='login')
def NewEmployeeProfile(request):
form = EmployeeProfileForm()
if request.method == 'POST':
form = EmployeeProfileForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'accounts/new_employee_profile.html', {'form': form})
As a superuser I would like to have the decision of allocating an employee either the role of User or employee. (Any User can be able to do this once logged in) When having to update or create an employee
Also as a superuser I would like to allocate whether the employee/User has an blocked or active account (so allowing them access when they log in or not) also when having to create an employee (Any User can be able to do this once logged in)
How will this be reflected on to the view.py when it is either updated or created?

Related

How to assign a default choice value to a user when they sign up in django framework

I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted.
Models.py
class Membership(models.Model):
MEMBERSHIP_CHOICES = (
('Enterprise', 'Enterprise'), # Note that they are all capitalize//
('Team', 'Team'),
('Student', 'Student'),
('Free', 'Free')
)
PERIOD_DURATION = (
('Days', 'Days'),
('Week', 'Week'),
('Months', 'Months'),
)
slug = models.SlugField(null=True, blank=True)
membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30)
duration = models.PositiveIntegerField(default=7)
duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
def __str__(self):
return self.membership_type
#### User Membership
class UserMembership(models.Model):
user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True)
reference_code = models.CharField(max_length=100, default='', blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=UserMembership)
def create_subscription(sender, instance, *args, **kwargs):
if instance:
Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration))
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
in models you need to special a default="..." attribute

Issue Pre-populating form in Django

I'm trying to get the user profile name to populate the form field 'user' from AgendaForm but what I get "'user': None".
And, in views, in the following prints:
print(form.cleaned_data)
print(initial_data)
I get:
{'user': None, 'date': datetime.date(2021, 9, 24), 'time': datetime.time(4, 0), 'comment': 'some comment', 'mode': 'ONLINE'}
{'user': <Profile: Jhon Doe>}
views.py
#login_required(login_url='login')
#allowed_users(allowed_roles=['user'])
def agenda(request):
user = request.user.profile
initial_data = {
'user': user
}
form = AgendaForm(initial=initial_data)
if request.method == 'POST':
form = AgendaForm(request.POST, initial=initial_data)
if form.is_valid():
form.save()
print(form.cleaned_data)
print(initial_data)
context = {'form': form}
return render(request, 'agenda.html', context)
agenda.models.py
class Agenda(models.Model):
user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
date = models.DateField(null=True, blank=True, default="1900-01-11")
...
def __str__(self):
return '%s' % (self.user)
main.models.py
#(The OneToOneField 'User' comes from the UserCreationForm Django function)
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
id = models.AutoField(primary_key=True, null=False, blank=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
...
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
The objects you pass in initial is only used for displaying purposes to show some initial values, and not as fallback/default values. So if there is no user data found in request.POST, it will default to None.
From the docs:
These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided.
This means if the post data does not have user, it will default to None.
If you want to set the agenda's user FK to the profile of the current user, you can do:
if request.method == 'POST':
form = AgendaForm(request.POST, initial=initial_data)
if form.is_valid():
agenda = form.save(commit=False)
agenda.user = request.user.profile
agenda.save()

Allow the user to input only a part of django model creaton form (add to form after user submitted it)

How I can add data to form that user submitted ? I want the user to fill in the "name" and "done" in the form and automatically add "user" (creator) and "board"
code:
#views.py
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = Board.objects.filter(user=request.user).get(pk=pk)
form = AddTaskForm()
if request.method == "POST":
form = AddTaskForm(request.POST)
if form.is_valid():
form.initial['user'] = request.user
form.initial['board'] = board
# that doesn't seem to work....
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
#forms.py
class AddTaskForm(ModelForm):
class Meta:
model = Task
fields = "__all__"
exclude = ('user', 'board',)
#models.py
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
You can edit the instance wrapped in the form:
from django.shortcuts import get_object_or_404
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = get_object_or_404(Board, user=request.user, pk=pk)
form = AddTaskForm()
if request.method == 'POST':
form = AddTaskForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.board_id = pk
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.

Query user in Django

first post here. Im trying to query the user so i from the form so i can save the user in my database.
This is my code
form = lageBruker(request.POST)
bruker = User.objects.create(format(request.POST['username']))
print()
if request.method == 'POST':
if form.is_valid():
fornavn = request.POST['first_name']
etternavn = request.POST['last_name']
email = request.POST['email']
kunde = Kunde.objects.create(
#bruker = bruker,
fornavn=fornavn,
etternavn=etternavn,
email=email
)
kunde.save()
context = {'form': form}
return render(request, 'ebutikk/registrer.html', context)
Kunde Model:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
fornavn = models.CharField(max_length=200, null=True, blank=True)
etternavn = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.etternavn
What im trying to do is, when the registration form is submittet, i want to save the registerd user as a kunde/customer. I dont have a User model, i use the default made by django with the import:
from django.contrib.auth.models import User
I make the form by importing the user creation form given by django and customizing it im my forms.py file.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class lageBruker(UserCreationForm):
class Meta:
model = User
fields = ['username',
'email',
'first_name',
'last_name',
'password1',
'password2']
Normally, you'd simply create the Kunde model like this:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
# more fields here, so the model makes sense
#property
def fornavn(self): return self.user.first_name
#property
def etternavn(self): return self.user.last_name
#property
def email(self): return self.user.email
Then all you need to do is:
def customer_signup_view(self, request):
if request.method == "POST":
form = lageBruker(request.POST)
# Saving the model form returns the user created
user = form.save()
# Now use that user to create a new customer
Kunde.objects.create(user=user)
return redirect("success/")
return render(request, 'ebutikk/registrer.html', {"form": lageBruker())

Suppress django signal

I have been struggling with this for a couple of weeks now and It seems, I can't get it to work.
As you sign up on my website, you are able to create a userprofile and a company. Then, you are able to add members to your company, however the signal just fires everytime and creates empty companies. How do I stop django from doing this?
model.py
class Companyname(models.Model):
company_name = models.CharField(max_length=100, default = '', null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
def __str__(self):
return self.company_name
#receiver(post_save, sender=User)
def update_user_company(sender, instance, created, **kwargs):
if created:
Companyname.objects.create(user=instance)
if instance.companyname.company_name is '':
print("just print this")
else:
instance.companyname.save()
the company gets stored on the userprofile
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default = '', null=True, blank=True)
company = models.ForeignKey(Companyname, null=True, on_delete=models.CASCADE)
role = models.ForeignKey(Role, null=True, on_delete=models.CASCADE)
team = models.ForeignKey(Team, null=True, on_delete=models.CASCADE)
company_admin = models.BooleanField(default=False)
add_user view.py
def add_user(request):
if request.method == 'POST':
form = AddUserForm(request.POST)
if form.is_valid():
company = request.user.userprofile.company_id
form.save()
user = form.save()
user.refresh_from_db()
user.userprofile.company_id = company
user.userprofile.role = form.cleaned_data.get('role')
user.is_active = False
user.save()
register view.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.userprofile.description = form.cleaned_data.get('description')
user.companyname.company_name = form.cleaned_data.get('company_name')
user.userprofile.company_id = user.companyname.id
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('/account/my_product')
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
Hope someone can help :)

Categories