I have a model with a location field like so:
from django.contrib.gis.db import models as gis_models
class Facility(models.Model):
location = gis_models.PointField(srid=4326, verbose_name=_('location'), null=True, blank=True)
I want the user to be able to set a location using a map in django admin. I have added the below code in my django admin:
from django.contrib.gis.db import models as gis_models
from mapwidgets.widgets import GooglePointFieldWidget
#admin.register(Facility)
class FacilityAdmin(admin.ModelAdmin):
formfield_overrides = {
gis_models: {'widget': GooglePointFieldWidget},
}
at the end I have added the following setting to my settings.py:
MAP_WIDGETS = {
"GooglePointFieldWidget": (
("zoom", 12),
("mapCenterLocation", [ 50.8157, 9.1846]),
),
"GOOGLE_MAP_API_KEY": env('GOOGLE_MAP_API_KEY')
}
I am using postgis image as my database and the following is my requirements.txt:
asgiref==3.5.2
async-timeout==4.0.2
branca==0.5.0
certifi==2022.9.24
chardet==5.0.0
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
Deprecated==1.2.13
Django==4.1.2
django-crispy-forms==1.14.0
django-environ==0.9.0
django-map-widgets==0.4.0
django-rq==2.5.1
folium==0.13.0
idna==3.4
Jinja2==3.1.2
lml==0.1.0
MarkupSafe==2.1.1
numpy==1.23.4
packaging==21.3
pandas==1.5.1
Pillow==9.2.0
postgis==1.0.4
psycopg2==2.9.4
pyexcel==0.7.0
pyexcel-io==0.6.6
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2022.5
redis==4.3.4
requests==2.28.1
rq==1.11.1
six==1.16.0
sqlparse==0.4.3
texttable==1.6.4
tzdata==2022.5
urllib3==1.26.12
wrapt==1.14.1
The map appears in django admin, but as it turns out, it doesn't read the settings. Also the styling of the map is just unacceptable. Is there any way it could be fixed?
Right now this is what I'm getting in my django admin panel:
Apparently, the syntax is wrong. As it says in the document of Django Map Widgets, formfield_overrides should be written like this:
from django.contrib.gis.db import models as gis_models
class FacilityAdmin(admin.ModelAdmin):
formfield_overrides = {
gis_models.PointField: {'widget': GooglePointFieldWidget},
}
*Notice the PointField added to gis_models.
Also remember to enable Maps Javascript Api in google console as it says here.
Related
Model:
from django.db import models
class VilleStation(models.Model):
nomVille = models.CharField(max_length=255)
adresse = models.CharField(max_length=255)
cp = models.CharField(max_length=5)
def __str__(self):
return self.nomVille
admin.py :
from django.contrib import admin
from prixcarbu.models import VilleStation
class VilleStationAdmin(admin.ModelAdmin):
list_display = ('nomVille', 'adresse','cp',)
fields = ('nomVille', 'adresse','cp',)
admin.site.register(VilleStation, VilleStationAdmin)
I imported a CSV file using database browser for SQLite. Table contains the data but admin page doesn't show it.
Do you see empty model in admin or no model at all?
If you don't see your model in the admin at all check if you added your app to INSTALLED_APPS in settings.py.
After closing my computer and reopening, the data is now visible in the admin. Probably a cache problem. Everything is fine now. Thank you all.
Is there a way to inject a featured image field in Mezzanine / Django RichTextPage's model? I need get a image, to specific pages in "richtextpage.html" template, but these are different from blogPost models that have a featured image field.
[SOLVED] The problem: I was trying to register/unregister a new field in Page model instead RichTextPage, changing the references got the expected result;
# settings.py
EXTRA_MODEL_FIELDS = (
(
"mezzanine.pages.models.Page.page_image",
"ImageField",
("Featured Image",),
{"blank": True, "upload_to": "uploads", },
), ...
# application admin.py
from copy import deepcopy
from mezzanine.pages.admin import PageAdmin
from mezzanine.pages.models import RichTextPage
(...)
pages_fieldsets = deepcopy(PageAdmin.fieldsets)
pages_fieldsets[0][1]["fields"].insert(-2, "page_image")
pages_fieldsets[0][1]["fields"].insert(-3, "content")
class CustomPageAdmin(PageAdmin):
fieldsets = pages_fieldsets
admin.site.unregister(RichTextPage)
admin.site.register(RichTextPage, CustomPageAdmin)
I am trying to fork django-oscar to change the dashboard form for product attributes, multioption. Need to have a description field for every option.
project/oscar_fork/catalogue/models.py:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from oscar.apps.catalogue.abstract_models import AbstractAttributeOption, AbstractAttributeOptionGroup
class AbstractAttributeOption(AbstractAttributeOption):
description = models.CharField(_('Description'), max_length=250, blank=True)
group = models.ForeignKey(
'catalogue.AttributeOptionGroup',
on_delete=models.CASCADE,
related_name='optionsblabla',
verbose_name=_("Group"))
from oscar.apps.catalogue.models import *
The models are changed with the extra field "description" in my DB, but still my form field returns cannot find this field.
project/oscar_fork/dashboard/catalogue/forms.py:
from oscar.apps.dashboard.catalogue import forms as base_forms
class AttributeOptionForm(base_forms.AttributeOptionForm):
class Meta(base_forms.AttributeOptionForm.Meta):
fields = ('option', 'description')
If I change the form.py and models.py fields directly in the Oscar app it works. Other forms can be forked that easily as shown above. Tried it with AttributeOptionGroupForm. I think there is a problem with the sequence of import. How can I solve this?
Error:
django.core.exceptions.FieldError: Unknown field(s) (description) specified for AttributeOption
I am using django-oscar v1.6. Django v.2.08.
Your concrete model should be named AttributeOption without the 'Abstract', otherwise oscar will not pick it up and use its own AttributeOption model instead, which has no description:
class AttributeOption(AbstractAttributeOption):
description = ...
You will have to run makemigrations and migrate after that.
Check the source code of the models module that you import at the end. You will see how their dynamic model loading works:
if not is_model_registered('catalogue', 'AttributeOption'):
class AttributeOption(AbstractAttributeOption):
pass
I'm working with an existing django project that uses south. Within each app there's a models folder where models are stored in different files. I have added a new file (shown below) but when I attempt to create migration files for the model, South fails to detect the new file and says: "Nothing seems to have changed." My question is what is the correct way to get south to detect this new model? Thanks.
from django.contrib.auth.models import User, Group
from django.db import models
from django.contrib import admin
class AdgroupEmailRecipients(models.model):
users = models.ForeignKey(User)
class Meta:
app_label = 'wifipromo'
class AdgroupEmailRecipientsAdmin(admin.ModelAdmin):
list_display = ('user_first_name', 'user_last_name', 'user_email')
def user_first_name(self, obj):
return obj.users.first_name
user_first_name.short_description = "First Name"
def user_last_name(self, obj):
return obj.users.last_name
user_last_name.short_description = "Last Name"
def user_email(self, obj):
return obj.users.email
user_email.short_description = "Email"
In the __init__.py file of the models folder, you have to import the model for South or even syncdb to detect it. Basically django is just looking for one file with all your models... and if you import it all in init.py that's what the system will see.
I need to update an existing project to Django 1.5 to take advantage of its newly available custom user model. However, I'm having trouble migrating reusable apps that contain a model with a foreign key to a user. Currently, the foreign key points to auth.User but with a custom user model, it needs to point to myapp.CustomUser. Hence, some kind of migration is needed. I can't simply create a migration file for it because its a reusable app. It wouldn't be future proof because each time the app is updated, I would need to remember to create that migration again (there might even be migration conflicts) so it's not exactly a plausible solution.
Is there a solution to this problem other than to, maybe, fork each project, add a migration file, and then use that instead?
Some code:
models.py in reusable app
from django.conf import settings
from django.db import models
UserModel = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class ModelA(models.Model):
user = models.ForeignKey(UserModel)
models.py in my project
from django.conf import settings
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
...
settings.py in my project
AUTH_USER_MODEL = 'myapp.CustomUser'
So if the reusable app has a migration that creates a foreign key to a user, the following can be done to support Django 1.5's custom user model.
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class Migration(SchemaMigration):
def forwards(self, orm):
db.create_table('reusableapp.modela', (
('user', self.gf('django...ForeignKey')(to=orm["%s.%s" % (User._meta.app_label, User._meta.object_name)])
models = {
...
# this should replace "auth.user"
"%s.%s" % (User._meta.app_label, User._meta.module_name): {
'Meta': {'object_name': User.__name__},
}
"reusableapp.modela": {
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)})
}
}
I'm not sure if this is the best solution but it's being used in apps such as django-reversion.
However, this solution still can pose a problem if you originally started with auth.User and then changed to myapp.customuser, simply because south is honors AUTH_USER_MODEL but the migration for the custom user model hasn't been created yet. This can occur during testing. Ticket #1179 of south addresses this issue (http://south.aeracode.org/ticket/1179).