Django Guardian TemplateSyntaxError In Admin - django

Trying to edit object permissions using django-guardian in the admin site I get this error.
Caught VariableDoesNotExist while rendering: Failed lookup for key [adminform] in u'[{}, {\'csrf_token\': }, {\'debug\': True, \'sql_queries\': [{\'stacktrace\':...
Template error
In template /Library/Python/2.7/site-packages/grappelli/templates/admin/change_form.html, error at line 34
The line where the error occurs.
var related_lookup_fields_fk = {% get_related_lookup_fields_fk adminform.model_admin %};
I'm using grappelli and south if that makes any difference.
My model
class Alert(models.Model):
"""Alert for product updates"""
product = models.ForeignKey(Product)
message = models.CharField(help_text="What has changed?",blank=True, max_length=200)
created = models.DateTimeField(auto_now_add=True, editable=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=True, editable=False)
def __unicode__(self):
return u"%s" % self.message
class Meta:
ordering = ['-created']
permissions = (
('view_alert', 'View Alert'),
)
Admin.py
class AlertAdmin(GuardedModelAdmin):
pass
admin.site.register(Alert, AlertAdmin)

grappelli is the key here.
This is related issue #51 (https://github.com/lukaszb/django-guardian/issues/51) which was fixed with https://github.com/lukaszb/django-guardian/commit/a21b044711266534eaef5e58397d0701ec101058.
Unfortunately, I haven't released new django-guardian yet so you can try using pip to install package directly from github:
pip install -e git+git://github.com/lukaszb/django-guardian.git#a21b044711266534eaef5e58397d0701ec101058#egg=django-guardian-1.0.4.dev
Hope that helps.

Related

Why RelatedObjectDoesNotExist is thrown when trying to add an entery from the django admin?

In my models, I have the ImageAlbum model and Image model. In the Image model, I have a ForeignKey field to the ImageAlbum. This code is actually recommended from this article.
class ImageAlbum(models.Model):
def __str__(self):
return str(self.pk)
class Image(models.Model):
name = models.CharField(max_length=255)
image = models.ImageField(upload_to=get_upload_path)
default = models.BooleanField(default=False)
thumbnail = models.ImageField(upload_to=get_thumbnail_path, default='default/default_thumbnail.jpg')
album = models.ForeignKey(ImageAlbum, on_delete=models.CASCADE)
I registered the models in the admin and the Image form looks like that:
And after I hit save, the following exception occurs:
Your ImageAlbum Model should look like this .
class ImageAlbum(models.Model):
image = models.ImageField(upload_to='images/', blank=True) # new
def __str__(self):
return str(self.pk)
Migrate first and then Check again this would work.
I experienced the same issue, in my case it had to do with the migrations. I re-ran migrations afresh after clearing them out and that solved the issue you are highlighting. Of cause this was on a local dev environment with a SQLite db setup, you may not have such a luxury in production.

ValueError in models.py

Here is my models.py file. When I try to migrate it gives me an error.
I changed Class name and it gives me an error. Now if I put even old name, it gives me the same error
from django.db import models
from tinymce.models import HTMLField
class BlockTags(models.Model):
pass
class BlockTags_Text(models.Model):
text = models.CharField(max_length=300, verbose_name='Заголовок 1', null=True, blank=True)
block = models.ForeignKey(BlockTags, related_name="text", verbose_name='Заголовок 1', on_delete=models.CASCADE, null=True,blank=True)
number = models.DecimalField(max_digits=3, decimal_places=0)
ValueError: The field content.BlockTags.text was declared with a lazy reference to 'content.blocktags_text', but app 'content' doesn't provide model 'blocktags_text'.
(venv) appledeMacBook-Pro:letbuycar apple$
app 'content' doesn't provide model 'blocktags_text'.
This means that django doesnt see a blocktags_text model in your models.py, try running makemigrations and then migrate, also try adding at least one field to your empty model.

unique_together does not work in Django shell

