Opened 20 months ago

Last modified 19 months ago

#27595 assigned Bug

ForeignKey to model subclass using UUID as primary key isn't populated in form's <select>

Reported by: oyooyo Owned by: Sarthak Mehrish
Component: Forms Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Sample models.py:

from django.db import models

import uuid

class Base_Model(models.Model):
	id = models.UUIDField(primary_key = True, default=uuid.uuid4, editable=False)
	# id = models.AutoField(primary_key = True)
	prototype = models.ForeignKey('Prototype_Model', blank=True, null=True)
	def __str__(self):
		return str(self.id)

class Prototype_Model(Base_Model):
	pass

Sample admin.py:

from django.contrib import admin

from .models import Prototype_Model

class Base_Model_Admin(admin.ModelAdmin):
	list_display = ['id', 'prototype']

admin.site.register(Prototype_Model, Base_Model_Admin)

Steps to reproduce:

  1. Create a Prototype_Model via the admin. Leave the "prototype" ForeignKey field empty.
  2. Create another Prototype_Model via the admin. For the "prototype" ForeignKey field, choose the first created Prototype_Model from the dropdown
  3. Switch to the Prototype_Model list view, it should show that the "prototype" ForeignKey field of the second Prototype_Model indeed references the first model
  4. Click on this second Prototype_Model in order to access the change/edit model form and look at the dropdown for the "prototype" field. The expected behaviour is that the dropdown should have the referenced first model automatically selected, but instead, nothing is automatically selected.

If an AutoField is used instead of a UUIDField as the primary key "id" field (see commented out line in Base_Model), the behaviour is as expected.

Change History (2)

comment:1 Changed 20 months ago by Tim Graham

Component: UncategorizedForms
Summary: In admin panel, ForeignKey to model subclass using UUID as primary key is not automatically "selected"ForeignKey to model subclass using UUID as primary key isn't populated in form's <select>
Triage Stage: UnreviewedAccepted
Type: UncategorizedBug

I can reproduce this at eb7fb565e6483637fc4ee251940b86db813485a0 on SQLite but not PostgreSQL -- I guess it's based on whether or not the database has a native UUID type. On SQLite, for example, the initial form data appears as {'prototype': '35bba53ceafc4df2b1abc110d5f51b2a'} but the UUID values in the form's <select> have dashes, so there's a mismatch. On PostgreSQL, the initial data is {'prototype': UUID('154e323f-cc57-4399-9023-58357ae9ce21')} and there's no issue.

comment:2 Changed 19 months ago by Sarthak Mehrish

Owner: changed from nobody to Sarthak Mehrish
Status: newassigned
Note: See TracTickets for help on using tickets.
Back to Top