English 中文(简体)
如何在Django数据表中显示使用APIC的数据
原标题:How to show data using API in Django data table

我建立了模式。 py Internal Profile_management app.

import requests
from django.db import models
from datetime import date
from package_management.models import Package
from api_url_config import CREATE_CONNECTION_API_URL

class ClientProfile(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    profile_name = models.CharField(max_length=50, default="default_profile")
    active_status = models.BooleanField(choices=[(True,  Yes ), (False,  No )], default=True)
    subscribed_package = models.ForeignKey(Package, related_name= client_profiles_subscribe , on_delete=models.PROTECT,
                                           default=1)
    plugin_platform = models.CharField(max_length=15, blank=True, null=True)
    expire_date = models.DateField(default=date.today)
    company_email = models.EmailField(unique=True, null=True)
    company_phone = models.CharField(max_length=15, blank=True, null=True)
    website = models.CharField(max_length=50, null=True)
    company_address = models.TextField(max_length=255, blank=True, null=True)
    main_client = models.BooleanField(choices=[(True,  Yes ), (False,  No )], default=True)


    def profile_auto_increment_id(self):
        if self.pk:
            return f"#{self.pk}"
        else:
            return "(Not saved)"

    profile_auto_increment_id.short_description =  ID 

    def __str__(self):
        return self.profile_name

    def save(self, *args, **kwargs):
        self.send_data_to_api()


    def send_data_to_api(self):
        api_url = CREATE_CONNECTION_API_URL
        data = {
            "profile_name": self.profile_name,
            "active_status": self.active_status,
            "subscribed_package": self.subscribed_package.id,
            "plugin_platform": self.plugin_platform,
            "expire_date": str(self.expire_date),
            "company_email": self.company_email,
            "company_phone": self.company_phone,
            "website": self.website,
            "company_address": self.company_address,
            "main_client": self.main_client,
        }

        try:
            response = requests.post(api_url, json=data)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"Error sending data to API: {e}")

在此,我没有在数据库中保存数据,就将数据发送至APIC。 此前,我把数据储存在我的当地数据库中,因此,我可以把这些数据显示在行政上:

from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from profile_management.models import ClientProfile


@admin.register(ClientProfile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = (
     profile_auto_increment_id ,  profile_name ,  profile_status ,  action_column )
    search_fields = ( profile_name ,)
    list_filter = ( profile_status , )

    def profile_auto_increment_id(self, obj):
        if obj.pk:
            return f"#{obj.pk}"
        else:
            return "(Not saved)"

    profile_auto_increment_id.short_description =  ID 

    def profile_auto_increment_id_link(self, obj):
        if obj.pk:
            return f"#{obj.pk}"
        else:
            return "(Not saved)"

    profile_auto_increment_id_link.admin_order_field =  id 
    profile_auto_increment_id_link.short_description =  ID 

    def action_column(self, obj):
        # This method is for the action column
        edit_url = reverse( admin:profile_management_clientprofile_change , args=[obj.pk])
        return format_html(
             <a href="{}" class="button">Edit</a> , edit_url
        )

    action_column.short_description =  Actions 

现在我如何能够从APIC获得数据并显示行政数据表? 例见APIC/L.2/Add.1。

问题回答

我也这样做。

观点。

def profile_view(request):
    api_url = GET_ALL_CONNECTION_API_URL
    try:
        curl_command = (
            f curl -X GET {api_url}  
            f -H "Content-Type: application/json" 
        )

        process = subprocess.Popen(curl_command, stdout=subprocess.PIPE, shell=True)
        output, _ = process.communicate()

        api_data = json.loads(output.decode( utf-8 ))

    except Exception as e:
        print(f"Failed to fetch data from API: {e}")
        return None

    if  data  in api_data:
        # Extract the data array from the response
        api_data_array = api_data[ data ]

        breadcrumbs = [{ url :  / ,  name :  Home },
                       { url :  /profile_management/profile ,  name :  Customer_Account_Management }
                       ]

        # Pass the array to your Django template
        context = {
             api_data_array : api_data_array,
             available_apps : admin.site.get_app_list(request),
             breadcrumbs : breadcrumbs
        }

    return render(request,  admin/客户_账户清单。 , context)

客户_账户清单。

{% for item in api_data_array %}
     <tr>
        <td>{{ item.project_env.profile_name }}</td>
        <td>{{ item.project_env.subscribed_package }}</td>
        <td>{{ item.project_env.company_email }}</td>
        <td>{{ item.project_env.main_client }}</td>
        <td>
           <p class="status-text">{{ item.project_env.active_status }}</p>
        </td>
     </tr>
{% endfor %}




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签