Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get Django forms to save to User and Profile model
I am trying to extend the Django User model by creating a user Profile model. I am able to create the models successfully, but I can't get the information entered into the custom UserCreationForm to save the data. I can't get the new forms on the same page and get the information related to the User to save. When I try i get the error of 'Anonymous User has to data _meta' models.py class Profile(models.Model): ''' periods = [ ('-','-'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('6','6'), ('7','7'), ] ''' user = models.OneToOneField(User,on_delete=models.CASCADE) period = models.IntegerField(default=1) first_name = models.CharField(max_length=100,default='Home') last_name = models.CharField(max_length=100,default='Simpson') def __str__(self): return f'{self.user.username}' forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserProfileForm(forms.ModelForm): periods = [ (1,1), (2,2), (3,3), (4,4), (6,6), (7,7), ] period = forms.ChoiceField(choices=periods) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = Profile fields = ['first_name','last_name','period'] signals.py @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() views.py def login(request): context = { 'title':'Login', } return render(request,'users/login.html',context) def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') email_domain = re.search("@[\w.]+", email) if email_domain.group() == EMAIL_DOMAIN: form.save() username = form.cleaned_data.get('username') messages.success(request,f'Account created for {username}! You are … -
How can I restrict the options for ForeignKey to keys inside a ManyToMany field
I have a ManyToManyField that stores a users "inventory" which is a ManyToManyField of items, I also have a foreign key field "active" that stores the id of the active item of the user. I was wondering if there was a constraint I could put so that any "active" id must be in the ManyToMany inventory. -
Injecting custom data into Django Queryset before passing to template
What is the best way to append or inject some extra data into a Django QuerySet? Imagine a situation where I am displaying a list of Books, and I want to show the result of a special calculation on each one: models.py class Book(models.Model): name = models.CharField(max_length=64) book_list.html {% for book in objects %} {{ book.name }} - {{ book.special_result }} {% endfor %} views.py class BookListView(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) books = self.object_list for book in books: book.special_result = do_special_calculation(foo=bar) context['books'] = books return context Imagine that do_special_calculation() method cannot be calculated in the template or as a model parameter, because it needs to have a variable foo passed in. This code does not achieve the desired result of making each book's special_result value accessible from the template, because the book variable is overwritten with each iteration of the for loop. Every solution I've come up involves basically building out a new dictionary in parallel with the QuerySet, passing that into the template, and looping through them both in the template simultaneously, causing very ugly code. I also don't want to save the result of do_special_calculations() back to the database for a host of reasons (efficiency, potential … -
SQL join in Django without foreign key
I need to do the following join in views.py, I did some research and the select_related function works for me but the tables do not have a foreign key between them, how could I do the join with specific fields, specifically "id_curso" SELECT * FROM ALUMNO A JOIN HORARIO H ON (A.ID_CURSO = H.ID_CURSO) models.py class Alumno(models.Model): rut_alumno = models.IntegerField(primary_key=True) dv_alumno = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15) s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) fecha_nac = models.DateField() genero = models.CharField(max_length=1) direccion = models.CharField(max_length=25, blank=True, null=True) nivel_socio = models.CharField(max_length=10) id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING, db_column='id_examenes') rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING, db_column='rut_apoderado') id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio') id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso') id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') class Horario(models.Model): id_horario = models.IntegerField(primary_key=True) dia = models.CharField(max_length=10) hora_inicio = models.CharField(max_length=5) hora_termino = models.CharField(max_length=5) annio = models.IntegerField() id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura') id_sala = models.ForeignKey('Sala', models.DO_NOTHING, db_column='id_sala') rut_profesor = models.ForeignKey('Profesor', models.DO_NOTHING, db_column='rut_profesor') id_curso = models.ForeignKey(Curso, models.DO_NOTHING, db_column='id_curso') views.py def vistaAlumno(request): horarios = Alumno.objects.select_related('') return render(request, 'core/vistaAlumno.html', {'horarios': horarios}) -
Django file not showing input data in actual website
I'm currently attempting to learn how to use django to build a website but my input data in the models is not showing up properly ''' from django.db import models class products(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class typeWork(models.Model): work = models.CharField(max_length = 255) hoursWorked = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(products, on_delete=models.CASCADE) ''' models.py ''' from django.urls import path from . import views urlpatterns = [ path('hello/', views.hello, name='hello') ] ''' urls.py from django.shortcuts import render from django.http import HttpResponse from .models import typeWork def hello(request): products2 = {typeWork.objects.all()} return render(request, 'index.html', {products2}) views.py is slightly altered as i was messing with it in order to try and fix it the image shows the code with no alterations and my original issue arising from that code views.py <table class="table"> <thead> <tr> <th>Work</th> <th>Type of Work</th> <th>Hours needed</th> </tr> </thead> <tbody> {% for products2 in products%} <tr> <td>{{products2.work}}</td> <td>{{products2.genre}}</td> <td>{{products2.hoursWorked}}</td> </tr> {% endfor %} </tbody> indes.html is also slightly altered the image will show the original code before i tried fixing it again index.html Actual error and what it does show currently -
How do I get more than one value in a Django filter method?
I'm trying to get more than one query parameter in as a value to a filter method. For example, my request ,contains invite_status=not_invited&invite_status=completed My filter method starts is defined as def filter_by_invite_status(self, queryset, field_name, value): Value gets set as the last parameter in the request, in this case completed. How can I get both not_invited and completed? https://django-filter.readthedocs.io/en/stable/ref/filters.html#method -
oReverseMatch at /reviews/ Reverse for 'reviews_detail' with arguments
Have serious issues with the following. have a reviews app in my project where people can read, leave, edit and delete views. Was all working fine in gitpod on the local side but then when i pushed to Heroku i started getting errors. On Heroku I was gettings a null constraint error and on the local side I was getting "null value in column" error. I cleared my database, deleted users and created a new superuser after updating the models to use uuid instead. Now i'm getting a noreverse error on the local side (god only knows what's going to happen when i push it to Heroku but lets deal with one thing at a time). Anyways I'll attach all relevant code below. Have a project due tomorrow so any help would be massively appreciated. reviews.html {% extends "base.html" %} {% load static %} {% block content %} <div class="container-fluid text-white"> <div class="row mt-5"> {% for review in object_list %} <div class="col col-md-3 reviews"> <h1 class="pt-3">Title: {{ review.title }}</h1> {% if request.user.is_authenticated %} {% if user.id == review.user.id %} <a href="{% url 'update_review' review.pk %}">Edit</a> <a href="{% url 'delete_review' review.pk %}">Delete</a><br> {% endif %} {% endif %} <a href="{% url … -
dj_rest_auth 403 error using django_rest_framework_simplejwt authentication
I am currently working on a Django project and I am using Django 4.0 version so I am user DJ_REST_AUTH for my package and I am currently having 403 error when passing my access token and this is my configuration REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', # used for swagger login # 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',} REST_USE_JWT = True -
Django Form: Drop-Down/Select Not Rendering
Hey so my present problem is that I've a form, Command_Form which has two fields, host_id and current_commands. Current_commands should be a drop-down menu of choices from CHOICES. Likely a super simple solution and I'm just blind to it, as you sometimes are with coding any help appreciated. Forms.py code from django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node from .models import beacon CHOICES = [ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ] class Command_Form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=beacon.objects.all(), widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) Views.py from django.shortcuts import render from django.http import HttpResponse from .models import beacon from .models import command_node from .forms import Command_Form from django.http import HttpResponseRedirect def home(request): form = Command_Form() if request.method == "POST": form = Command_Form(request.POST) if form.is_valid(): form.save() return render(request, 'home.html', {"form": form}) return render(request, 'home.html', {"form": form},) Relevent HTML section /br> </br> <form action="" method=POST> {% csrf_token %} {{ form }} <button type="Submit" class="btn btn-secondary btn-sm">Submit</button> … -
How to save data to a Django model in views.py?
I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add a listing, created through the Listings Model, to their WatchList. I am using a Django form with a Boolean field. I need help saving the listing to the WatchList Model. Also, since there will be more than one WatchList because of the multiple users, should I implement Sessions, and if so, how do I do that? views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) watchlist_form = WatchListForm() watchlist_form = WatchListForm(request.POST) if watchlist_form.is_valid(): watchlist = watchlist_form.save(commit=False) watchlist.user = request.user watchlist.save() return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing "watchlistForm": watchlist_form }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listing = models.ManyToManyField(Listings) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") add_to_watchlist = models.BooleanField(default=False) -
Django literally will not work on repl.it or command prompt
ive been trying to launch Django from command prompt and receiving no such file or directory error for literally weeks now, i put my project path on cd and it stil didnt work and also put the management file in the project. ive now downloaded Django in visual studio code, how does that work. i know i don't just start coding , how do i begin using this extentison or can someone tell me another way to fix command prompt error -
Unable to get Session Id when API called using React
export default function Index(){ // const [auth, setAuth] = useState(); const authenticateSpotify = ()=>{ fetch('http://localhost:8000/spotify/is-authenticated') .then((response) => response.json()) .then((data) => { // setAuth(data.status); console.log(Cookies.get('sessionid')); console.log(data); if(!(data.status)){ fetch('http://localhost:8000/spotify/auth') .then((response) => response.json()) .then((data) => { window.location.replace(data.url); }) // console.log('Hii'); } }) } return( <div> <h1>Hello</h1> <Button variant="contained" onClick={(e)=>{ e.preventDefault(); authenticateSpotify(); }}>Hello World</Button> </div> ); } When I click on button i get enter image description here in other case when I open http://localhost:8000/spotify/is-authenticated it displays me the status as true and is returning session id. Confused please help Github repo for full code: https://github.com/pradhyumanarora/test -
Django v3.2 static files not serving in VS Code windows 11
I am trying to get static files to work in Django 3.2 (python 3.7) running in VS code (in Windows 11). My base template is referring to a style sheet at static/styles/style.css. The static folder is in the project root directory. In my base template I have; {% load static %} <link rel="stylesheet" href="{% static 'styles/style.css'%}"> In my settings.py file, I tried both STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] and STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' I have also added the following to urls.py file; from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() But I keep getting the following error; "GET /static/styles/style.css HTTP/1.1" 404 179 Can someone please provide a solution? Thanks in advance. -
How to add Media Editing tools to a Django Blog project as in Instagram?
I was working on my blog project in Django. I could not find the plugin for editing video or photos while uploading to a DB for example in Instagram while uploading Post you can put some texts, links and can do some edits on images and videos, I wanted the same thing but could find any data on this issue. Thanks for answers ahead ! My Post model: class Post(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=True) title = models.CharField('Title', max_length=400, blank=True) preview = models.FileField('Preview', upload_to='post_previews', blank=True) slug = models.SlugField("*", unique=True, blank=True) -
Next element with jQuery
I need to move on to the next element. My code shows 3 different cards and put the option in ddbb, but when click on the option I need to pass the 'screen-view' to the next card when sucess is ok. I tried .next('.card').toggle() and .show() but don't work, any advice? My template: {% for standard in standards %} <div class="card mx-auto mt-4" style="width: 95%;" data-aos="fade-up"> <div class="card-header"> <h5 class="card-title">Estándar {{standard.code}}</h5> </div> <div class="card-body"> <p class="card-text">{{standard.name}}</p> <div class="card-text"> <div class="table-responsive-sm tabla-standard" data-alternative-url="{% url 'answeruser' %}"> <table class="table table-bordered"> <thead class="thead"> <tr> {% for alternative in standard.alternative_set.visible %} <th> <div class="alternative color-{{forloop.counter}} {% if alternative.pk in answeruser_alternative_pks %} btnAlternativeFocus {% endif %}" data-alternative-pk="{{alternative.pk}}"> <button class="btn btnAlternative-{{forloop.counter}}">{{alternative.name}}</button></div> </th> {% endfor %} </tr> </thead> <tbody class="tbody"> <tr> {% for alternative in standard.alternative_set.visible %} <td> <div class="alternativeDetail {% if alternative.pk in answeruser_alternative_pks %} btnAlternativeFocus {% endif %}">{{alternative.detail|safe|linebreaks}}</div> </td> {% endfor %} </tr> </tbody> <tfoot class="tfoot"> <tr> <th colspan="4">{{standard.diagnosis_tools|safe}}</th> </tr> </tfoot> </table> </div> </div> </div> </div> {% endfor %} <script type="text/javascript"> AOS.init({ duration: 1200, }) $(document).on('click', '.alternative', function () { const $this = $(this) const alternative_pk = $this.data('alternative-pk'); console.log(alternative_pk) const url = $('.tabla-standard').data('alternative-url'); $.ajax({ type: "POST", url: url, // dataType: 'json', // contentType: "application/json; charset=utf-8", … -
django authentification login
I created a django project of which it contains 13 templates and I have 4 specific users (manager, consultant, computer scientist) my question is the following how to authorize each user to access his pages during authentication by login? Any idea ? -
Get error The current path, didn’t match any of these
What is wrong with my code yet it seems to me that everything is correct. I am trying to display a test page with this code: -------- urls.py ------- from django.urls import path from . import views urlpatterns = [ path('http_response/', views.search, name='search'), ] --------views.py------- def search(request): return render(request, 'store/search.html') ------------ But I get the error'The current path, didn’t match any of these. ' -
How to set django csrf and session cookies an ionic capacitor app
I am developing an Ionic 6 capacitor app, with a python Django backend. I am trying to set csrf and sessionid cookies to be able to query a backend api. So far everything works well in browser (both desktop and mobile), but does not seem to work in the built app. I am trying to debug the app on the local network, so during this phase the server is running in http mode on LAN. On the frontend, I am using Ionic 6 with capacitor, and I have the following setup: axiosConfig.js import axios from "axios"; const validateStatus = function (status) { return status >= 200 && status < 500; // default }; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.withCredentials = true; axios.defaults.validateStatus = validateStatus; export default axios; The following requests are made from the frontend: requests.js import endpoints from "../../helpers/endpoints"; import axios from "../../helpers/axiosConfig"; export default { async setCSRFToken() { const response = await axios.get(endpoints.csrfToken); // csrf token set here if (response.status === 200) { console.log("CSRF token set"); return true; } else { this.error = response.data.detail; console.log("Error: ", this.error); return false; } }, async login(username, password) { // sessionid is set here const response = await axios.post(endpoints.login, { username, … -
Convert Python UTC Datetime to local timezone before performing django __date filter
I am trying to convert a utc datetime to a local timezone to filter for matching dates. If I passed a date such as 2022-05-26 and want to find all records with a time on that day, a time such as '2022-05-27T22:00:00.000z' would be excluded... even if that time IS on 2022-05-26 in the local timezone. I was previously filtering using queryset = Event.objects.filter(time__date=time) and am trying to do something like: queryset = Event.objects.filter(time.replace(tzinfo=timezone.utc).astimezone(tz=None)__date=time) however that is invalid syntax, but hopefully you get the point... Thanks! -
Static files do not work after connecting Django to AWS
I'm creating an ecommerce site and am trying to deploy by connecting Django to S3 on Amazon Web Services. However, since doing so my static files won't load when I run the server from GitPod, and I get 404 errors for my static files in the terminal (the Django admin page has also lost all its CSS). However, the static files do work on the deployed heroku page. Additionally, I get a 500 server error on heroku when I try to go to my checkout page, but the checkout page does work when I view it via running the server on gitpod. Something has obviously gone wrong with the connection for the static files on AWS, but I can't work out what. It's probably impossible to solve the problem with that info alone, but perhaps someone may be able to help me narrow down the list of possibilities. -
Why I cant POST review form in DJANGO
I don't know whats the problem, I have created Reviews form, i defined everything correct but still all the data do not save in Database after submitting and also I am not getting any kind of error. but as far as i know i have mentioned everything correctly. please correct me, may be i forgot something I am new to python and Django. Reviews Model: class Reviews(models.Model): reviewer_name = models.CharField(max_length=50, unique=True) review = models.TextField() review_date = models.DateField() def __str__(self): return self.reviewer_name Reviews Function in views.py: from home.models import Reviews def reviewForm(request): if request.method == 'POST': review_name = request.users user_review = request.POST.get('user_review') Myreview = Reviews(reviewer_name= review_name, review = user_review, review_date=dt.today()) Myreview.save() messages.success(request, 'Your Review has been submitted') return render(request, "users/user.html") URLS.PY: from home import views urlpatterns = [ path('users/', views.reviewForm, name="review") ] Review Form in HTML: <div class="overlay"> <form method="POST" action="{% url 'review' %}"> {% csrf_token %} <div class="form-group"> <label class="text-white" for="desc">Review</label> <textarea class="form-control" id="user_review" name="user_review" rows="3"></textarea> </div> <button type="submit" class="btn1 btn2 btn-primary">SUBMIT</button> </form> </div> -
Blog matching query does not exist when using slug
i am using slug to show blogs. here's how creating auto slug def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) if form.is_valid: blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('index') return render(request,'blogs/creatingblog.html',context={'form':form}) here's the anchor tag to lead me to the page <a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a> urls.py path('details/<slug:slug>', views.blog_details, name='blog_details'), slug field on models.py slug= models.SlugField(max_length=264,unique=True) But whenever i am trying to visit is shows me DoesNotExist at /details/25-million-likes-b4067224-d5c5-46b1-9ca6-0cba8680cb11 Blog matching query does not exist. i can visit the page when i am using pk of the blog. But here it says query does not exist for slug. -
Django testing environment is missing Group and Permissions: but I created them in a migration
I'm trying to fix a bunch of tests in a codebase, which are failing due to not having permissions (for ex: update ticket). The weird thing is, I have a migration in place which creates auth Groups and adds the appropriate Permissions to the Groups. I feel like I'm missing something fundamental in Django's test environment setup - I thought it applies migrations before running tests, and that migrations are a preferred way over fixtures for something like this where the Group should always 1. exist and 2. have that Permission. The Migration from django.db import migrations from django.core.management.sql import emit_post_migrate_signal def create_groups(apps, schema_editor): # Ensure permissions and content types have been created. db_alias = schema_editor.connection.alias emit_post_migrate_signal(2, False, db_alias) Permission = apps.get_model("auth", "Permission") Group = apps.get_model("auth", "Group") # Create CC group permission = Permission.objects.get( codename="handle_ticket", content_type__model="ticket" ) corps = Group.objects.create(name="CC") corps.permissions.add(permission) def remove_groups(apps, schema_editor): Group = apps.get_model("auth", "Group") cc = Group.objects.filter(name="CC").delete() class Migration(migrations.Migration): dependencies = [ ("my_app", "previous"), ] operations = [ migrations.RunPython(create_groups, remove_groups), ] The test, which fails with an Auth error. def test_update_ticket(self): ticket = factories.TicketFactory(notes="Old notes") cc_group = Group.objects.get(name="CC") assignee = factories.UserFactory() assignee.groups.set([cc_group]) self.client.force_login(assignee) result = self.client.post( reverse("ticket_update", args=[ticket.id]), data={"notes": "New notes"} ) print(assignee.groups.all(), assignee.get_all_permissions(), assignee.has_perm("my_app.handle_ticket")) #### … -
apply multiple python decorators across a code base
What's the pythonic way of applying the same set of decorators across multiple methods in a code base (django tests)? Example: from mock import patch Class A: @patch('module.function.c') @patch('module.function.b') @patch('module.function.a') def test_a1(self): ... @patch('module.function.c') @patch('module.function.b') @patch('module.function.a') def test_a2(self): ... Class B: @patch('module.function.c') @patch('module.function.b') @patch('module.function.a') def test_b1(self): ... -
Django: Serialize a ManyToMany relationship with a through argument via a related OneToOne model
So the subject may or may not be contextually accurate but what I do know is it involves all of the above and I'm hitting a wall... I'm looking to get a Workspace model's owner URL directly on the Workspace something like: Desired Output { "url": "http://127.0.0.1:8000/api/workspaces/1/", "id": 1, "name": "Ws 1", "slug": "ws-1", "users": [ "http://127.0.0.1:8000/api/users/2/", "http://127.0.0.1:8000/api/users/4/" ], "owner": "http://127.0.0.1:8000/api/users/2/" } Models class Workspace(models.Model): name = models.CharField(max_length=80) users = models.ManyToManyField(UserModel, through="workspaces.WorkspaceUser", related_name="workspaces") class WorkspaceUser(models.Mode): user = models.ForeignKey(User, related_name="user_workspaces", on_delete=models.CASCADE) workspace = models.ForeignKey( Workspace, related_name="workspace_users",on_delete=models.CASCADE) class WorkspaceOwner(BaseTimeStampedModel): workspace_user = models.OneToOneField(WorkspaceUser, on_delete=models.CASCADE) workspace = models.OneToOneField(Workspace, related_name="owner", on_delete=models.CASCADE) Serializers class WorkspaceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Workspace fields = ["url", "id", "name", "slug", "users", "owner"] class WorkspaceUserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = WorkspaceUser fields = ["url", "id", "user"] class WorkspaceOwnerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = WorkspaceOwner fields = ["url", "id", "user"] How can I best serialize the workspace.owner.workspace_user.user url for the HyperlinkedModelSerializer? Thank you!