I am following the Django Poll tutorial, I just changed the models a little: https://docs.djangoproject.com/en/1.5/intro/tutorial02/
I am wondering why my alarm does not show in the admin interface when I add/edit/change a pill. The admin only shows to edit the name, not the related alarm object.
It should display inline, according to the tutorial.
admin.py:
from django.contrib import admin
from pills.models import Alarm,Pill
class AlarmInline(admin.TabularInline):
model = Alarm
extra = 3
class PillAdmin(admin.ModelAdmin):
fieldsets = [
('Drug information', {'fields': ['name']}),
]
inlines = [AlarmInline]
list_display = ('name')
admin.site.register(Pill, PillAdmin)
models.py
from django.db import models
class Pill(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Alarm(models.Model):
pill = models.ForeignKey(Pill)
time = models.DateTimeField('Alarm time')
def __unicode__(self):
return self.time.strftime('%c')
All my models validate. I tried rebuilding the database etc...
Any ideas?
If you've correctly reproduced your code above, the problem is your indentation.
It should be:
class PillAdmin(admin.ModelAdmin):
fieldsets = [
('Drug information', {'fields': ['name']}),
]
inlines = [AlarmInline]
list_display = ('name')
inlines is an attribute of the admin class - it and list_display need to be part of the class definition, not statements at the module level.
Related
I'm not able to get the list_display of admin to show the information from a model method, but the same method displays fine in the fieldsets on the change page. I think I've fixed all my mistakes that are present in other questions/answers on this topic, but I just can't seem to figure out what I've done. Any help will be much appreciated.
Admin:
class StudentAdminConfig(admin.ModelAdmin):
list_dispaly = ('name', 'get_total_funds')
fieldsets=(
(None, {'fields': ('name', 'get_total_funds')}),
)
readonly_fields = ('get_total_funds',)
admin.site.register(Student, StudentAdminConfig)
Models:
(Note: there is another model FundsEvent with a many-to-many relationship to Student)
class Student(models.Model):
name = models.CharField(max_length=255)
def get_total_funds(self):
events = self.get_funds_events()
total = float(0)
for event in events:
if event.income:
total += float(event.amount)
else:
total -= float(event.amount)
return f'${total:.2f}'
get_total_funds.short_description = "Total Funds"
def get_funds_events(self):
return FundsEvent.objects.filter(students_attended=self)
def __str__(self):
return self.name
The annoying thing about this list_display issue is that it's not giving any errors I can traceback, it's just displaying the page with no column for the "Total Funds".
Also, I've sunk so much time into this and it's not even that vital of a feature, just a convenience for me, as I'm literally the only one who will ever look at this display on this particular project, but I'm invested enough that I really want to figure it out, haha.
Again, thanks in advance.
What happens if you fix the typo in
class StudentAdminConfig(admin.ModelAdmin):
list_dispaly = ('name', 'get_total_funds')
fieldsets=(
(None, {'fields': ('name', 'get_total_funds')}),
)
readonly_fields = ('get_total_funds',)
admin.site.register(Student, StudentAdminConfig)
to make it:
class StudentAdminConfig(admin.ModelAdmin):
list_display = ('name', 'get_total_funds')
fieldsets=(
(None, {'fields': ('name', 'get_total_funds')}),
)
readonly_fields = ('get_total_funds',)
admin.site.register(Student, StudentAdminConfig)
it works for me..
from django.contrib import admin
from .models import Student
class StudentAdminConfig(admin.ModelAdmin):
list_display = ['name', 'email', 'phone']
this should be with StudentAdminConfig
admin.site.register(Contact, StudentAdminConfig)
I am using django reset framework to create an API.
Here is my Serializer.py
class ArticleSerializer(serializers.Serializer):
class Meta:
model = Article
fields = ("title", "content")
views.py
class ArticleListView(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetailView(RetrieveAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
urls.py
from .views import ArticleListView, ArticleDetailView
urlpatterns = [
path('', ArticleListView.as_view() ),
path('<pk>', ArticleDetailView.as_view() ),
]
When I pull up http://127.0.0.1:8000/api/, there are 3 objects of Article model in DB and all what I get is this:
[
{},
{},
{}
]
models.py
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
def __str__(self):
return self.title
Why can't I see the values of the title and content of my class ?
There's a small typo in your code.
class ArticleSerializer(serializers.Serializer):
should be:
class ArticleSerializer(serializers.ModelSerializer):
Note the "Model" that you are missing.
With regular Serializer you would need to define the fields explicitly while ModelSerializer will introspect the associated model.
I am trying to build my first django app using the most common posts as a test. Unfortunately the server keeps returning errors such as Postmodel admin not defined. I have tried migrating the new changes but this doesnt work, as well as modifying the views, but it seems i need to explicitly define this model. Could someone point me in the right direction
Heres how my admin.py looks like
from django.contrib import admin
# Register your models here.
from .models import posts
import views
admin.autodiscover()
class PostsModelAdmin(admin.ModelAdmin):
list_display = ('title', 'updated', 'timestamp')
list_display_links = ('updated')
list_editable = ('title')
list_filter = ('updated', 'timestamp')
search_fields = ("title", 'content')
class Meta:
model = posts
admin.site.register(posts)
admin.site.register(PostModelAdmin)
Try this...
from .models import posts
from django.contrib import admin
class PostsModelAdmin(admin.ModelAdmin):
list_display = ('title', 'updated', 'timestamp')
list_display_links = ('updated')
list_editable = ('title')
list_filter = ('updated', 'timestamp')
search_fields = ("title", 'content')
class Meta:
model = posts
admin.site.register(posts, PostsModelAdmin)
The register method takes a model and a class. Your error is because you're just passing the class, which is never allowed unless it's passed after the model.
Also you had a typo in your code. You're missing an s when registering it at the bottom.
In tutorial here I get down to where you run was_published_recently and I get this error:
ImproperlyConfigured at /admin/polls/poll/
PollAdmin.list_display[2], 'was_published_recently' is not a callable or an attribute of 'PollAdmin' or found in the model 'Poll'.
Request Method: GET
Request URL: /admin/polls/poll/
Django Version: 1.4
Exception Type: ImproperlyConfigured
Exception Value:
PollAdmin.list_display[2], 'was_published_recently' is not a callable or an attribute of 'PollAdmin' or found in the model 'Poll'.
Exception Location: C:\Python27\lib\site-packages\django\contrib\admin\validation.py in validate, line 38
here is my code:
from polls.models import Poll
from django.contrib import admin
from polls.models import Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
class PollAdmin(admin.ModelAdmin):
# ...
list_display = ('question', 'pub_date', 'was_published_recently')
admin.site.register(Poll, PollAdmin)
here is my poll model
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
Can you update your question with your Poll model?
It looks like you may have made a mistake when adding the was_published_recently method to your Poll model in the Playing with the API step in Tutorial 1.
Update:
Now that you've posted your model, it does look as if you've missed out the was_published_recently method. Go back over tutorial 1 and add it in.
Secondly, don't include each model more than once in models.py - the second one will replace the first.
My site makes use of Django's User Authentication User model and a custom UserProfile model to store some additional data (birthday, etc.). Is there a way to create a view in Django admin that weaves together fields from both the User and UserProfile models?
I suspect that this code snippet is not even close, but maybe it will help illustrate what I'm trying to do:
from django.contrib import admin
from django.contrib.auth.models import User
from userprofile.models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('name', 'gender', 'User.email') #user.email creates the error - tried some variations here, but no luck.
admin.site.register(UserProfile, UserProfileAdmin)
Error message:
ImproperlyConfigured: UserProfileAdmin.list_display[2], 'User.email' is not a callable or an attribute of 'UserProfileAdmin' or found in the model 'UserProfile'.
Ultimately, I'm trying to create an admin view that has first & last name from UserProfile and email from User.
for displaying user email you need to have a method on UserProfile or UserProfileAdmin that returns the email
on UserProfile
def user_email(self):
return self.user.email
or on UserProfileAdmin
def user_email(self, instance):
return instance.user.email
then change your list_display to
list_display = ('name', 'gender', 'user_email')
Related docs: ModelAdmin.list_display
You could try using InlineModelAdmin to display both User and UserPofile forms in a admin view.
To display user profile information in change list you can create a new method that delegates the values from UserProfile to User model.
For example this should work more or less :)
from django.contrib import admin
from django.contrib.auth.models import User
from my_models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
class UserAdmin(admin.ModelAdmin):
list_display = ['get_userprofile_name', 'email']
list_select_related = True
inlines = [
UserProfileInline,
]
def get_userprofile_name(self, instance):
# instance is User instance
return instance.get_profile().name
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Using Ashoks top answer i made snippet that simplifies this process for large number of fields
class ColumnViewer(object):
pass
column_list = ('name', 'surname', )
for col in column_list:
setattr(ColumnViewer, col, lambda s,i : getattr(i, col))
#admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin, ColumnViewer):
list_display = column_list