Yax Yax - 1 year ago 68
Python Question

Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute

I have a model linked to Django

model but when I try saving to that model using
instance, it says 'User' object has no attribute 'mymodel_set'

My models.py:

from django.contrib.auth.models import User
from django.db import models

class MyModel(models.Model):
user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel')
name = models.CharField(max_length=14, blank=True, null=True)

My views.py:

from django.contrib.auth.models import User
from myapp.models import mymodel

def register(request):
#gets data here from template
user = User(username=reg_username, password=reg_password)
user.mymodel_set.create(name= display_name)
return HttpResponse('Success')

Answer Source

If the related object existed, you would use mymodel, but it does not exist and the relationship is void, so it cannot be accessed via the user. Create it first and set the relationship to that user:

mymodel = MyModel.objects.create(name=display_name, user=user)
#                                                   ^^^^ set related user

The _set suffix is usually used for reverse ForeignKey relationships and not for OneToOne relationships.

Also note that the related_name on the user field was already specified as mymodel, and the related field can now be accessed from the User model via user.mymodel

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download