Django MPTT Giving DatabaseError When Saving - django

I have installed MPTT for Django, put it in "installed apps," set up my files, and synced my database. My model shows in admin, but when I click save after trying to add a category I get the following error:
DatabaseError at /admin/myapp/category/add/
relation "django_admin_log" does not exist
LINE 1: INSERT INTO "django_admin_log" ("action_time", "user_id", "c...
Here are my files:
Models:
from django.db import models
from django.contrib.auth.models import User
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
user = models.ForeignKey(User)
name = models.CharField(max_length=30, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
def __unicode__(self):
return self.name
Admin:
from django.contrib import admin
from myapp.models import Category
from mptt.admin import MPTTModelAdmin
admin.site.register(Category, MPTTModelAdmin)

Is it possible, that you've enabled the admin logs feature without running syncdb afterwards? Here you'll find a very similar question.

Related

Dango : Andministration page do not diplay user new well

I am learning Django 2.2, I am trying to display the user name of my model named 'Profile' but instead I have : Profile objet(3), Profile Object(4)
Here is the code in Profile Apps=> models.py :
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import FileExtensionValidator
# Create your models here.
class Profile(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
website = models.URLField(blank=True)
avatar = models.ImageField(upload_to='uploads/img', validators=[FileExtensionValidator(allowed_extensions=['png'])], blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
#property
def get_created(self):
return self.created.strftime("%m/%d/%Y, %H:%M:%S")
def __str__(self):
return "{}-{}".format(self.name, self.get_created)
Here is the code in Profile Apps=> admin.py :
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
Here is the code in Profile Apps=> init.py :
default_app_config = "profiles.apps.ProfilesConfig"
I have this, instead of user name:

Can't create many-to-many object in django admin using django-mptt

I can't create an object in django admin. It raises the error:
ValueError at /admin/app/category/add/
"<Category: >" needs to have a value for field "from_category" before this many-to-many relationship can be used.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/app/category/add/
Django Version: 1.6.5
Exception Type: ValueError
Exception Value:
"<Category: >" needs to have a value for field "from_category" before this many-to-many relationship can be used.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py in __init__, line 524
Python Executable: /usr/bin/python
Python Version: 2.7.6
I can't understand what's going wrong. I have the following models.py:
from django.db import models
from mptt.models import MPTTModel, TreeManyToManyField
class Category(MPTTModel):
name = models.CharField(max_length=255, default=u'')
engName = models.CharField(max_length=255, default=u'', blank=True)
parents = TreeManyToManyField('self', symmetrical=False, related_name='children', blank=True)
description = models.TextField(default=u'', blank=True)
active = models.BooleanField(default=True, blank=True)
def __unicode__(self):
return u"{}".format(self.name)
class MPTTMeta:
order_insertion_by = ['name']
parent_attr = 'parents'
and admin.py:
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from app.models import Category, Pattern
admin.site.register(Category, MPTTModelAdmin)
admin.site.register(Pattern)
The problem with this is the TreeManyToManyField parent.
In a tree structure, nodes can only have one parent. So mptt doesn't support this.
If you use a TreeForeignKey instead you should have better luck.
I've added a note to the django-mptt docs about this.

Django user profile creation happening twice

I am seeing an error with Django user profile creation that has been asked before a few times, but the solutions to the other questions and the Django docs recommended fix is not working.
I have a UserProfile model that I am trying to create when creating a new user object from the Django admin pages.(forgive me on syntax here, it has been a while since I used stack overflow)
class UserProfile(models.Model):
user = models.OneToOneField(User)
organization = models.IntegerField(null=True)
phone = models.CharField(max_length=20, null=True, blank=True)
phone_ext = models.CharField(max_length=8, null=True, blank=True)
team_no = models.CharField(max_length=30, null=True, blank=True)
post_save.connect(create_user_profile, sender=User, dispatch_uid="a.unique.string.that.does.not.help.me")
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
I have added the user profile to the UserAdmin class and unregistered/registered the admin site entries.
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
actions = [set_organization]
exclude = ('is_staff',)
try:
admin.site.unregister(User)
admin.site.unregister(RegistrationProfile)
admin.site.unregister(Group)
## Re-register UserAdminadmin.site.unregister(User)
finally:
admin.site.register(User, UserAdmin)
admin.site.register(RegistrationProfile, RegistrationAdmin)
admin.site.register(Group, GroupAdmin)
So each time that I try to go create a new user I always get a duplicate key error for the user_profile_user_id field. Looking at the logs there is two insert statements being ran on the user save. The first is missing all data input into the user profile fields in the admin interface. The second has all the data but fails since there was already the initial insert with just he user_id.
I have searched the project over a few times looking for a duplicate import of my models.py for the UserProfile class and have found nothing.
Does anyone have any ideas here?
Thank you.
--update --
Django version is 1.3
imports in the profile/models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_save
import logging
imports from the admin.py
from django.contrib import admin
from django.contrib.auth.models import Group
from test.django.registration.models import RegistrationProfile
from test.django.registration.admin import RegistrationAdmin
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import User
from test.django.extranet.profile.models import UserProfile
from test.django.common.models.ajrsonline.ajrsonline_users import AjrsonlineUsers
from test.django.common.middleware.ajrs_ldap import AJRSOnlineLdapBackend
Use if statement so that the first one will be restricted. Like this for example:
if instance.field_name:
//save data here
//In here you can save the value that has complete data

django admin site models not showing

i have a site with django, is showing a basic view, and the admin site,
but when i log into the admin site i cannot see the models:
this are my models.py
from django.db import models
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Admin:
pass
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
so im referencing the admin from my db scheme,
but cannot see this tables in my admin,
what is missing?
thanks!
You need to create a file called admin.py and register any models you want to be accessible from the Django admin:
from django.contrib import admin
from myproject.myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
pass
admin.site.register(MyModel, MyModelAdmin)

How to implement admin meta fields in Django 1.3 User profile?

from django.db import models
from django.contrib.auth.models import User
class MySiteProfile(models.Model):
# This is the only required field
user = models.ForeignKey(User, unique=True)
# The rest is completely up to you...
favorite_band = models.CharField(max_length=100, blank=True)
favorite_cheese = models.CharField(max_length=100, blank=True)
lucky_number = models.IntegerField()
The problem is that
User._meta.admin and MySiteProfile._meta.admin both return NoneType. I've dropped and recreated whole database, but no new fields appeared in admin panel; AUTH_PROFILE_MODULE is set.
There are a few ways you can make your MySiteProfile show up in the admin. One is to simply register your model with the admin, and it will show up under the app name it resides in.
Another is to unregister the contrib user from admin and instead load yours:
#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_app.models import MySiteProfile
class MySiteProfileAdmin(UserAdmin):
def __init__(self,*args,**kwargs):
super(MySiteProfileAdmin).__init__(*args,**kwargs)
fields = list(UserAdmin.fieldsets[0][1]['fields'])
fields.append('favorite_band')
fields.append('favorite_cheese')
fields.append('lucky_number')
UserAdmin.fieldsets[0][1]['fields']=fields
admin.site.unregister(User)
admin.site.register(MySiteProfile, MySiteProfileAdmin)
There are quite a few articles around on this topic, but hope that helps you out.