0

I'm getting this error:

user = models.OneToOneField(User) TypeError: init() missing 1 required positional argument: 'on_delete'

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

# Create your models here.

class UserProfileInfo(models.Model):

    # creating relationship
    user = models.OneToOneField(User)

    # additional attributes
    portfolio = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_pics', blank=True)

    def __str__(self):
        return self.user.username
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
orphyg
  • 9
  • 1

3 Answers3

1

As the error indicates, you need to specify what should happen, given the object to which you refer is removed, by the on_delete= parameter [Django-doc]. For example:

class UserProfileInfo(models.Model):

    # creating relationship
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # additional attributes
    portfolio = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_pics', blank=True)

    def __str__(self):
        return self.user.username

The options here are:

CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.

Model.delete() isn't called on related models, but the pre_delete and post_delete signals are sent for all deleted objects.

PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

SET_NULL

Set the ForeignKey null; this is only possible if null is True.

SET_DEFAULT

Set the ForeignKey to its default value; a default for the ForeignKey must be set.

SET()

Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported (...)

DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

A similar question is answered here Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Basically following should fix url problem

From Django 2.0 on_delete is required:

user = models.OneToOneField(User, on_delete=models.CASCADE)
Hussain Fakhruddin
  • 3,202
  • 4
  • 25
  • 36
1

put 'on_delete = models.CASCADE' in the constructor

what it does: when you will delete the user object as you have referenced it in the user field of your model. it will also delete the model object of UserProfileInfo for taht particular user.