I’m encountering an error while attempting to add a reverse-related GenericForeignKey inline form to a model in Django admin. The specific error message states: “‘EventsRaw’ has no ForeignKey to ‘UserEvents’.”
Here’s what I need assistance with:
Displaying UserEvents in the Django admin dashboard.
When navigating to the UserEvents page in the admin dashboard, I would like to see a list of all EventsRaw objects that are reverse-related.
Thank you in advance for your help!
Below is the simple representation of my code:
# models.py
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class UserEvents(models.Model):
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, null=True, blank=True
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
class EventsRaw(models.Model):
raw_message = models.JSONField()
# For Creating test data
def create_events_raw():
events_raw = EventsRaw()
events_raw.raw_message = "test"
events_raw.save()
user_event = UserEvents()
user_event.content_object = events_raw
user_event.save()
# admin.py
from django.contrib import admin
from .models import UserEvents, EventsRaw
class EventsRawInline(admin.TabularInline):
model = EventsRaw
@admin.register(UserEvents)
class User_EventsAdmin(admin.ModelAdmin):
inlines = (EventsRawInline,)
Side note: I would recommend you post the code as part of your message.
When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted.
I’m not following what you’re trying to define as a relationship here. Which side is supposed to be the “one” in this “one-to-many” relationship?
Do you have one UserEvent with many related EventsRaw? Or do you have one EventsRaw with many related UserEvents?
Keep in mind that the ForeignKey exists on the “many” side of that relationship. The entity without the foreign key is the “one” side.
(I’m also not understanding what you’re trying to model with the GenericForeignKey here, but I’m guessing that should be clear once I understand the relationship between the two.)
Are you saying that EventRawA-1, etc, are instances of a model named EventRawA?
For UserEvents, is Event1 an instance of UserEvent?
And based upon the above, you wrote:
This implies a many-to-one relationship from EventRaw to UserEvent, where each instance of EventRaw may be related to multiple instances of UserEvent. Is that correct? (That’s the implication I’m getting based upon your example that both Event1 and Event4 are related to EventRawA-1.