首页 > 解决方案 > Django 无法在网页上查看模型中的数据

问题描述

我正在尝试构建一个项目管理系统,但我无法从网页上的模型中看到数据。我的代码如下。另外,我不确定数据是否完全存储在数据库中。

模型.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class CustomUser(AbstractUser):
    user_type_data = ((1, "Admin"), (2, "Staff"), (3, "Client"))
    user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
    
    
class AdminUser(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

class Staffs(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
    phone = models.CharField(max_length=15, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

视图.py

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from django.core.files.storage import FileSystemStorage #To upload Profile Picture
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import json

from powercons_app.models import CustomUser, AdminUser, Staffs, Projects, Tasks, Clients, Contracts
from .forms import AddClientForm, EditClientForm

def add_staff(request):
    return render(request, "admintemplate/add_staff_template.html")


def add_staff_save(request):
    if request.method != "POST":
        messages.error(request, "Invalid Method ")
        return redirect('add_staff')
    else:
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        phone = request.POST.get('phone')

        try:
            user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2)
            user.staffs.phone = phone
            user.save()
            messages.success(request, "Staff Added Successfully!")
            return redirect('add_staff')
        except:
            messages.error(request, "Failed to Add Staff!")
            return redirect('add_staff')



def manage_staff(request):
    staffs = Staffs.objects.all()
    context = {
        "staffs": staffs
    }
    return render(request, "admintemplate/manage_staff_template.html", context)

模板

add staff template

{% extends 'admintemplate/base_template.html' %}

{% block page_title %}
    Add Staff
{% endblock page_title %}

{% block main_content %}

{% load static %}

<section class="content">
        <div class="container-fluid">

            <div class="row">
                <div class="col-md-12">
                    <!-- general form elements -->
                    <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Add Staff</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form role="form" method="POST" action="{% url 'add_staff_save' %}">
                        {% csrf_token %}

                        
                                {% comment %} Display Messages {% endcomment %}
                                {% if messages %}
                                <div class="form-group">
                                <div class="col-12">
                                    {% for message in messages %}
                                    {% if message.tags == "error" %}
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">
                                        {{ message }}
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        </div>
                                    {% elif message.tags == "success" %}
                                        <div class="alert alert-success alert-dismissible fade show" role="alert" style="margin-top: 10px;">
                                        {{ message }}
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        </div>
                                    {% endif %}
                                    {% endfor %}
                                </div>
                                </div>
                                {% endif %}
                            

                        <div class="card-body">
                            <div class="form-group">
                                <label>Email address</label>
                                <input type="email" class="form-control" name="email" placeholder="Enter email" id="id_email">
                            </div>

                            <div class="form-group">
                                <label>Username</label>
                                <input type="text" class="form-control" name="username" placeholder="Username" id="id_username">
                            </div>

                            <div class="form-group">
                                <label>Password</label>
                                <input type="password" class="form-control" name="password" placeholder="Password">
                            </div>

                            <div class="form-group">
                                <label>First Name</label>
                                <input type="text" class="form-control" name="first_name" placeholder="First Name">
                            </div>

                            <div class="form-group">
                                <label>Last Name</label>
                                <input type="text" class="form-control" name="last_name" placeholder="Last Name">
                            </div>

                            <div class="form-group">
                                <label>Phone</label>
                                <textarea class="form-control" name="phone" placeholder="phone"></textarea>
                            </div>

                            


                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                        <button type="submit" class="btn btn-primary">Add Staff</button>
                        </div>
                    </form>
                    </div>
                    <!-- /.card -->

                </div>
            </div>

        </div><!-- /.container-fluid -->
      </section>

  {% endblock main_content %}

管理人员模板 - 数据应该显示的模板

{% extends 'admintemplate/base_template.html' %}

{% block page_title %}
    Manage Staff
{% endblock page_title %}

{% block main_content %}

{% load static %}

<section class="content">
        <div class="container-fluid">

            <a class="btn btn-primary" href="{% url 'add_staff' %}" role="button">+ Add Staff</a> <br/>&nbsp;

            {% if messages %}
                                <div class="form-group">
                                <div class="col-12">
                                    {% for message in messages %}
                                    {% if message.tags == "error" %}
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">
                                        {{ message }}
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        </div>
                                    {% elif message.tags == "success" %}
                                        <div class="alert alert-success alert-dismissible fade show" role="alert" style="margin-top: 10px;">
                                        {{ message }}
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        </div>
                                    {% endif %}
                                    {% endfor %}
                                </div>
                                </div>
            {% endif %}
                                

            <div class="row">

                <div class="col-md-12">
                    <!-- general form elements -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Staff Details</h3>

                            <div class="card-tools">
                            <div class="input-group input-group-sm" style="width: 150px;">
                                <input type="text" name="table_search" class="form-control float-right" placeholder="Search">

                                <div class="input-group-append">
                                <button type="submit" class="btn btn-default"><i class="fas fa-search"></i></button>
                                </div>
                            </div>
                            </div>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body table-responsive p-0">
                            <table class="table table-hover text-nowrap">
                            <thead>
                                <tr>
                                <th>ID</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Last Login</th>
                                <th>Date Joined</th>
                                <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for staff in staffs %}
                                <tr>
                                <td>{{ staff.admin.id }}</td>
                                <td>{{ staff.admin.first_name }}</td>
                                <td>{{ staff.admin.last_name }}</td>
                                <td>{{ staff.admin.username }}</td>
                                <td>{{ staff.admin.email }}</td>
                                <td>{{ staff.phone }}</td>
                                <td>{{ staff.admin.last_login }}</td>
                                <td>{{ staff.admin.date_joined }}</td>
                                <td>
                                    <a href="{% url 'edit_staff' staff.admin.id %}" class="btn btn-success">Edit</a> 
                                    <a href="{% url 'delete_staff' staff.admin.id %}" class="btn btn-danger">Delete</a>
                                </td>
                                </tr>
                                {% endfor %}
                                
                            </tbody>
                            </table>
                        </div>
                        <!-- /.card-body -->
                        </div>
                    <!-- /.card -->

                </div>
            </div>

        </div><!-- /.container-fluid -->
      </section>

  {% endblock main_content %}

任何建议都会对我的项目工作有所帮助。谢谢!

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


add_staff_save视图中,您没有创建没有更新任何员工:

# This creates a user
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2)

# This sets the related staffs' phone but does not save it
user.staffs.phone = phone

# This saves only the user, not the related FK. So the staffs is not updated, you'd need user.staffs.save() to update the staffs instance
user.save()

您明确需要:

  • 创建您的用户
  • 然后创建一个链接到您的用户的员工
user = CustomUser.objects.create_user(username=username, password=password, email = email, first_name=first_name, last_name=last_name, user_type=2)
# Assuming staffs does not exist yet:
staffs = Staffs.objects.create(admin =user, phone=phone)
# If it already exists, then just
user.staffs.phone = phone
user.staffs.save()

推荐阅读