Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Admin List filters for custom list_display functions?
Is it possible to create list_filters on the admin model page based on a function created to pull info on models that are a couple of Foreign Keys away? I've created the functions to display the info needed in 'list_display', but am hoping to also be able to filter using these fields. The current admin.ModelAdmin functions are seen here: class HardwareAdmin(admin.ModelAdmin): list_display = ('hardware_id', 'device_type', 'get_customer', 'network_health','get_region') def get_customer(self, obj): if obj.site: return obj.site.customer return '-' get_customer.short_description = 'Customer' get_customer.admin_order_field = 'site__customer' def get_region(self, obj): if obj.pad: return obj.pad.lease.region return '-' get_region.short_description = 'Region' How would I go about adding filters that allow me to filter by both region and customer? -
Django csrf token cookie and Cookie Policy
Is there a way not to store csrf_token cookies until users accept the Cookie Policy? -
Link multiple different forms with id
I am having one form which creates objects to Patient model with unique id and I want to create new object using Patient's object linked with id and add new data Patient's objects and create new object with new id , but I am not able to display the Patient's object data in another form template (IpdForm). One thing I want to make clear I don't want to update the patient object. I want to create new object linked with the patient id, and I want to show patient objects in new IpdForm i have already used following QuerySets: "qs = Ipd.objects.get(patient__id=patient_id)" , "qs = Ipd.objects.filter(patient__id=patient_id)" "qs = Ipd.objects.filter(patient_patient=patient_id)" models.py : ```python class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name ``` forms.py : ```python class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient', 'reason_admission', 'presenting_complaints', 'rooms', 'date_of_admission'] ``` views.py: ```python @login_required def new(request): … -
Two identical PNGs, one is corrupt
I have this PNG file, uploaded to a django REST server from an Angular front-end. About 99.9% of uploaded images work fine; you can view them in admin and download them. But every once in a while, I get these corrupt PNG images. You can see the image if you put the image URL in the address bar but you can't see it on django admin and you can't download it through right click>save. I uploaded and downloaded the image to Imgur and now it seems to be working. When I put it in the media directory of the Django development server, I can download it with the right click at the image URL. But it seems to be identical to the original file! I get nothing with a diff File sizes are the same Neither of the files seem to be open (checked with lsof) I'm out of options. I uploaded both versions of the images to my google drive and checked that if you download the images, corrupt one still seems to be corrupt. Maybe somebody can figure out what the difference between these files is. corrupt image saved and fixed image -
How to order a queryset result by the number of entries in a manytomanyfield?
Let's say that i have this queryset : result_list = [] get_result_list = [x for x in search_text_imported.split() if len(x) > 2] for keyword in get_result_list: result_list += list(Node.objects.filter((Q(name__icontains=keyword) | Q(Tags__icontains=keyword)), tree_type='root', tunisia_office=True, published=True ).order_by('-bookmarked_by')) result = list(dict.fromkeys(result_list)) models.py class Node(MPTTModel): name = models.TextField(blank=True, null=True) bookmarked_by = models.ManyToManyField(CustomUser, null=True, blank=True) I want to show first the objects that have the most number of entries in the bookmarked_by field. Is there a way to do it ? Any help is appreciated. -
How to update website and its data automatically
Basically i have a front end on Django server and back end on pycharm python. I made a website that scrape some data and stored in CSV files then i push this repository into git and then push it into heroku cloud server for hosting by the problem is the website update when i update it manually by running those python scripts and then update git repository and push it into hasting servers. I want to linked them that my python scripts run after every hour and it automatically push to my hosting server. please help me! PS: i am working on windows -
Django , Use Viewsets inside views.py
I'm Using a ViewSet to implement restful API . for a similar Operation in views.py i wanna use those API methods . how can i use api calls inside my views.py ? here is ViewSet class with one GET method : class ProductViewSet(ViewSet): @action(methods=['get'], detail=False) def get_price_with_code(self, request): some operations ... here is views.py and i wanna use get_price_with_code in index method : @csrf_exempt def index(request): if request.method == "GET": return render(request, "showProduct.html", {}) else: code = request.POST['pr_code'] phone = request.POST['phone'] # use get_price_with_code method to get results -
Django 2 annotate to prepare data for chart from Models
I'm working on a project using Python(3) and Django(2) in which I need to prepare data to display a chart. I have 2 models as: (1): UserGroup (2): VotingValuesHistory I need to aggregate all the votes in user's group. From models.py: class UserGroup(models.Model): email = models.EmailField(primary_key=True) group = models.CharField(max_length=250, default='notingroup') def __str__(self): return self.group VOTE_CHOICES = ( ('1', "helpful"), ('2', 'meh'), ('3', 'disaster') ) class VotingValuesHistory(models.Model): id = models.AutoField(primary_key=True, auto_created=True) value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) Here's what I have tried: From views.py: deli_val = [] e_t_r = [] fun = [] h_o_c = [] tw = [] for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('value1').annotate(Sum('score' + str(i))) deli_val.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value2').annotate(Sum('score' + str(i))) e_t_r.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value3').annotate(Sum('score' + str(i))) fun.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value4').annotate(Sum('score' + str(i))) h_o_c.append(int(vv[0]['score' + str(i) + '__sum'])) … -
How to hide tracebacks for users when an import csv fail using django import export library
I have implemented successfully import and export in my app. The only thing that I can't make to work is to hide the tracebacks for users when an import fails. I have tried so far: raise_errors = False in admin.py .traceback{display:none} in import.css DEBUG = False in settings.py I put wrong data starting with the column name on purpose in the csv file and I always get this per row: § Line number: 1 - "Column 'my_error' not found in dataset. Available columns are: ['column1', 'column2', 'my_err', 'column3']" row1data1, row1data2, row1data3, 0 Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 63, in clean value = data[self.column_name] KeyError: 'my_error' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\instance_loaders.py", line 32, in get_instance params[field.attribute] = field.clean(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 66, in clean "columns are: %s" % (self.column_name, list(data))) KeyError: "Column 'my_erro' not found in dataset. Available columns are: ['column1', 'column2', 'my_error', 'column4']" How can I get only the fisrt lines of the message?: § Line number: … -
Django - endblock. Did you forget to register or load this tag
I am having and error in endblock tag in Django and I can't seem to find any errors in my code. Here are the 2 .html files. The {% endblock %} is written right but Django throws me an error TemplateSyntaxError at / Invalid block tag on line 57: 'endblock'. Did you forget to register or load this tag? Do I miss something or did I input something wrong? I tried to search some solutions but most of them are syntax errors with the { and % have space in between. login.html {% extends 'base.html' %} {% load static %} <body> <-- some HTML codes here --> </body> {% endblock %} base.html <-- HTML tags --> <-- CSS links --> {% block content %} {% endblock %} <-- JavaScript links --> -
Not saving data of some fields
Hello I am trying to save a new registered user to database. Besides native User Model I have a Profile model with additional fields and here is my problem, after registrations fields named 'gender' and 'birthday' are not saved to database, but the user and profile is created with according fields. models.py class Profile(models.Model): GENDER_CHOICES = [ ('male', 'Male'), ('female', 'Female'), ('other', 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) image_prof = models.ImageField( default='default.jpg', upload_to='profile_pics') gender = models.CharField( max_length=100, choices=GENDER_CHOICES, default='male',) birthday = models.DateField(name='birthday', null=True) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileGenderBirthdayForm(forms.ModelForm): YEARS = [x for x in range(1940, 2021)] birthday = forms.DateField( widget=forms.SelectDateWidget(years=YEARS), required=True) class Meta: model = Profile fields = ['gender', 'birthday'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileGenderBirthdayForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) bg_form = ProfileGenderBirthdayForm(request.POST) if form.is_valid(): user = … -
Cannot load media static file photo anymore after pushing to heroku a number of times
At the beggining it was fine to login but now after a number of times logging in and pushing changes to heroku, the static files stopped working. The error itself is "FileNotFoundError at /accounts/login/ [Errno 2] No such file or directory: '/app/media/profile_pics/obama.jpg'" Initially i thought it was the "" provided by the Login html django auth. This should redirect me to the index page. .settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Deployment configs # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ PROJECT_ROOT = os.path.join(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra lookup directories for collectstatic to find static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '/static'), ) # Add configuration for static files storage using whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # update the db import dj_database_url prod_db = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(prod_db) I expected after logging in to be redirected to the index page but I get Filenotfound error even though theres no call function for any filetype. My instinct is that heroku doesnt keep static files so how can i make sure it keeps. -
How do I properly provide user field to ModelSerializer in Django Rest Framwork
I have a django Profile model as: class Profile(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) meta = models.TextField(blank=True) def __str__(self): return self.created_by And a serializer (which I know is not currently doing much) class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' In my update method in view, I can't ever seem to validate the serializers. This is how I am going about it: profile = Profile() profile.created_by = request.user serializer = ProfileSerializer(profile) serializer.is_valid() always returns False. And by the way, request.user is an authenticated CustomUser. I have also tried setting serializer = ProfileSerializer( instance=profile, data={'created_by':request.user} ) And many combinations thereof. What am I missing that the serializer can't be validated? Clearly there's some trouble with the user here. Extra: I am new to DRF, why is the 'created_by' field set by default when DRF seems to know who the user is? -
Unable to Get a proper result from Dict in Django Template
I am unable to print the value from Dict in Django Template. {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.0.steam_name }} - d</h2> </div> {% endfor %} or {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.steam_name }} - d</h2> </div> {% endfor %} {0: {'steam_name': 'ABC', 'steam_data': }, 1: {'steam_name': 'DEF', 'steam_data': }} I have properly passed the steam_d to the template but still unable to print the 'steam_name'. Loop is also working. -
How to make a filter that filters if a certain object has already been confirmed or not? Using reverse relationship
Im have two models: Notice and ReadConfirmation, i want to filter notices by read confirmation against the logged in user. class ReadConfirmation(TimestampedModel): notice = models.ForeignKey(Notice, models.CASCADE, db_column='aviso_id', related_name='read_confirmations') user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) api return all notices, and i want return notices news that the user has already read, that is, they are saved in the ReadConfirmation table -
Generate separate translation files with django-admin
How I can generate separate *.po files for my Django project? This files used only for automatic database table fill. Table look's like: id | SKU | en | cz | ... I need only SKU and lang column to generate filter dropdown for the user. Command django-admin makemessages -a includes them to the one main file. There are large dataset with 2000+ entries in summary. So I want to split them into the parts. Especially, because most of them used only during table fill. I have tried pygettext.py command, but it doesnt generate *.po files for all website locales. And this command removes already translated content. -
Problem with importing some .models from the 2 folders in one bigger one
I moved my django project from Atom to PyCharm and there is a problem, when i wrote, ''' from .models import BookItem ''' I've got error I tried do fix that with double dot, with adding full path, but it still does not work, have anyone know what can i do ? i tried ''' from shelf.models import BookItem from ..models import BookItem ''' even ''' from wypozycz.shelf.models import BookItem ''' The error that i receive is: "ImportError: cannot import name 'BookItem' from 'rental.models'" -
Simple solutions to create an interface with a python script?
I coded a simple Python script to automate some accounting work at my internship and it has worked wonderfully. However, now that I am leaving I am a bit worried about the other accountants being able to use the same script from the command line or JupyterLab. It would be amazing if I could create a simple interface for them so they don't have to learn anything new (: the script is really simple: it imports an excel file from the user's computer, transforms into a data frame, replaces a few strings, does some calculations, deletes some columns, and outputs an excel file with the new formatting. The script can be viewed at my github here: https://github.com/brunnatorino/FEC/blob/master/ALL_app.py I even tried adding some user input functions so they wouldn't have to mess with the code, but that has also proven challenging for them to learn and remember. Is there any simple interface solutions where I can use my existing script? I would prefer to have the least amount of modifications to the code as I don't have a lot of time left in my internship. -
How to Dynamically Remove Form from Formset
I have a Django formset where a user can dynamically add forms through a jQuery script. How can I use jQuery to dynamically remove the last form in the formset when the user clicks the #remove_form button? template.html <div id="form_set"> {{ presales_formset.management_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} {% endfor %} </div> <div id="empty_form" style="display: none;"> {{ presales_formset.empty_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="emptyPresalesForm" method="post" name="presalesForm"> {% csrf_token %} <div class="field is-inline-flex"> <div class="control"> <button class="button is-success" id="add_more" name="add_more" type="button">+</button> </div> </div> <div class="field is-inline-flex"> <div class="control"> <button class="button is-danger" id="remove_form" type="button">-</button> </div> </div> <script> $(document).ready(function () { $('body').on('click', '#add_more', function () { var form_idx = $('#presalesForm-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#presalesForm-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); }); </script> -
Unable to create a project with django-admin, the process is using a wrong path because I installed a wrong Python beforehand
When typing "django-admin startproject DEMOPROJECT" in command prompt, I'm getting the following feedback: "Fatal error in launcher: Unable to create process using '"c:\program files (x86)\python37-32\python.exe" "C:\Program Files\Python37\Scripts\django-admin.exe" startproject DEMOPROJECT'" The "c:\program files (x86)\python37-32\python.exe" is a wrong path and I'm not sure why django-admin is looking at this path. I have changed the path to my new path in the environmental variables. -
could not create unique index "credits_credit_pkey"
Initially, I had a model of Credit. But after adding models of Hypothec and AutoCredit with similar functionality, I realized that I needed to make a base model and inherit from it. When I tried makemigrations, I received a question: You are trying to add a non-nullable field 'abstractbaseproduct_ptr' to `credit` without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py I entered 1; 1 It is not clear what the 'abstractbaseproduct_ptr' field is? Then i got You are trying to add a non-nullable field abstractbaseaction_ptr to creditaction without a default; we can't do that (the database needs something to populate existing rows). Again introduced 1; 1. When I try to migrate, I get django.db.utils.IntegrityError: could not create unique index "credits_credit_pkey" DETAIL: Key (abstractbaseproduct_ptr_id) = (1) is duplicated. Such questions arose only with the Credit model. Apparently, because there is already data in this table... How to be, tell me? class AbstractBaseProduct(models.Model): bank = models.ForeignKey('banks.Bank', verbose_name=_('bank')) #other fields class AbstractBaseAction(models.Model): name = models.CharField(_('name'), max_length=255) short_description = models.CharField(_('short description'), … -
When I enter the admin panel I get an error DoesNotExist at /admin/login/ Site matching query does not exist
When I enter the admin panel I get an error. I go through localhost:8000/admin If you want, I will throw off the code of how I did the registration and settinngs I logged into the admin panel recently, and after that I worked with registrations and after that I could not log in, but I deleted everything I did and returned everything to its original form when I still entered but still had an error Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sites\models.py" in _get_site_by_request 39. SITE_CACHE[host] = self.get(domain__iexact=host) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in get 408. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py" in login 399. return LoginView.as_view(**defaults)(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, … -
How to mock test python requests
I want to know how to write mock python request tests. def request_headers(): payload = { 'client_id': settings.STAT_SERVER['CLIENT_ID'], 'client_secret': settings.STAT_SERVER['CLIENT_SECRET'], 'username': settings.STAT_SERVER['USERNAME'], 'password': settings.STAT_SERVER['PASSWORD'], 'grant_type': 'password', } How can I mock test all of this? token_url = settings.STAT_SERVER['URL'] + 'o/token/' r = requests.request( method="POST", url=token_url, data=payload, verify=False) if r.status_code != 200: msg = "Failed to authenticate. Error code {}: {}" msg = msg.format(r.status_code, r.text) LOGGER.error(msg) credentials = r.json() Here's the base_headers base_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, */*' } base_headers['Authorization'] = "{} {}".format( credentials['token_type'], credentials['access_token'] ) LOGGER.debug('Get token: credentials={}'.format(credentials)) return base_headers -
Documenting Django rest framework with rest_framework.documentation
I am documenting rest api using rest_framework.documentation not swagger, But I did not find any proper docs on how to use it. Can anyone tell me how it works, How it picks the apis and create document? beacause for my application, it is picking every url and there is not heading to seperate those apis. Also, how can I edit the the generated document for apis. -
How to Paginate within an action in Django Rest Framework
Good afternoon community, I have a question about the django rest framework page, in this case I manage to do it in the viewset, but in a class action I have not been able to achieve it. class PostPageNumberPagination(PageNumberPagination): page_size=10 class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination # La siguiente funcion es un decorador(funciones extra) de la clase RegistrosViewSet para poder manipular los datos que voy a presentar de acuerdo a la URL que se le asigne con el url_path # El siguiente action actua para poder presentar todos los datos de todos los objetos @action(methods=['get'],detail=False,url_path='registros-data-table',url_name='registros_data_table') def registros_data_table(self, request): paginator=PostPageNumberPagination return Response( { 'id_interface':interface.id_interface, 'id_EquipoOrigen':interface.id_EquipoOrigen_id, 'EquipoOrigen':interface.id_EquipoOrigen.nombre, 'LocalidadOrigen':interface.id_EquipoOrigen.localidad, 'CategoriaOrigen':interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen':interface.id_PuertoOrigen_id, 'PuertoOrigen':interface.id_PuertoOrigen.nombre, 'estatus':interface.estatus, 'etiqueta_prtg':interface.etiqueta_prtg, 'grupo':interface.grupo, 'if_index':interface.if_index, 'bw':interface.bw, 'bw_al':interface.bw_al, 'id_prtg':interface.id_prtg, 'ospf':interface.ospf, 'description':interface.description, 'id_EquipoDestino':interface.id_EquipoDestino_id, 'EquipoDestino':interface.id_EquipoDestino.nombre, 'LocalidadDestino':interface.id_EquipoDestino.localidad, 'CategoriaDestino':interface.id_EquipoDestino.categoria, 'id_PuertoDestino':interface.id_PuertoDestino_id, 'PuertoDestino':interface.id_PuertoDestino.nombre, 'ultima_actualizacion':interface.ultima_actualizacion, } for interface in Interfaces.objects.all() )