I am learning django and i am creating a simple Music Library which has 2 basic Models Song and Singer
Now a Singer has a many-to-many relationship with Song
Modles.py
class Singer(models.Model):
name = models.CharField('Singer', max_length=255)
class Song(models.Model):
title = models.CharField(max_length=255)
lyrics = models.TextField()
singer = models.ManyToManyField(Singer)
Now In my Admin Section i modified the singer (Multi Select) Field to Use the Select2 Jquery Plugin and I added the Tagging Support for this Plugin Using the code below :
$(".js-example-tags").select2({
tags: true
})
so i can type and add any new Singer's Name (who is not already Present) at the same time while adding the Song as i don't want a separate UI to add Singers Name.
Now I don't know how to proceed with adding this new Singer's Name to Singers Table and then relate him to the Specific Song in django-admin.
When i submit the form with any New Singer's Name, I get Validation Error. I have searched a lot but cannot seem to find any solution to this.
UPDATE
I tried to add a new Song from the Add Song Page in Admin Panel, In the Singer Field i specified "Some Singer" ( this singer is not present in my DB ). On submitting the form i get the error :
"Some SInger" is not a valid value for a primary key.
forms.py
class SongForm(forms.ModelForm):
class Meta:
model = Song
fields = ['title', 'lyrics', 'image', 'singer', 'pub_date']
widgets = {
'singer': forms.SelectMultiple(attrs={'class': 'multipleSelectBox'}),
}
admin.py
class SongAdmin(admin.ModelAdmin):
class Media:
def __init__(self):
pass
css = {
"all": ('css/plugins/select2.min.css', )
}
js = (
'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
'js/plugins/select2.min.js',
'js/songs.js'
)
form = SongForm
admin.site.register(Song, SongAdmin)
Related
I have the following models (simplified):
class Concert(models.Model):
title = models.CharField(max_length=50)
date = models.DateField()
songs = models.ManyToManyField(Song,
through='RunOrder',
related_name='run_order',
blank=True)
class Song(models.Model):
title = models.CharField(max_length=50)
class RunOrder(models.Model):
concert = models.ForeignKey(Concert, on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete=models.CASCADE)
act_no = models.SmallIntegerField()
scene_no = models.SmallIntegerField()
Basically, songs can be in multiple concerts, concerts have multiple songs.
While creating a new concert in the admin view, I would like to be able to add new songs. Here's what I have:
class ConcertAdmin(admin.ModelAdmin):
...
inlines = [SongInline]
class SongInline(admin.TabularInline):
model = RunOrder
show_change_link = True
extra = 1
But this only lets me select from existing songs. In order to add a new song, I have to use the Song admin interface. When I tried to use Song as the model for SongInline, I got a has no ForeignKey error. Is there a way I can streamline/inline the process of adding new Songs to a Concert?
It turns out this is a default feature, but the admin interface has to be enabled for the Song model:
admin.site.register(Song)
Then you get the little plus sign. Screenshot of django admin inline table.
I have an app in which two models are related with foreign keys.
class Trans(models.Model):
pk = UUIDField(auto=True, primary_key=True, serialize=True, hyphenate=True)
en = models.TextField('English')
class Article(models.Model):
pk = UUIDField(auto=True, primary_key=True, serialize=True, hyphenate=True)
title = models.OneToOneField(Trans)
description = models.OneToOneField(Trans)
Now if I want to add values in Article model via admin interface and for title and description there will be a '+' sign above the field to add values , on click Trans model form popup will shown where I can add values and then that instance will be attach into Article title field (Usual process).
But I do not want to add values like this , I want to show a simple text field to admin there for both title and description and on save those values saved into Trans model and their instance in Article model . In simple words I do not want to show '+' sign to admin but a simple text field.
Is this possible in Django admin if yes then any suggestions ?
I've got a two part question regarding Django Admin.
Firstly, I've got a Django model Classified that has a foreign key field from another table Address. On setting data, I've got no issues with any of the fields and all fields get saved correctly.
However, if I want to edit the foreign field in the entry in Classified, it doesn't display the old/existing data in the fields. Instead it shows empty fields in the popup that opens.
How do I get the fields to display the existing data on clicking the + so that I can edit the correct information?
Secondly, I'm sure I've seen search fields in Django Admin. Am I mistaken? Is there a way for me to implement search in the admin panel? I have over 2 million records which need to be updated deleted from time to time. It's very cumbersome to manually go through all the pages in the admin and delete or edit those.
Adding Model Code:
Classified
class Classified(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=256)
contact_person = models.CharField(max_length=300, blank=True)
email = models.CharField(max_length=100, blank=True)
address = models.ForeignKey(Address)
subcategory = models.ForeignKey(Subcategory)
Address
class Address(models.Model):
id = models.AutoField(primary_key=True)
build_add = models.CharField(max_length=255)
street_add = models.CharField(max_length=255)
area = models.CharField(max_length=255)
city = models.ForeignKey(Cities)
The + means just that - add a new instance of the related object and relate the object you're editing to that. Because you're adding a new object it will be blank to start. If you want to be able to edit existing related objects from another object's admin you need to use inlines.
In your app's admin.py have something like:
from django.contrib import admin
from yourapp.models import Address, Classified
class AddressInline(admin.TabularInline):
model = Address
class ClassifiedAdmin(admin.ModelAdmin):
inlines = [AddressInline,]
admin.site.register(Classified, ClassifiedAdmin)
Adding search from there is really easy.
...
class ClassifiedAdmin(admin.ModelAdmin):
inlines = [AddressInline,]
search_fields = [
'field_you_want_to_search',
'another_field',
'address__field_on_relation',
]
...
Note the double underscore in that last one. That means you can search based on values in related objects' fields.
EDIT: This answer is right in that your foreignkey relationship is the wrong way round to do it this way - with the models shown in your question Classified would be the inline and Address the primary model.
My models.py looks like this :
class Author(models.Model):
name = models.CharField()
class DraftBooks(models.Model):
title = models.CharField()
author = models.ForeignKey(Author)
status_choices = ((1,Draft),(2,Published))
status = models.SmallIntegerField(choices=status_choices)
class PubBooks(DraftBooks):
class meta:
proxy = True
verbose name = 'Published Books'
I am using a proxy model since I want a different change list view for books in draft state and books which have been published.To achieve this,my admin.py looks like this :
class AuthorAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)
class DraftBooksAdmin(admin.ModelAdmin):
list_display = ('title','author','status')
def queryset(self):
return DraftBooks.objects.filter(status='1')
admin.site.register(DraftBooks, DraftBooksAdmin)
class PubBooksAdmin(admin.ModelAdmin):
list_display = ('title','author','status')
def queryset(self):
return PubBooks.objects.filter(status='2')
admin.site.register(PubBooks, PubBooksAdmin)
This setup works perfectly fine.In my admin,now I have 3 change list views,one which shows a list of all authors,one which shows book which are in a draft state and finally one which shows the list of books which are in a published state.
I now need to add a hyperlink to every item (Author) in the authors' list overview that links to a view showing all books of the specific authors.For Example:
J.K. Rowling (books)
J.R.R. Tolkien (books)
where books is a hyperlink to a site showing all books of a particular author.
Now I am completely clueless as to how to do this.Django Xadmin has a plugin which provides just this feature.This Stackoverflow question also provides answer to this problem.But the problem is that they do not work in proxy models with the custom filters that I have.When I try to get the list of books by an author,I get only the books which are in Draft state.I would ideally want all the books,Draft and Published by an author.How do i achieve this ?
im new to Django and i try to learn it.
The critic point for me is a Form chapter!
My project has a class "charter" and i want to display all objects (by field name) into a dropdown menu!
and i want to create 2 anothers dropdown form for a particular "search" (by type and guest)
models.py
class Charter(models.Model):
name = models.CharField(max_length=200)
type = models.CharField(max_length=200)
guest = models.CharField(max_length=200)
the picture explains better...
https://lh6.googleusercontent.com/-lJDVVEVRpJc/T2NHRphgdPI/AAAAAAAAAdk/By8oki041fI/w490-h500-k/Schermata%2B2012-03-16%2Ba%2B14.45.02.jpg
(sorry for bad english)
In your forms.py, you can create what's called a ModelForm by doing:
class CharterForm(forms.ModelForm):
class Meta:
model = Charter