在 Django 中生成动态链接:公司和员工

Generate Dynamic Links in Django : Company and Employee

我正在用 Django 做一个项目,这是一个员工管理系统。

我制作了公司主页,我们可以在其中选择添加新公司、删除以前的公司或删除它。

现在我希望当我点击那个公司名称时,它会为那个特定的公司名称生成一个动态 link(它将具有添加、删除和编辑员工的相同功能)

目前,我卡住了。无法为每个提供员工详细信息的公司生成动态 links。

这是我的 Models.py 文件

from datetime import date, datetime
from django.db import models
from django.db.models.fields.related import ForeignKey
from django.utils import timezone
# Create your models here.

class companyModel(models.Model):
    company_name = models.CharField(max_length=100,blank=False)
    company_created = models.DateField(default=datetime.now,blank=False)

class employeeModel(models.Model):
    employee_company_name = models.ForeignKey(companyModel,on_delete=models.CASCADE)
    employee_name = models.CharField(max_length=100,blank=False)
    employee_created = models.DateField(default=datetime.now,blank=False)

Forms.py 文件

from django import forms
from django.forms import widgets
from empman.models import companyModel,employeeModel

class companyForm(forms.ModelForm):
    class Meta:
        model = companyModel
        fields = ['company_name','company_created']
        widgets = {
            'company_name' : forms.TextInput(attrs={'class':'form-control '}),
            'company_created':forms.TextInput(attrs={'class':'form-control'})
        }

class employeeForm(forms.ModelForm):    
    class Meta:
        model = employeeModel
        fields = ['employee_company_name','employee_name','employee_created']

Views.py 文件

from django import forms
from django.shortcuts import render,HttpResponsePermanentRedirect
from empman.forms import companyForm,employeeForm
from empman.models import companyModel,employeeModel
# Create your views here.
def companyShowView(request):
    if request.method == 'POST':
        form = companyForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponsePermanentRedirect('/')
    else:
        form = companyForm()
    
    comp = companyModel.objects.all()
    return render(request,'empman/companyshow.html',{'form':form,'comp':comp})

def editCompany(request,id):
    if request.method == 'POST':
        uniqueid = companyModel.objects.get(pk=id)
        requestpost = companyForm(request.POST,instance=uniqueid)
        if requestpost.is_valid():
            requestpost.save()
            return HttpResponsePermanentRedirect('/')
    else:
        uniqueid = companyModel.objects.get(pk=id)
        requestpost = companyForm(instance=uniqueid)
    return render(request,'empman/companyupdate.html',{'form':requestpost})

def deleteCompany(request,id):
    if request.method == 'POST':
        dele=companyModel.objects.get(pk=id)
        dele.delete()
        return HttpResponsePermanentRedirect('/')


# def viewEmployee(request,id):
#     print(id)
#     return render(request,'empman/employeeshow.html')

def viewEmployee(request,id):
    showemps = employeeModel.objects.all()
    return render(request,'empman/employeeshow.html')

def employeeShowView(request):
    if request.method == 'POST':
        empform = employeeForm(request.POST)
        if empform.is_valid():
            empform.save()
            
    else:
        form = employeeForm()
    
    emp = employeeModel.objects.all()
    return render(request,'empman/employeeshow.html',{'empform':empform,'emp':emp})

urls.py 文件

# from mysite.empman.views import editCompany
from django.contrib import admin
from django.urls import path
from empman import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.companyShowView,name='index'),
    path('delete/<int:id>',views.deleteCompany,name='deletecomp'),
    path('<int:id>/edit',views.editCompany,name='editcomp'),
    path('<int:id>/employee/',views.viewEmployee,name='showemp')
]

companyShow.html

{% extends 'empman/base.html' %}

{% block content %}
<p></p>
<center>
<div class="col-sm-3">
    <h4 class="alert alert-info">Add new Company</h4>
    <form class="form-control" method="POST">
    {% csrf_token %}
    {{ form }}
    <p></p>
    <input type="submit" class="btn btn-warning" value="ADD" id="add">
</form>
</div>
<div class="col-sm-10">
    <p></p>
    <h4 class="alert alert-info">Here is the list of companies</h4>
    <table class="table table-hover">
        <th class="thead-dark">
        <tr>
            <th scope="col">Sr</th>
            <th scope="col">Company Name</th>
            <th scope="col">Creation Date</th>
            <th scope="col">Operations</th>
        </tr> 
        </th> 
        <tbody>
          {% for comps in comp %}  
          <tr>
            <th scope="col">{{comps.id}}</th>
            <th scope="col"><a href="{% url 'showemp' comps.id %}">{{comps.company_name}}</a></th>
            <th scope="col">{{comps.company_created}}</th>
            <td>
                <!-- <a href="{% url 'showemp' comps.id %}" class="btn btn-success btn-sm">View</a> -->
                <a href="{% url 'editcomp' comps.id %}" class="btn btn-warning btn-sm">Edit</a>
                <form action="{% url 'deletecomp' comps.id %}" method="POST" class="d-inline">
                    {% csrf_token %}
                    <input type="submit" value="Delete" class="btn btn-danger">
                </form>
            </td>
          </tr>
        </tbody>
        {% endfor %}
</div>
</center>
{% endblock content %}

employeeShow.html

{% extends 'empman/base.html' %}

{% block content %}
<p></p>
<center>
<div class="col-sm-3">
    <h4 class="alert alert-info">Add new Employee</h4>
    <form class="form-control" method="POST">
    {% csrf_token %}
    {{empform}}
    <p></p>
    <input type="submit" class="btn btn-warning" value="ADD" id="add">
</form>
</div>
<div class="col-sm-10">
    <p></p>
    <h4 class="alert alert-info">Employees for {{eachshowemps.employee_company_name.company_name}}</h4>
    <table class="table table-hover">
        <th class="thead-dark">
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Employee Name</th>
            <th scope="col">Joining Date</th>
            <th scope="col">Operations</th>
        </tr> 
        </th> 
        <tbody>
          {% for eachshowemps in showemps %}  
          <tr>
            <th scope="col">{{eachshowemps.id}}</th>
            <th scope="col">{{eachshowemps.employee_name}}</th>
            <th scope="col">{{eachshowemps.employee_created}}</th>
            <td>
                <a href="" class="btn btn-success btn-sm">Edit</a>
                <a href="" class="btn btn-warning btn-sm">Delete</a>
            </td>
          </tr>
        </tbody>
        {% endfor %}
</div>
</center>
{% endblock content %}

目前,我公司的编辑和删除功能正常

您的 viewEmployee 函数应该 return CompanyModel 实例而不是 employeeModel

的所有查询集
def viewEmployee(request,id):
    company = companyModel.objects.get(id=id)
    employess = company.employeemodel_set.all() #employess of that company
    return render(request,'empman/employeeshow.html', {'company':company, 'showemps':employees})

也请考虑为您的视图使用有意义的名称。