django-image-cropping not working - python

Trying to use django-image-cropping. I don't get any errors, I just have what looks like CharField in Django Admin instead of the django-image-cropping functionality:
base.py (settings):
from easy_thumbnails.conf import Settings as thumbnail_settings
THUMBNAIL_PROCESSORS = (
'image_cropping.thumbnail_processors.crop_corners',
) + thumbnail_settings.THUMBNAIL_PROCESSORS
added easy_thumbnails and image_cropping to INSTALLED_APPS
models.py:
from image_cropping import ImageRatioField
# ...
class Organization(models.Model):
image_cover = models.ImageField(upload_to='media', blank=True, help_text="blah")
cropping = ImageRatioField('image_cover', '308x850')
admin.py:
from django.contrib import admin
from image_cropping import ImageCroppingMixin
class OrganizationAdmin(ImageCroppingMixin, admin.ModelAdmin):
pass
class OrganizationAdmin(admin.ModelAdmin):
filter_horizontal=['categorys']
#...
admin.site.register(Organization, OrganizationAdmin)

You're defining OrganizationAdmin twice in admin.py. Once, correctly, subclassing ImageCroppingMixin and once without. Since the latter definition overwrites the former, you end up without the Mixin. This is how it should look like:
from django.contrib import admin
from image_cropping import ImageCroppingMixin
class OrganizationAdmin(ImageCroppingMixin, admin.ModelAdmin):
filter_horizontal=['categorys']
#...
admin.site.register(Organization, OrganizationAdmin)

Related

Django:What is best way to import my Custom-User in views.py?

Actually i have created my own custom-user (MyUser) in models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
country=models.CharField(max_length=20)
settings.py
AUTH_USER_MODEL = 'new_user.MyUser'
I created a simple function in views.py to create new users.
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.conf import settings
def save_account(request):
MyUser=get_user_model()
if request.method == "POST":
name=request.POST.get("name")
email=request.POST.get("email")
password1=request.POST.get("password1")
password2=request.POST.get("confirm-password")
country=request.POST.get("country")
new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country)
new_user.save()
return redirect('/')
else:
return HttpResponse("404 Not Found")
1. Here i use get_user_model() function to get my currently custom-user.
2. I have second option to get my custom user just by importing MyUser model from models.py and then use it.
from .models import MyUser
3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way.
from django.conf import settings
MyUser=settings.AUTH_USER_MODEL
but third option returning a string instead of returning my custom-user.but why?
I just want to know that which option is best to import custom-user in views.py and why?
Your first two options are both ok. Using get_user_model makes it easier to reuse the app without changing the import. However many Django projects are not meant to be re-used, in which case the explicit import makes it clearer where the user model is imported from.
settings.AUTH_USER_MODEL is meant to be a string. You set it to a string when you did AUTH_USER_MODEL = 'new_user.MyUser', and Django doesn't automatically change it to the model instance when you access it. It's useful in foreign keys because it means you don't need to import the model. For example:
class MyModel(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)

Is there any official way to get the admin options of a model?

I need to get to the search_fields property defined on the admin options for a model. A long time ago it was really simple and direct (but undocumented), i.e. model._meta.admin.search_fields.
Getting to the admin is the hard part, and the closest I could get was:
def admin_options(model):
from django.contrib import admin
return admin.site._registry.get(model)
I couldn't find the ._registry member documented (and the underscore seems to imply that it isn't public). This also doesn't work for sites that haven't run admin.autodiscover(). The fallback-code does this:
try:
appname = model.__module__.split('.models')[0]
admin_module = appname + '.admin'
__import__(admin_module) # registers admin option classes with AdminSite
except:
return None
else:
return admin.site._registry.get(model)
Is there an official (or simpler) way to get the admin options for a model?
first create model
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
class LocationCode(models.Model):
"""
A web service that will allow user to create there price rule based on conditions
"""
name = models.CharField(max_length=255)
code = models.CharField(max_length=255)
def __unicode__(self):
return self.name
in admin.py you need to add code
from django.contrib import admin
from dx_man.models import LocationCode
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class LocationAdmin(admin.ModelAdmin):
list_display=[]
for x in LocationCode._meta.get_all_field_names():
list_display.append(str(x))
admin.site.register(LocationCode, LocationAdmin)
in url.py add these line
from django.contrib import admin
admin.autodiscover()
You need to ensure the registration code has been run or the site will not contain the (model, modeladmin) in the _registry.
code.py
from django.contrib.admin.sites import site
# run admin registration code before we get here
for model, model_admin in site._registry.items():
if model == whatevermodel:
print(model_admin.search_fields)