I have below model:
class Property(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE)
app = models.ForeignKey(App, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
value = models.CharField(max_length=350, blank=True)
description = models.TextField(blank=True)
pub_date = models.DateTimeField('date_published', default=timezone.now)
class Meta:
verbose_name_plural = "properties"
unique_together = (('value', 'name'),)
def __str__(self):
return self.name
When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.
But in manage.py shell:
>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
In this case I do not get any exceptions and objects are added in database.
I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3
The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.
Check SQLite alter table docs for allowed updates on an existing table.
The admin form throws error because it checks uniqueness by itself without relying on database constraints.

Django South DatabaseError: App inside app - Table doesn't exist

After being inspired by django-oscar, I tried to put a cmsplugin inside its main app. However, after doing a schemamigration --initial I can't use the plugin in Django CMS.
DatabaseError: (1146, "Table 'devel_test.cmsplugin_galleries_gallerycontainer_galleries' doesn't exist")
App Tree
gallery
apps
cmsplugin_galleries
migrations
cms_plugins.py
init.py
models.py
init.py
migrations
static
templates
admin.py
init.py
models.py
views.py
Gallery models
class Gallery(models.Model):
title = models.CharField(_(u'title'), max_length=200)
description = models.TextField(_(u'description'), blank=True)
image_folder = FilerFolderField(verbose_name=_(u'image folder'))
is_video = models.BooleanField(_(u'is video content'), default=False)
snippet = models.TextField(_(u'video snippet'))
class Meta:
verbose_name = _(u'Gallery')
verbose_name_plural = _(u'Galleries')
class GalleryImage(models.Model):
gallery = models.ForeignKey(Gallery, verbose_name=_(u'gallery'))
title = models.CharField(_(u'title'), max_length=200, blank=True)
src = FilerImageField(verbose_name=_(u'image'))
Cmsplugin_galleries models
class GalleryContainer(CMSPlugin):
title = models.CharField(_(u'title'), max_length=200)
galleries = models.ManyToManyField(Gallery, verbose_name=_(u'galleries'))
def __unicode__(self):
return u'%s' % self.title
Since I can properly run it using syncdb --all, what did I do wrong?
Notes:
Using syncdb creates a table with the name cmsplugin_galleries_gallerycontainer_galleries but using south, the table name is cmsplugin_gallerycontainer_galleries
Thanks
Since there was no other alternative I followed #daigorocub tip and replaced all the shorten_name instances of cmsplugin_gallerycontainer_galleries inside the migration file
m2m_table_name = db.shorten_name(u'cmsplugin_gallerycontainer_galleries')
to
m2m_table_name = db.shorten_name(u'cmsplugin_galleries_gallerycontainer_galleries')
This issue was fixed in the development branch of django cms 3.0 (https://github.com/divio/django-cms/issues/2291#ref-pullrequest-26529456) but since my version is older I couldn't update to the latest branch
Thank you guys for your help!

relation error on adding new model class

I have 2 model-classes inside models.py file :
class Certificate(models.Model):
comments = models.TextField(blank=True, default='')
generic_certificate = models.ForeignKey(GenericCertificate, related_name='certificates_awarded')
tag = models.ForeignKey('Tag', related_name='certificates_awarded', null=True, blank=True)
class GenericCertificate(CommonInfo):
CERTIFICATE_TYPE = (('C', 'system created'),
('U', 'user created'))
certificate_icon = models.ImageField(upload_to='certificate/icons', default='defaults/certificate.png')
certificate_type = models.CharField(choices=CERTIFICATE_TYPE, max_length=1, default='C')
template = models.FileField(upload_to='certificate/generic_templates')
They are working fine in django admin , but When I am adding one more model class it starts giving error on hitting Generic certificates option: Included operation : South Migration and syncdb
Exception Type: ProgrammingError
Exception Value:
relation "certificates_genericcertificate" does not exist
LINE 1: SELECT COUNT(*) FROM "certificates_genericcertificate"
newly added model class in same models.py
class PositionCertificate(models.Model):
rewardee = models.CharField(max_length=50, default = '0,0')
org_logo = models.CharField(max_length=50, default = '0,0')
tag_name = models.CharField(max_length=50, default = '0,0')
How to remove this error ? and why this error is coming ?
Error
relation "certificates_genericcertificate" does not exist
means that "certificates_genericcertificate" relation do not exists in your database.
Please do
python manage.py syncdb
and if you are using South you can use
python manage.py migrate
try to hit these commands and if it does not help you, drop your tables/database and recreate tables/database by using syncdb.