Hi guys I have this model
class Class1(models.Model):
....
ctime = models.FloatField() # I am storing date in timestamp here
....
Is it possible to display ctime field in admin panel not as float but as time field?
Check Django documentation. You can override default widgets for model fields -
from django.db import models
from django.contrib import admin
# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': RichTextEditorWidget},
}
Or, for a single model, as described in this answer -
class StopAdminForm(forms.ModelForm):
class Meta:
model = Stop
widgets = {
'approve_ts': ApproveStopWidget(),
}
class StopAdmin(admin.ModelAdmin):
form = StopAdminForm
Check other answers in that question too.a
Related
from oscar.apps.catalogue.abstract_models import AbstractProduct
from oscar.core.compat import AUTH_USER_MODEL
from django.db import models
class Product(AbstractProduct):
seller = models.ForeignKey(
AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True)
from oscar.apps.catalogue.models import *
I added this code to forked catalog model >
I want to show it in the dashboard,Image of dashboard and dropdown box I tried admin.site.register but it is not working.
This is the code for override of form , when I fork and overrtide it doesn't work but when I change the code in core it works .
from oscar.apps.dashboard.catalogue.forms import ProductForm
from oscar.core.loading import get_class, get_classes, get_model
from yourappsfolder.catalogue.models import Product
class SellerField(ProductForm):
class Meta(ProductForm.Meta):
model =Product
fields = [
'title','seller', 'upc', 'description', 'is_public', 'is_discountable', 'structure']
You have forked the form incorrectly. Calling your form class SellerField will not work. The form class needs to have exactly the same name as the core form, otherwise Oscar's loader will not find it. Change it like this:
from oscar.apps.dashboard.catalogue.forms import ProductForm as BaseProductForm
class ProductForm(BaseProductForm):
class Meta(BaseProductForm.Meta):
fields = ['title','seller', 'upc', 'description', 'is_public', 'is_discountable', 'structure']
Using the example in the Django documentation for utilizing IntergerRangeField with Postgres backend to create ranges in "ages" with the following model:
from django.contrib.postgres.fields import IntegerRangeField
from psycopg2.extras import NumericRange
from django.db import models
class Event(models.Model):
name = models.CharField(max_length=200)
ages = IntegerRangeField()
def __str__(self):
return self.name
This works perfectly however when using Django Rest Frameworks and using filter view with the following filter:
import django_filters
from django_filters import rest_framework as filters
from app import Event
class EventFilter(django_filters.FilterSet):
ages = django_filters.NumericRangeFilter(queryset=Event.objects.all())
class Meta:
model = Event
fields = ['name','ages']
the view generates an AssertionError at /api/event_filter/ and suggests adding an override to Meta.filters_override.
What I would really appreciate is an example based on the example model for this override, the example in django-filters documentation http://django-filter.readthedocs.io/en/latest/ref/filterset.html#filter-overrides, isn't helping me understand how to get this to render. I would appreciate any help with this so I can understand with this example to utilize this in the future.
Based on the documentation, overriding custom option seems to be done inside the Meta class and not the way you have done it.
ages = django_filters.NumericRangeFilter(queryset=Event.objects.all())
There are a few potential issues here:
The declaration itself does not seem supported
The overrides appear to be supported from within the Meta class
queryset is not a valid option for NumericRangeFilter AFAIk
Can you try the following:
from django.contrib.postgres.fields import IntegerRangeField
class EventFilter(django_filters.FilterSet):
class Meta:
model = Event
fields = ['name','ages']
filter_overrides = {
IntegerRangeField: {
'filter_class': django_filters.NumericRangeFilter,
}
}
Working on a similar thing.
from django.contrib.postgres.fields import ArrayField
import django_filters
class SkillFilter(django_filters.Filters):
class Meta:
model = Skill
filter_overrides = {
ArrayField: {
'filter_class': django_filters.CharFilter,
'extra': lambda f: {
'lookup_expr': 'icontains',
},
},
}
class SkillType(DjangoObjectType):
class Meta:
model = Skill
filterset_class = SkillFilter
interfaces = (relay.Node, )
Then my model
from django.contrib.postgres.fields import ArrayField
from django.db import models
class Skill(models.Model):
name = models.CharField(max_length=50)
skills = ArrayField(models.CharField(max_length=200), blank=True)
Doing this solves the problem, hopefully you can leverage on this to get a solution
Note: I think django_filters does not have support for an array filter that is why I used the CharFilter and this works for me
I've been trying to change the widget used in the admin but can't seem to get it to work - there is presumably something I'm not doing quite right after looking at the docs. I'm get a models is not defined error but defining models or changing models.ManyToManyField to use the actual Product.ManyToManyField doesn't seem to work either?
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ('supplier', 'name', 'last_updated')
# model = Product
inlines = [ProductPricesInline,]
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
you forgot to import models?
from django.db import models
# ...
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
This may be a stupid question but I can't find any clear answers.
How do I change the display in the Django Admin so the Pointfield does not show up like a OpenLayer Map but as a regular input field. I need to see the long, lat for debugging..
Do i have to change the field type? Widgets?
Thanks!
Update
This is how I managed -at last- to keep separate fields for lattitude and longitude without having to save them in the database since the values are already saved in the PointField.
The idea is :
If we are inserting a new entry, the latitude and longitude fields will be used to set the PointField
If we open an existing PointField entry, it will be used to provide the latitude and longitude values in the relevant FormFields.
models.py
from django.contrib.gis.db import models as geomodels
class Entry(geomodels.Model):
point = geomodels.PointField(
srid=4326,
blank=True,
)
admin.py
from myapp.forms import EntryForm
from django.contrib import admin
class EntryAdmin(admin.ModelAdmin):
form = EntryForm
admin.site.register(Entry, EntryAdmin)
forms.py
from django import forms
from myapp.models import Entry
from django.contrib.gis.geos import Point
class MarketEntryForm(forms.ModelForm):
latitude = forms.FloatField(
min_value=-90,
max_value=90,
required=True,
)
longitude = forms.FloatField(
min_value=-180,
max_value=180,
required=True,
)
class Meta(object):
model = MarketEntry
exclude = []
widgets = {'point': forms.HiddenInput()}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
coordinates = self.initial.get('point', None)
if isinstance(coordinates, Point):
self.initial['longitude'], self.initial['latitude'] = coordinates.tuple
def clean(self):
data = super().clean()
latitude = data.get('latitude')
longitude = data.get('longitude')
point = data.get('point')
if latitude and longitude and not point:
data['point'] = Point(longitude, latitude)
return data
From the source code of PointField we see that its form class uses the OpenLayersWidget which inherits from the BaseGeometryWidget.
The conclusion is that in this class, the variable display_raw is by default set to False.
If you set it to True in yourapp/admin.py, you will get a textbox with lat and long and other data, useful for debugging purposes:
from django.contrib.gis import admin
from yourapp.models import YourClass
from django.contrib.gis import forms
from django.contrib.gis.db import models
class YourClassAdminForm(forms.ModelForm):
your_attribute = forms.PointField(widget=forms.OSMWidget(attrs={
'display_raw': True}))
class YourClassAdmin(admin.GeoModelAdmin):
form = YourClassAdminForm
admin.site.register(YourClass, YourClassAdmin)
There is also a way to have both a map and manual insertion of longitude / latitude permanently (not only for debugging).
The idea is to use FloatFields to insert the Longitude/Latitude and update the PointField with the inserted data.
You can override a widget with another in Django admin. From the documentation -
from django.db import models
from django.contrib import admin
# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': RichTextEditorWidget},
}
This overrides TextField with RichTextEditorWidget. Just find the field type for point field and override it with TextField.
This is a Model Class
class ModelName(models.Model):
(...)
pasta = TaggableManager(verbose_name=u'Pasta')
and a form template (normal :P )
{{form.as_p}}
I'd like to leave everything very clean and usefull.
But result is a list of TaggedItem Object :( :
[<TaggedItem: id: 2 tagged with general >, <TaggedItem: id: 3 tagged with outer >]
Instead of something like
general, outer
How do it fashionably in Django?
Give a look at the code in: https://github.com/alex/django-taggit/blob/master/taggit/forms.py. You will find the widget used to render the tags. You can use it to render them correctly.
Example:
models.py
from django.db import models
from taggit.managers import TaggableManager
class Example(models.Model):
name = models.CharField(max_length=20)
tags = TaggableManager()
forms.py
.models import Example
from django import forms
from taggit.forms import TagWidget
class ExampleForm(forms.ModelForm):
class Meta:
model = Example
fields = ('name', 'tags',)
widgets = {
'tags': TagWidget(),
}
I'd recommend you to check this answer too.
django - django-taggit form
I would use django-taggit-autosuggest as it offers better UI to the user.