0

I am doing a project in which I have created a model form for employee details. Now, I want the user to be able to update only their records through the employee form and the URL of this employee form is dynamic.

In this project, I am populating the user authentication model from views.py and have not provided the option for creating the user from the front end because the idea behind not providing the option for user creation from the front end is to create a user automatically when someone creates a new employee record.

So, to populate the user authentication model, for the employee whose record has been created recently. I am applying the concatenation on the first name, last name and on the primary key to generate a user name and for the password, I am generating a random password.

on the home page, I have generated a list view of Employee records and also provided a link for view (to see the complete details of a particular employee) and another link for updating the records which is a dynamic URL (update/<int: id>/).

Now, I want the user to be able to only update his record not someone else's and this is the part I am struggling with.

models.py

from django.db import models

# Create your models here.

class Department(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Designation(models.Model):
    name = models.CharField(max_length=50)
    department_id = models.ForeignKey(Department, on_delete=models.CASCADE, default='')

    def __str__(self):
        return self.name

class Country(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class State(models.Model):
    name = models.CharField(max_length=50)
    country_id = models.ForeignKey(Country, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length=50)
    state_id = models.ForeignKey(State, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class Employee(models.Model):
    emp_id = models.AutoField(primary_key=True)
    emp_first_name = models.CharField(max_length=50)
    emp_last_name = models.CharField(max_length=50, default='')
    email = models.EmailField()
    salary = models.IntegerField()
    joining_date = models.DateField()
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True)
    designation = models.ForeignKey(Designation, on_delete=models.SET_NULL, null=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
    # system generated password when created the record
    sys_gen_pass = models.CharField(max_length=50, blank=True)

    def __str__(self):
        return self.emp_name

forms.py

from bootstrap_datepicker_plus import DatePickerInput
from django import forms
from .models import Employee

class EmployeeForm(forms.ModelForm):
    class Meta:
        model= Employee
        fields= '__all__'

        widgets = {
            'joining_date': DatePickerInput(),
        }

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('home/', views.home, name='home'),
    path('new/', views.new, name='new'),
    path('detail/<int:id>/', views.detail, name='detail'),
    path('delete/<int:id>/', views.delete, name='delete'),
    path('update/<int:id>/', views.update, name='update'),
    path('load_state/', views.load_state, name='load_state'),
    path('load_city/', views.load_city, name='load_city'),
    path('load_designation/', views.load_designation, name='load_designation'),
    path('loginuser/', views.loginuser, name='loginuser'),
    path('logoutuser/', views.logoutuser, name='logoutuser'),
]

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from .forms import EmployeeForm
from .models import *
import random

# Create your views here.

def home(request):
    emp = Employee.objects.all()
    return render(request, 'home.html', {'employees': emp})

def new(request):
    if request.method == 'GET':
        form = EmployeeForm
        return render(request, 'new.html', {'form': form})
    else:
        form = EmployeeForm(request.POST)
        if form.is_valid():
            # here I am generating a password for every employee created
            string = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_=+-[]{};:,./<>?"
            password_length = 12
            password = "".join(random.sample(string, password_length))
            form.save()
            # here I am updating the password in model
            latest=Employee.objects.last()
            latest.sys_gen_pass = password
            latest.save()
            # here I am creating user for which I have just added a record
            # the user_name = First_name+last_name+PrimaryKey and the password will be what I have just created
            # for that I am removing the spaces from Employee_Name field
            def remove(string):
                return string.replace(" ", "")
            e_name = remove(latest.emp_first_name) + remove(latest.emp_last_name) + str(latest.emp_id)
            e_email = latest.email
            user_password = latest.sys_gen_pass
            # Creating user and saving it to the database
            user = User.objects.create_user(e_name, e_email, user_password)
            user.first_name = latest.emp_first_name
            user.last_name  = latest.emp_last_name
            user.save()
            return redirect('home')

def loginuser(request):
    if request.method == 'GET':
        return render(request, 'loginuser.html', {'form': AuthenticationForm})
    else:
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'],)
        if user is None:
            return render(request, 'loginuser.html', {'form': AuthenticationForm, 'error': 'user does not exist or invalid password'})
        else:
            login(request, user)
            return redirect('home')

def logoutuser(request):
    if request.method == "POST":
        logout(request)
        return redirect('home')


def detail(request, id):
    emp_details = Employee.objects.get(pk = id)
    return render(request, 'detail.html', {'emp_details': emp_details})

def delete(request, id):
    emp_remove = Employee.objects.get(pk = id)
    emp_remove.delete()
    # return render(request, 'delete.html')
    return redirect('home')

@login_required(login_url='loginuser')
# @permission_required(login_url='')
def update(request, id):
    emp_id = Employee.objects.get(pk=id)
    if request.method == 'GET':
        form = EmployeeForm(instance=emp_id)
        return render(request, 'update.html', {'form': form})
    else:
        form = EmployeeForm(request.POST, instance=emp_id)
        if form.is_valid():
            form.save()
            print(id)
            return redirect('detail', id = id)
            # return redirect('detail/', id = emp_id)
    return render(request, 'update.html', {'form': form})

def load_designation(request):
    # print('designation')
    department_id = request.GET.get('department')
    designations = Designation.objects.filter(department_id = department_id).order_by('name')
    return render(request, 'load_designation.html', {'designations': designations})

def load_state(request):
    # print('state')
    country_id = request.GET.get('country')
    states = State.objects.filter(country_id = country_id).order_by('name')
    return render(request, 'load_state.html', {'states': states})

def load_city(request):
    # print('city')
    state_id = request.GET.get('state')
    cities = City.objects.filter(state_id = state_id).order_by('name')
    return render(request, 'load_city.html', {'cities': cities})

3 Answers3

0

I didn't go through your code because it's a lot to look at.

Your last line of the description is your question I believe.

Now, I want the user to be able to only update his record not someone else's and this is the part I am struggling with.

The answer is, in the list view of Employee records, you should display records only of that particular user so that he can only update his records. I hope it helps.

0

You could be using a button "Update Info" which shows the user a page with their data so that they update the data. You should only display the data of the user who requested that page and when they alter the data, it should only save the changes into their data, not any other user's data.

In the template that displays the user's information, you should first check whether the user requested their own info or another user's info. After displaying the requested user's data, use an if condition, if the user requested their own info, the "Update Info" button will show, and if the user requested for another user's info, the "Update Info" button will not show.

Nduati
  • 75
  • 6
0
@login_required(login_url='loginuser')
def update(request, sys_gen_user):

    # here I am getting the user name of current logged in user.
    if request.user.is_authenticated:
        username = request.user.username

    # comparing with the user_name(sys_gen_user) saved in Employee Table with the user name of current logged in user.
    if username == sys_gen_user:
        emp_id = Employee.objects.get(sys_gen_user=sys_gen_user)
        if request.method == 'GET':
            form = EmployeeForm(instance=emp_id)
            return render(request, 'update.html', {'form': form})
        else:
            form = EmployeeForm(request.POST, instance=emp_id)
            if form.is_valid():
                form.save()