Nested Inline in Django Admin

I have the following scenario where there are three models as follows which should be displayed nested in DJango admin. Am using Django 1.6 release and applied settings as put up in https://github.com/Soaa-/django-nested-inlines
However, it didnt turn up with the expected output. Is there any other solutions to implement nested inlines in Django. I'm a newbie to this framework. Kindly guide me to fix this issue.
model.py
class Project(models.Model):
name = models.CharField(max_length=200)
code = models.IntegerField(default=0)
def __unicode__(self):
return self.name
class Detail(models.Model):
project = models.ForeignKey(Project)
value = models.DecimalField(max_digits=5, decimal_places=2)
location = models.IntegerField(default=0)
class Configuration(models.Model):
detail = models.OneToOneField(Detail)
content1 = models.IntegerField()
content2 = models.IntegerField()
admin.py
from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedTabularInline, NestedStackedInline
from myapp.models import Project, Detail, Configuration
class ConfigInline(NestedStackedInline):
model = Configuration
extra = 1
class DetailInline(NestedTabularInline):
model = Detail
inlines = [ConfigInline,]
extra = 1
class ProjectAdmin(admin.ModelAdmin):
inlines = [DetailInline]
admin.site.register(Project, ProjectAdmin)
try https://pypi.python.org/pypi/django-nested-inline .
It has been updated to work with Django 1.6
I believe you've forgotten to set the ProjectAdmin as a NestedModelAdmin:
admin.py :
from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedTabularInline, NestedStackedInline
from myapp.models import Project, Detail, Configuration
class ConfigInline(NestedStackedInline):
model = Configuration
extra = 1
class DetailInline(NestedTabularInline):
model = Detail
inlines = [ConfigInline,]
extra = 1
class ProjectAdmin(NestedModelAdmin):
inlines = [DetailInline]
admin.site.register(Project, ProjectAdmin)
Before you import this below package first install this
pip install django-nested-admin
then add this in installed app list
INSTALLED_APPS = [
...
'nested_admin',
...
]
Now, you can import it.
from nested_inline.admin import NestedModelAdmin, NestedTabularInline, NestedStackedInline

Why are my django model fields not working?

I don't think that it is recognizing the existence of my fields. Here's my models.py:
from django.db.models import *
from django.contrib import admin
from django.forms import *
class Stock(Model):
name = CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)
When I run it, I get this error: "portfolio.stock: "ordering" refers to "name", a field that doesn't exist." When I comment the meta function out and run it, it works fine until the admin site, where when I try to create a stock object, the fields don't show up.
I'm completely confused by what's going on.
The problem is your * imports.
django.db.models.CharField is being replaced by django.forms.CharField:
>>> from django.db.models import *
>>> CharField
<class 'django.db.models.fields.CharField'>
>>> from django.forms import *
>>> CharField
<class 'django.forms.fields.CharField'>
So, actually name = CharField(max_length=60) defines a form field instead of a model one - it breaks everything and makes this bug subtle.
Solution: remove unnecessary forms import and be explicit in your imports:
from django.db import models
from django.contrib import admin
class Stock(models.Model):
name = models.CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)

The model FlatPage is already registered

I'm attempting to work my way through Practical Django Projects. It seems to be a bit old, but I've manage to convert the code up to this point.
At this point the book would like me to change my models.py to be this:
class SearchKeyword(models.Model)
keyword = models.CharField(maxlength=50, core=True)
page = models.ForeignKey(FlatPage, edit_inline=models.STACKED,
min_num_in_admin=3, num_extra_on_change=1)
I know that this is now done in the admin.py instead. So my models.py looks like this:
from django.db import models
from django.contrib.flatpages.models import FlatPage
class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)
class Admin:
pass
def __unicode__(self):
return self.keyword
And the admin.py I've created now looks like this:
from search.models import SearchKeyword
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
class SearchKeywordInline(admin.StackedInline):
model = SearchKeyword
extra = 3
class FlatPageAdmin(admin.ModelAdmin):
model = FlatPage
inlines = [SearchKeywordInline]
admin.site.register(FlatPage, FlatPageAdmin)
When I load the Admin page, I receive:
AlreadyRegistered at /admin/
The model FlatPage is already registered
Exception Value:The model FlatPage is already registered
Thank you!
You have to unregister it first as the app itself ships with an admin.py
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)

Categories

Resources