So I am trying to setup an entry posting system, where the user can select a bunch of related entries when creating an entry. And it would be wonderful if I could use the InlineModelAdmin for it. But it keeps wanting a foreignkey, which for some reason I'm unable to set up properly.
Here's a simplified setup of my situation:
models.py
class Entry(models.Model):
entry = models.ForeignKey('self', related_name='related_entry', null=True, blank=True)
title = models.CharField(max_length=100, verbose_name='title')
description = models.TextField(verbose_name='description')
def __unicode__(self):
return self.title
admin.py
class EntryInline(admin.TabularInline):
model = Entry
verbose_name = "related entry"
class EntryAdmin(admin.ModelAdmin):
inlines = [
EntryInline,
]
admin.site.register(Entry, EntryAdmin)
The problems im getting are of the likes:
DatabaseError at /admin/app/entry/add/
column app_entry.entry_id does not
exist LINE 1: SELECT "app_entry"."id",
"app_entry"."entry_id", "...
I'm still just kneedeep into the magic world of django, so if someone could point me out where I am going wrong that would be greatly appreciated!
First, I tried the code you provided in my machine (Django 1.2.3, Python 2.6.2, Ubuntu Jaunty) and it worked well as far as I could tell.
where the user can select a bunch of related entries when creating an entry.
Shouldn't you be using a ManyToMany relationship if you want an entry to be related to a bunch of entries? Your code currently defines a ForeignKey instead.
admin.py
...
admin.site.register(Entry, EntryAdmin)
Your admin is presently set up to let the user add an entry and also (optionally) one or more related entries in the same page (this worked perfectly). Was this your expectation?
Related
I am trying to query and annotate some data from my models:
class Feed(models.Model): # Feed of content
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Piece(models.Model): # Piece of content (video or playlist)
removed = models.BooleanField(default=False)
feed = models.ForeignKey(Feed, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Other fields are not used in the following queries so I skipped them here.
In my view I need to get queryset of all feeds of an authenticated user. Annotation should contain quantity of all pieces that are not removed.
Initially, Piece model didn't contain removed field and everything worked great with the queryset like this:
Feed.objects.filter(user=self.request.user).annotate(Count('piece'))
But then I added the field removed to Piece model and needed to count only pieces that were not removed:
Feed.objects.filter(user=self.request.user)
.annotate(Count('piece'), filter=Q(piece__removed=False))
It gave me the following error:
'WhereNode' object has no attribute 'output_field'
It is only a little fraction of what django outputs on the error page, so if it is not enough, please let me know what else I need to include in my question.
I tried to include output_field with options like models.IntegerField() or models.FloatField() (properly imported) here and there but got some errors which I do not provide here because I believe those actions made no sense.
I am using Django 2.0.3
Your syntax mistake is here,
Feed.objects.filter(user=self.request.user)
.annotate(Count('piece', filter=Q(piece__removed=False)))
filter needs to apply at Count not at annotate.
Reference from Django's documentation:
https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#filtering-on-annotations
I have a Django website, with model Event, lets say:
class Event(models.Model):
home = models.ForeignKey('Team', related_name='%(class)s_home')
away = models.ForeignKey('Team', related_name='%(class)s_away')
...
class Team(models.Model):
name = models.CharField("team's name", max_length=100)
Using ForeignKeys for this was a bad idea, but anyway, how to make this usable in Django Admin page?
In admin edit event page, a ton of foreign keys is fetched for this:
http://127.0.0.1:8000/admin/event/event/116255/
It produces tons of selects like:
SELECT "event_team"."id", "event_team"."name" FROM "event_team" WHERE "event_team"."id" = 346;
and page dies. I was playing with these:
class EventAdmin(admin.ModelAdmin):
list_display = ('id', 'home', 'away', 'date_game', 'sport', 'result')
search_fields = ['home__name', 'away__name']
list_select_related = (
'home', 'away', 'league', 'sport', ...
)
def get_queryset(self, request):
return super(EventAdmin, self).get_queryset(request).select_related(*self.list_select_related)
admin.site.register(Event, EventAdmin)
But no luck.
The simplest, quickest way
It would be to add raw_id_fields on your ModelAdmin (Django ModelAdmin.raw_id_fields documentation) :
class EventAdmin(admin.ModelAdmin):
raw_id_fields = ("home", "away")
It would result in a inputText with the FK field ids in such as :
.
Loading will be fast as it won't populate a select list with ALL the teams.
You'll have the Django admin change_view of the Team ModelAdmin to select the teams, thanks to the browse icon.
A nicer way ?
A lot more elegant on the UX side of things, it requires you to know part of the name of the team: using an ajax autocomplete widget to represent your field.
You could use for example Django Autocomplete Light (DAL) quick tutorial by having a custom form for your admin and a autocompleteModelSelect2 for your home and away fields (with 2 differents QS in the ajax view).
It will produce a field looking like:
.
The tutorial of this link have all you need!
Or you can chose another third party plugin or build your own field/widget to produce a similar result.
I think #ppython's answer is the simplest and works perfectly but I ended up using autocomplete_fields instead of raw_id_fields. Achieving a more friendly approach, it has been available since Django 2.0.
Following the answer, it'll be something like this:
class EventAdmin(admin.ModelAdmin):
autocomplete_fields = ['home', 'away']
I found the problem, it was my mistake and I did not even mention it in question :(
So this is my model, but I did not mention important part if it:
class Event(models.Model):
home = models.ForeignKey('Team', related_name='%(class)s_home')
away = models.ForeignKey('Team', related_name='%(class)s_away')
merged = models.ForeignKey('Event', null='True', blank='True')
def __unicode__(self):
return str(self.id) + ": " + self.home.name + " - " + self.away.name
Problem was not with home or away, but with merged field, that fetched self.home.name and self.away.name for each event.
Replaced with
def __unicode__(self):
return 'Event id: {}'.format(self.id)
and added merged to list_select_related
fixed my problem. Thanks for help and sorry for incomplete question.
I want the admin interface to show disctrict field only if I choose 'B' as the category. If I choose 'W' I want all fields of Offer model to be displayed. Is it possible to show selected (filtered) fields in admin page depending on the choice in other field in the same model? Thanks in advance for your help.
My models:
class Category(models.Model):
NAME_CHOICES = (
('B', 'BLACK'),
('W', 'WHITE'),
)
name = models.CharField(max_length=200, choices=NAME_CHOICES)
class Meta:
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.get_name_display()
class Offer(models.Model):
category = models.ForeignKey(Category, verbose_name='Kategoria')
city = models.CharField(max_length=128, verbose_name='Miasto')
province = models.CharField(max_length=3)
district = models.CharField(max_length=128, verbose_name='Dzielnica')
def __unicode__(self):
return "Offer number %s" % (self.id)
First of all I must to tell, that django works only in sync way. So if you want to choose which input to use, you must send a request and wait a feedback. In my opinion there're no straight way to do this task correctly.
And I see a few solutions:
1) You can use jQuery for that. But the main problem is that django has a own admin system with a built-in widgets. You can try to customize it in two ways:
Take an app with this option (for example, django-admin-tools) and create custom behavior on your form;
manage.py collectstatic and after that going to admin folder and create custom jQuery script.
2) Build a custom admin form for your model with ModelChoiceField. I don't quit sure about this field behavior really help you, but you can investigate that.
If I need to do this task, I choose first way with admin static and custom jQuery.
I have just begun to play around with Django admin views, and to start off, I am trying to do something very simple: showing several fields in the listing of objects using list_display as explained here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/
This is my dead simple code:
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'category')
Unfortunately, the list_display option is causing the columnar view to appear, but only some of the objects (40 out of 85) are now displaying in the listing. I cannot deduce why certain objects are showing over the others - their fields look like they are filled similarly. It's clearly not paginating, because when I tried it on an admin of another model, it showed only 2 objects out of about 70 objects.
What might be going on here?
[UPDATE] Article Model:
class Article(models.Model):
revision = models.ForeignKey('ArticleRevision', related_name="current_revision")
category = models.ForeignKey('meta.Category')
language = models.ForeignKey('meta.Language', default=get_default_language)
created = models.DateTimeField(auto_now_add=True, editable=False)
changed = models.DateTimeField(auto_now=True, editable=False)
title = models.CharField(max_length=256)
resources = models.ManyToManyField('oer.Resource', blank=True)
image = models.ManyToManyField('media.Image', blank=True)
views = models.IntegerField(editable=False, default=0)
license = models.ForeignKey('license.License', default=get_default_license)
slug = models.SlugField(max_length=256)
difficulty = models.PositiveIntegerField(editable=True, default=0)
published = models.NullBooleanField()
citation = models.CharField(max_length=1024, blank=True, null=True)
Before adding list_display:
After adding list_display:
[UPDATE] This behaviour occurs only when ForeignKey fields are included in list_display tuple. Any of them.
[UPDATE] Category model code:
class Category(models.Model):
title = models.CharField(max_length=256)
parent = models.ForeignKey('self')
project = models.NullBooleanField(default=False)
created = models.DateTimeField(auto_now_add=True, editable=False)
slug = models.SlugField(max_length=256, blank=True)
def __unicode__(self):
return self.title
This behavior is caused by a foreign key relation somewhere that is not declared as nullable, but nonetheless has a null value in the database. When you have a ManyToOne relationship in list_display, the change list class will always execute the query using select_related. (See the get_query_set method in django.contrib.admin.views.ChangeList).
select_related by default follows all foreign keys on each object, so any broken foreign key found by this query will cause data to drop out when the query is evaluated. This is not specific to the admin; you can interactively test it by comparing the results of Article.objects.all() to Article.objects.all().select_related().
There's no simple way to control which foreign keys the admin will look up - select_related takes some parameters, but the admin doesn't expose a way to pass them through. In theory you could write your own ChangeList class and override get_query_set, but I don't recommend that.
The real fix is to make sure your foreign key model fields accurately reflect the state of your database in their null settings. Personally, I'd probably do this by commenting out all FKs on Article other than Category, seeing if that helps, then turning them back on one by one until things start breaking. The problem doesn't have to be with a FK on an article itself; if a revision, language or category has a broken FK that will still cause the join to miss rows. Or if something they relate to has a broken FK, etc etc.
I have several models with several fields in my app. I want to set up a way for the user to be able to modify a help text system for each field in the model. Can you give me some guidance on how to design the models, and what field types to use? I don't feel right about storing the model and field name in CharFields, but if that is the only way, I may be stuck with it.
Is there a more elegant solution using Django?
For a quick and silly example, with an app named jobs, one named fun, and make a new app named helptext:
jobs.models.py:
class Person(models.Model):
first_name = models.CharField(max_length=32)
.
.
interests = models.TextField()
def __unicode__(self):
return self.name
class Job(models.Model):
name = models.CharField(max_length=128)
person = models.ForeignKey(Person)
address = models.TextField()
duties = models.TextField()
def __unicode__(self):
return self.name
fun.models.py:
class RollerCoaster(models.Model):
name = models.CharField(max_length=128)
scare_factor = models.PositiveInteger()
def __unicode__(self):
return self.name
class BigDipper(RollerCoaster):
max_elevation = models.PositiveInteger()
best_comment_ever_made = models.CharField(max_length=255)
def __unicode__(self):
return super.name
Now, let's say I want to have editable help text on Person.interests, and Job.duties, RollerCoaster.scare_factor, and BigDipper.best_comment_ever_made. I'd have something like:
helptext.models.py:
from django.contrib.contenttypes.models import ContentType
class HelpText(models.Model):
the_model = models.ForeignKey(ContentType)
the_field = models.CharField(max_length=255)
helptext = models.CharField(max_length=128)
def __unicode__(self):
return self.helptext
So, what is the better way to do this, other than making HelpText.the_model and HelpText.the_field CharFields that have to be compared when I am rendering the template to see if helptext is associated with each field on the screen?
Thanks in advance!
Edit:
I know about the help_text parameter of the fields, but I want this to be easily edited through the GUI, and it may contain a LOT of help with styling, etc. It would be HTML with probably upwards of 50-60 lines of text for probably 100 different model fields. I don't want to store it in the field definition for those reasons.
I changed the HelpText model to have a reference to ContentType and the field a CharField. Does this seem like a good solution? I am not sure this is the most elegant way. Please advise.
Edit 2013-04-19 16:53 PST:
Currently, I tried this and it works, but not sure this is great:
from django.db import models
from django.contrib.contenttypes.models import ContentType
# Field choices for the drop down.
FIELDS = ()
# For each ContentType verify the model_class() is not None and if not, add a tuple
# to FIELDS with the model name and field name displayed, but storing only the field
# name.
for ct in ContentType.objects.all():
m = ct.model_class()
if m is not None:
for f in ct.model_class()._meta.get_all_field_names():
FIELDS += ((f, str(ct.model) + '.' + str(f)),)
# HelpText model, associated with multiple models and fields.
class HelpText(models.Model):
the_model = models.ForeignKey(ContentType)
the_field = models.CharField(max_length=255, choices=FIELDS)
helptext = models.TextField(null=True, blank=True)
def __unicode__(self):
return self.helptext
Doesn't feel like the best, but please advise if this is a solution that will bite me in the behind later on and make me filled with regrets... :*(
The solution works, and I have it implemented, but you have to be aware that sometimes the ContentTypes get out of sync with your models. You can manually update the content types with this:
python manage.py shell
>>> from django.contrib.contenttypes.management import update_all_contenttypes
>>> update_all_contenttypes(interactive=True)
This allows you to add the new ones and remove the old ones, if they exist.
The nice thing about the Field not being a foreign key is that I can put anything in it for help text. So, say I have a field "First Name." I can put a helptext connected to the Person model and the "first_name" field. I can also make something up, like "Something really confusing." The helptext is now associated with the Person model and the "Something really confusing" field. So, I can put it at the top of the form, instead of associating to a field with hard foreign keying. It can be anything arbitrary and will follow with that "field" anywhere. The hangup would be that you may change the name of the helptext field association inadvertently sending your original helptext into never land.
To make this easy, I created a TemplateTag, which I pass the name of the model and the name of the "field" I want to associate. Then anytime the template is rendered, that helptext is there, editable for anybody to get assistance with their user interface forms.
Not sure this is the best solution, but I couldn't really see any other way to do it, and got no responses.
Cheerio!