Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change django admin label position
I need to change how the default admin form is rendered. It shows the label on the left like the image below. But I want it to be displayed on top of the input field, any idea? Here is my admin.py class ApplicationAdmin(admin.ModelAdmin): form = ApplicationAdminForm list_display = ['last_name', 'income'] fieldsets=( ("",{"fields": ( ('last_name',), ('income',), ), } ), ) -
Django-taggit migration fails at AlterUniqueTogether
I'm trying to migrate my Django application which uses jazzband django-taggit The error I get is: django.db.utils.IntegrityError: could not create unique index "taggit_taggeditem_content_type_id_object_i_4bb97a8e_uniq" DETAIL: Key (content_type_id, object_id, tag_id)=(41, 596, 242) is duplicated. The migration in question reads: migrations.AlterUniqueTogether( name="taggeditem", unique_together={("content_type", "object_id", "tag")} ) https://github.com/jazzband/django-taggit/blob/master/taggit/migrations/0003_taggeditem_add_unique_index.py#L12-L14 Which translates to the following SQL: ALTER TABLE "taggit_taggeditem" ADD CONSTRAINT "taggit_taggeditem_content_type_id_object_i_4bb97a8e_uniq" UNIQUE ("content_type_id", "object_id", "tag_id"); COMMIT; Checking the table in question I do get: # SELECT * FROM public.taggit_taggeditem WHERE tag_id=242 ORDER BY object_id; id | tag_id | object_id | content_type_id ------+--------+-----------+----------------- 691 | 242 | 356 | 41 2904 | 242 | 356 | 41 680 | 242 | 486 | 41 2893 | 242 | 486 | 41 683 | 242 | 596 | 41 2896 | 242 | 596 | 41 What is the suggested way to resolve the django.db.utils.IntegrityError error and successfully finish the migration? I think the same will happen with object_id 486 and 356 (+ several more). -
Django create a new record for each user every month
The title is self explanatory. I would like to create a new record for a user at the start of each month. What is the best way to achieve this in Django? My initial thoughts were to run a function that will check the date time every x amount of intervals and then if year and month of last record != then create a new record. Is this even possible? It seems that this constant checking of time would be inefficient but I am struggling to think of another solution. Am I headed in the right direction? -
C++ / Django Login
I have Django web application for login and register, and I need to write C++ program to login to existing account made in django register, how can I achieve this? -
how to add python in cpanel in ubantu server?
I have a VPS server with centos and I have Cpanel. How to after installing python from WHM it is not showing in Cpanel. I am not able to create a project in the Django. Please help -
How to save local data to a database in django?
I have a web scraper which is returning JSON data. I want to save that data to a database. I have gone through a lot of resources but none really explains how to perform a POST request on a local data or pass local data to a POST request. -
django admin : how can i use smart_selects in multi inline
how can i use smart_selects in multi inline i need in the admin django to select (Select Country) and show the cities of this country in inline i use : smart_selects : django_smart_selects_711-1.0.0.dist-info fieldsets_with_inlines : django_fieldsets_with_inlines-0.5 see what i need class Country(models.Model): status_choice = ( (1, 'Supprimé'), (2, 'Désactivé'), (3, 'Activé'), ) nom = models.CharField(max_length=100, blank=False,verbose_name="Nom") continents = models.ForeignKey(Continents, on_delete=models.CASCADE,verbose_name="Continents") region = models.ManyToManyField(RegionsMonde,verbose_name="Région") superficie = models.CharField(max_length=100, blank=True,verbose_name="Superficie") population = models.CharField(max_length=100, blank=True,verbose_name="Population") capitale = models.CharField(max_length=100, blank=True,verbose_name="Capitale") devise = models.CharField(max_length=100, blank=True,verbose_name="Devise") LangueOfficielle = models.CharField(max_length=100, blank=True,verbose_name="Langue(s) officielle(s)") formeEtat = models.CharField(max_length=100, blank=True,verbose_name="Langue(s) officielle(s)") chefEtat = models.CharField(max_length=100, blank=True,verbose_name="Chef de l'Etat") feteNationale = models.CharField(max_length=100, blank=True,verbose_name="Fête nationale") monnaie = models.CharField(max_length=100, blank=True,verbose_name="Monnaie") cgPm = models.CharField(max_length=100, blank=True,verbose_name="Chef du Gouvernement/Premier Ministre") ministreTutelle = models.CharField(max_length=100, blank=True,verbose_name="Ministre(s) de tutelle") lienMinistre = models.CharField(max_length=100, blank=True,verbose_name="Lien du Ministère") nbrUniversits = models.CharField(max_length=100, blank=True,verbose_name="Nbr d'Universités") status = models.IntegerField(choices=status_choice,default=3) def __str__(self): # __unicode__ for Python 2 return self.nom class Meta: ordering = ('nom',) verbose_name = 'Pays' verbose_name_plural = 'Pays' def regionName(self): return ', '.join([r.nom for r in self.region.all()]) regionName.short_description = "Regions" class City(models.Model): nom = models.CharField(max_length=100, blank=False) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.nom class Meta: unique_together = ('country', 'nom') verbose_name = 'City' verbose_name_plural = 'Cities' -
dj_database_url() loads empty dictionary for DATABASES when running locally
I have been following this tutorial: https://blog.usejournal.com/deploying-django-to-heroku-connecting-heroku-postgres-fcc960d290d1 It explains how to use the default SQLite3 database when running locally on your computer and postgreSQL when on Heroku. It has with the following steps: make an .env file with: 'DATABASE_URL=sqlite:///db.sqlite3' Then in settings.py add: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) and DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) But now I can't connect to my SQLite database when running locally and when I print DATABASES it's empty. I use anaconda and have installed the packages with conda install Any idea what causes this? -
Annotate each query with a function of itself
I need to annotate each query in queryset using a model method: class myModel(models.Model): ... def myModel_foo(self): .... return myModel_foo I need something like .annotate(myModel_foo=myModel.myModel_foo()). The problem is myModel_foo() requires self. I tried iterating over queryset and using query.annotate(myModel_foo=myModel.myModel_foo(self)), but i got object has no attribute 'annotate' error. What's the correct approach? -
How to serve a djangoAPI and Angular frontend in Apache
I am trying to serve a DjangoAPI with an Angular frontend. It already works on localhost using apache2, however it doesn't work on the web. The API is directed to 127.0.0.1:8000. further more the back end has an /auth, /projects and /admin url I would like to use. My current Apache set up is: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /home/user/Websites/Webapp/WebappFrontEnd ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/user/Websites/Webapp/WebappFrontEnd> Require all granted </Directory> </VirtualHost> <VirtualHost *:8000> ServerAdmin webmaster@localhost DocumentRoot /home/user/Websites/Webapp/WebappAPI SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/user/Websites/Webapp/WebappAPI/Webapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/Websites/Webapp/WebappAPI/Webapp/wsgi.py WSGIDaemonProcess Webapp python-path=/home/user/Websites/Webapp/WebappAPI python-home=/home/user/Websites/Webapp/WebappAPI/venv WSGIProcessGroup Webapp </VirtualHost> I already tried adding the following and adjusting ports accordingly: <VirtualHost *:80> ProxyPreserveHost On ProxyRequests Off ProxyPass /api/ http://localhost:8000/api/ ProxyPassReverse /api/ http://localhost:8000/api/ ProxyPass /auth/ http://localhost:8000/auth/ ProxyPassReverse /auth/ http://localhost:8000/auth/ ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ </VirtualHost> which let to Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at [no address given] to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server … -
Passing the data from a sign up form through a python script to create a new field in the user database in Django
I would like to add a specific code to each user as as they sign up for example my current form is in html - **<form class="form-signin" method="post">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Get your SiD</h1> <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus> <input type="text" name="firstname" id="inputFirstname" class="form-control" placeholder="First Name" required> <input type="text" name="middlename" id="inputMiddlename" class="form-control" placeholder="Middle Name" required> <input type="text" name="lastname" id="inputLastname" class="form-control" placeholder="Middle Name" required> <input type="text" name="idnumber" id="inputIdnumber" class="form-control" placeholder="ID number" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Verify & Get SiD</button> </form>** At the moment all of the fields save fine in my user database. However once doing the form I would like to automatically add another field to the user "customercode" which would be created through using the following python script - **import random import string def randomStringDigits(stringLength=6): """Generate a random string of letters and digits """ lettersAndDigits = string.ascii_letters + string.digits return ''.join(random.choice(lettersAndDigits) for i in range(stringLength)) email = input(); firstName = input(); firstInitial = firstName[0]; middleName = input() or "0"; middleInitial = middleName[0]; lastName = input(); lastInitial = lastName[0]; idnumber = input(); import datetime # Current time now = datetime.datetime.now() month = now.strftime("%m") day = now.strftime("%d") hour = now.strftime("%H") minute = now.strftime("%M") … -
Django: Does the virtual environment have to be on every time i develop my django app
i have installed and set up the virtual environment using the command line. i am using pycharm to develop my django application. so that was day 1. On day 2 when i put my laptop back on to go back to working on my django application do i need to go back to command line and type in workon 'virtualenvironment-name' or can i just develop the django app without switching on the virtual environment. -
Use Django Money field as default value in Django Case
I am trying to set a default value In Django Case but it complains django.db.utils.ProgrammingError: can't adapt type 'Money' Here is my code from djmoney.models.fields import MoneyField def method(self): clauses = [ When( value_currency=u.value_currency, then=Value(u.value) ) for u in Price.objects.all() ] return Case( *clauses, default=Value(Money('0.0', settings.DEFAULT_CURRENCY)), output_field=MoneyField() ) In [1]: type(Price.objects.first().value) Out[1]: djmoney.money.Money I have used that method in query set like this qs = qs.annotate( _price=self.method() ) I can use DecimalField() Like this and it works. def method(self): clauses = [ When( value_currency=u.value_currency, then=Value(u.value.amount) ) for u in Price.objects.all() ] return Case( *clauses, default=Value(0.0), output_field=models.DecimalField() ) But I want qs._price to be Money type. Can we use Money field value in Django Case? -
How can I use Javascript to implement a username taken function in my registration form?
So I'm loading my registration form into my html and then using a for loop to iterate over those fields. I am wondering where I can add form control to show a green box around my username field so that a user knows if a username is taken before hitting the submit button. I tried adding it to the form tag and setting a div tag around {{field}} but neither of those work. Furthermore, how can I make it ONLY for Username? I understand I need to use JavaScript for this, but I'm still new to coding and I haven't touched Javascript at all, so no idea how and where to place JS code in my code reg.html {% block content %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > {% bootstrap_form registration_form%} {% csrf_token %} {% for field in bootstrap_form %} <p> <div class="form-control is-valid"> {{field.label_tag}} {{field}} </div> {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> … -
How to add a link to a template form to extend the form to the corresponding id?
Currently I have a form consisting of updating an objects, based on the models below. class Product(models.Model): CATEGORY = ( ('Sports', 'Sports'), ('Fashion', 'Fashion'), ('Toys', 'Toys'), ('Electronics', 'Electronics'), ('Kitchen', 'Kitchen'), ('Jewellery', 'Jewellery'), ) product_sku = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) r_price = models.FloatField(null=True) d_price = models.FloatField(null=True, blank=True,default='') start_date = models.DateTimeField(null=True, blank=True,default='') end_date = models.DateField(null=True, blank=True,default='') tags = models.ManyToManyField(Tag) stock = models.CharField(max_length=200, null=True) min_stock = models.CharField(max_length=200, null=True) def __str__(self): return self.name def get_image_filename(instance,filename): id = instance.product.id return "picture_image/%s" % (id) def path_and_rename(instance, filename): upload_to = 'images' ext = filename.split('.'[-1]) if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(upload_to, filename) class Picture(models.Model): product_pic = models.ImageField(null=True, blank=True,upload_to=path_and_rename) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL ) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.product.name I have a form of updating the Product model, see below for its view, form and template views.py @login_required(login_url='login') def EditProduct(request,pk): product_list = Product.objects.all().order_by('product_sku') product = Product.objects.get(product_sku=pk) form = ProductForm(instance=product) if 'edit_product' in request.POST: if request.method =='POST': form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/edit_product_profile.html',context) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['product_sku','name','category','description','r_price','d_price','start_date', 'end_date','stock','min_stock'] Template <div class="row"> <div … -
How to load static files from separate S3 bucket when hosting site on Elastic Beanstalk Aws React Django
Setup: React+Django hosted on Elastic Beanstalk. Static files hosted on separate S3 Bucket. I'm trying to load an image using src="/static/images/logo.png". In development it works perfectly, but in production it sends a request to XXX.elasticbeanstalk.com/static/images/logo.png while it should be requesting Bucket.amazonaws.com/static/images/logo.png. Meanwhile the user uploaded media is working perfectly for both POST and GET requests, images are stored and fetched from the Bucket /media/ path. I want to avoid conditionally coding the absolute url path depending on the environment. I have a django production_settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static") STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_STORAGE_BUCKET_NAME = '****************' AWS_S3_REGION_NAME = '****************' AWS_ACCESS_KEY_ID = '****************' AWS_SECRET_ACCESS_KEY = '****************' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' custom_storages.py: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Thanks -
Reload template variable without refreshing in django
I will auto update template variable without refresh web page when spark streaming finished in view.py view.py spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate() schema = StructType().add("_c0", "integer").add("InvoiceNo", "string").add("Quantity","integer").add("InvoiceDate","date").add("UnitPrice","integer").add("CustomerID","double").add("TotalSales","integer") INPUT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../jsonFileInput") OUTPUT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../jsonFileOutput") CHECKPOINT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../writestream_checkpoints") dataStream = spark.readStream.format("json").schema(schema).load(INPUT_DIRECTORY) query = dataStream \ .writeStream \ .format("json") \ .option("checkpointLocation",CHECKPOINT_DIRECTORY) \ .option("path", OUTPUT_DIRECTORY) \ .start() def dashboardV2 (request): df = spark.read.format('json').schema(schema).option('header',True).load(OUTPUT_DIRECTORY) totalSales = codeData.totalSales(df) ncustomer = codeData.allCustomer(df) return render(request,'dashboardV2.html',{ 'totalSales': totalSales, 'ncustomer': ncustomer }) I need to auto update totalSales and ncustomer variable in template when streaming data. (df variable will read json file that spark streaming and use it to calculate in function for totalSales and ncustomer variable) template.html <!DOCTYPE html> <html> <body> <label class="valueTotalSales2017">$ {{totalSales}} M</label> <label class="valueNumCus2017">{{ncustomer}}</label> </body> </html> codeData.py spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate() def totalSales(df): total = df.select('TotalSales').groupby().sum().toPandas() total = total['sum(TotalSales)'][0]/1000000 # convert to millions total = "%.2f" % total # trim 2 decimal return total def allCustomer(df): ncus = df.select('CustomerID').distinct().count() return ncus Thank for your helping. -
How to create an interface/form in django where the user can use tools such as bold and italicize before submitting (similar to tools in google docs)
I am making a django website where a user inputs an essay. I want to the user to be able to use tools in order to "prettify" their essay by changing font, color, and other elements, and use tools such as bold and italics. For example, if you see the interface where you can ask a question in stack overflow, you can see formatting information on the top. Stack Overflow Create Question Tools -
Django postgre super user connection issue
File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection 2020-06-03T18:40:44.102875+00:00 app[web.1]: connection = Database.connect(**conn_params) 2020-06-03T18:40:44.102876+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect 2020-06-03T18:40:44.102876+00:00 app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) -
How do you get a django model instance from an Angular select dropdown field containing a django-rest-api field with a foreignkey?
I have an application that runs Angular on the client side and Django on the backend, im using Django-request-framework for my model serialization, whereby my model has a model named Job which in turn has a field named job_category which points to a model JobCategory in a foreignkey relationship like this models.py JobCategory(models.Model): title = models.CharField(max_value=100) Job(models.Model): title = models.CharField(max_value=200) job_category = models.ForeignKeyField(JobCategory, on_delete=models.CASCADE) So on my angular component i have a select field which loops over the job categories like this Angular component html form <select id="category" class="form-control color-gray" ngModel name='category'> <option *ngFor='let category of job_categories' [ngValue]="category.id" >{{ category.title }} </option> </select> everything works fine at that point until i select a job category from the Angular options and post it, then i get the error that "ValueError at /api/jobs/↵Cannot assign "'Companion Care'": "Job.job_category" must be a "JobCategory" instance. how can i fix this or how do you select an instance of JobCategory? -
Django clear rest api urls for function based views
I am writing the code using function based views ( I have some reasons for it ), and I need to solute one trouble. I want to have clear urls (like posts/id for detail view and the same posts/id for update view and posts/id for delete view ). But I don't know how we can do it using just usual function based views. I have tried to remove /update, /create/ delete/ from my views, but without that it doesn't work :) I suppose it happens because Django doesn't know, which request is for posts/id ( it might be get detail request, update or delete ). Could you help me? My urls for posts: from django.urls import path from posts.views import ( api_detail_post_view, api_create_post_view, api_update_post_view, api_delete_post_view, api_list_post_view ) app_name = "posts" urlpatterns = [ path('', api_list_post_view, name="list"), path('<int:post_id>/', api_detail_post_view, name="detail"), path('<int:post_id>/update/', api_update_post_view, name="update"), path('create/', api_create_post_view, name="create"), path('<int:post_id>/delete/', api_delete_post_view, name="delete"), ] -
Re-writing of the raw query
I had written a SQL raw query in python for the Postgres database. However, the following query I wrote for was when my Song field in my Django model was a many-to-many field. But, due to other requirements, the same Song field in the model has been changed to the foreign key. The issue, I am facing is that the query doesn't runs successfully and returns an error. I had written two raw Postgres queries: raw query:(Using left join) select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from ( select id, name, artist, album, albumart, "albumartThumbnail" from ( select song_id from core_plsongassociation where playlist_id in (1477) ) as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join ( select song_id, votes, bool_or(thirdpartyuser_id=177) as is_requested from ( select * from core_priorityrequests where client_id=2876 and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join ( select core_blockedsongs_song.song_id from core_blockedsongs join core_blockedsongs_song on core_blockedsongs.id=core_blockedsongs_song.blockedsongs_id where core_blockedsongs.unblock_flag = 'f' and core_blockedsongs.client_id=2870 ) as c on c.song_id = songs.id where c.song_id is null; My Model in Django is as follows: class BlockSong(models.Model): client = models.ForeignKey('Client') playlist = models.ForeignKey('Playlist', … -
Run manage.py with custom database configuration
My use case involves running python manage.py migrate with DATABASE_HOST=127.0.0.1 (since I use Cloud SQL Proxy). However, when the application is uploaded and is serving, the database URL needs to change to an actual remote URL. Right now, I upload a special settings.py file that contains the localhost URL when I wish to run the migration command. When I deploy to cloud, I make sure to overwrite that file with a new one (which is essentially the entire file except the database URL is my remote db URL) and then upload it. Is there a better way to achieve this? Something like python manage.py --database_url=127.0.0.1 migrate? -
Read HTML Response and print urls in Django
Im new to Django. Basically i have page where it has all city names, i have added them using admin page and models. Now if i click on any City name it should route to that city's wiki page. My question is how can i get the city name which i have clicked and how can i dynamically pass those city names in URLS appedning the city name to it and call individual wiki page. Here is my html snippet of city, where dests.name is my city name {%for dests in dests%} <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{dests.image.url}}" alt=""> {% if dests.offer %} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="destinations">{{dests.name}}</a></div> <div class="destination_subtitle"> <p>{{dests.desc}}</p> </div> <div class="destination_price">From ${{dests.price}}</div> </div> </div> {%endfor%} My present view has code to check user authentication and load sample html when clicked on city name class Destinations: def destinations(request): # Login.login(request) if request.user.is_authenticated: return render(request,'sample.html') else: print("In Destinations else loop") return redirect('login') -
How to get an url with username as slug parameter django rest framework
i have a balance model with onetoone field with Users models, so every user have a "balance" relationated with themselves. This is my model: class Balance(models.Model): user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE) balance = models.DecimalField(default=0, max_digits=8, decimal_places=2, blank=True) @receiver(post_save, sender=User) def create_balance(sender, instance, **kwargs): if kwargs.get('created', False): Saldos.objects.get_or_create(user=instance) print('created balance model to user') This is my Serializer from django.contrib.auth.models import User from rest_framework import serializers class OwnerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class BalanceSerializer(serializers.ModelSerializer): user = OwnerSerializer(read_only=True) class Meta: model = Saldos fields = '__all__' This is my view from .models import Balance from rest_framework import viewsets from .serializers import BalanceSerializer class BalanceViewSet(viewsets.ModelViewSet): queryset = Balance.objects.all() serializer_class = BalanceSerializer And this is my urls.py from django.urls import include, path from rest_framework import routers from .views import BalanceViewSet router = routers.DefaultRouter() router.register(r'api/balance', BalanceViewSet) urlpatterns = [ path('', include(router.urls)), ] This works fine, problem is that i'd like to the url for every single user be something like http://127.0.0.1:8000/api/balance/username instead of http://127.0.0.1:8000/api/balance/1 Is there any way to put the username that is related that balance in url ? Regards