I have two Django models:
class Author(models.Model):
user_email = models.CharField(max_length=100, blank=True)
display_name = models.CharField(max_length=250)
class Photo(models.Model):
author = models.ForeignKey(Author)
image = ThumbnailImageField(upload_to='photos')
To get inline photos, I have in admin.py:
class PhotoInline(admin.StackedInline):
model = Author
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
I get an error: Exception at /admin/metainf/author/11/
<class 'metainf.models.Author'> has no ForeignKey to <class 'metainf.models.Author'>
Why?
The inline model should be having a ForeignKey to the parent model. To get Photo as inline in Author your models code is fine. But your admin code should be as follows:
class PhotoInline(admin.StackedInline):
model = Photo
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
Read more info here.
That's because Author doesn't have a foreign key to photo. I think you need to switch the model for the inline like this:
class PhotoInline(admin.StackedInline):
model = Photo
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
Maybe you need to install django-nested-admin library, and later try with NestedStackedInline.
django-nested-admin
Related
I want to try to add a ListField increasible on django admin. I discover I can do that with inlines, so I goes to the doc to find this code :
models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
admin.py
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
I simply copy this code to see how it render on Django admin page.
But the following error appear :
<class 'users.admin.BookInline'>: (admin.E202) 'users.Book' has no ForeignKey to 'users.Book'.
I don't understand why because Book as a ForeignKey. Am I missing something ?
Thx
i am reciving a "value error"
because of "ModelForm has no model class specified."
i tried to check the : models.py forms.py and views.py but all looks pretty good for me
views.py :
class CreatePostView(LoginRequiredMixin,CreateView):
login_url='/login/'
redirect_field_name='Myblog/post_detail.html'
form_class = PostForm
model = Post
models.py:
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True,null=True)
forms.py:
class PostForm(ModelForm):
class meta:
model = Post
fields = ('author','title','text')
from app.urls.py
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
Meta is with an uppercase, according to PEP-8 the names of classes all start with an uppercase. In your form, you should write:
# app/forms.py
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('author','title','text')
Since you wrote it as meta, Django indeed did not understand what model you were using.
If you however do not write a form with specific items, you can - like #DanielRoseman says, just define this at the CreateView [Django-doc]:
class CreatePostView(LoginRequiredMixin,CreateView):
login_url='/login/'
redirect_field_name='Myblog/post_detail.html'
model = Post
fields = ('author', 'title', 'text')
Django can construct a form class through the modelform_factory [Django-doc].
I'm trying to hide and delete two fields from showing in a form I created in the Django administration page using ModelForm.
I looked at answers that said I should use the "exclude" meta field, but I don't know why it's not working in my case.
Here is my code:
models.py:
class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)
I'm trying to exclude the "attendee & volunteer" fields from displaying in the Django administration form.
In admin.py I have:
from django.contrib import admin
from django import forms
from KSUvity.models import Activity
class ActivityForm(forms.ModelForm):
class Meta:
model = Activity
exclude = ['attendee', 'volunteer',]
class ActivityAdmin(admin.ModelAdmin):
exclude = ['attendee', 'volunteer',]
form = ActivityForm
admin.site.register(Activity, ActivityAdmin)
You have to create an admin.py file in your app and register your models
Follow the instuctions
See the example below
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
admin.site.register(Person, PersonAdmin)
You can use either fields or exclude in one class.
In your app admin field add this code.
app_name/admin.py
from django.contrib import admin
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer',)
You have to use ModelAdmin option to exclude fields from form in Django administration, either ModelAdmin.exclude or ModelAdmin.fields. Below is an example:
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer', )
To make it work, you register model like this:
admin.site.register(Activity, ActivityAdmin)
You add this code to admin.py file.
I'm attemping to add copies of a book through a books admin page.
Inside models.py I have:
class Book(models.Model):
...
class BookCopy(models.Model):
book = models.ForeignKey(
'Book',
related_name='copies',
on_delete=models.CASCADE
)
# No additional fields here
class BookCopyInline(admin.StackedInline):
model = BookCopy
can_delete = False
verbose_name_plural = 'copies'
Inside admin.py I have the following:
class BookCopyInline(admin.StackedInline):
model = BookCopy
can_delete = False
verbose_name_plural = 'copies'
#admin.register(Book)
class BookAdmin(admin.ModelAdmin):
inlines = (BookCopyInline,)
#admin.register(Book)
class BookAdmin(admin.ModelAdmin):
model = Book
list_display = ('isbn', 'title', 'subtitle')
prepopulated_fields = {'slug': ('title',)}
inlines = (BookCopyInline,)
I'd like to be able to add book copies inside the Books Admin page. But since the BookCopy model defines no additional fields the instances are never saved.
Adding a field to BookCopy and filling that in each time allows BookCopies to be created as normal, but I don't require any additional fields right now.
The image below demonstrates the issue I'm facing, new rows can be added, but when save is clicked, no BookCopies are created
Is there a way to have the admin save the instances regardless?
I have a Profiles app that has a model called profile, i use that model to extend the django built in user model without subclassing it.
models.py
class BaseProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner',primary_key=True)
supervisor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='supervisor', null=True, blank=True)
#python_2_unicode_compatible
class Profile(BaseProfile):
def __str__(self):
return "{}'s profile". format(self.user)
admin.py
class UserProfileInline(admin.StackedInline):
model = Profile
class NewUserAdmin(NamedUserAdmin):
inlines = [UserProfileInline ]
admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)
admin
the error is
<class 'profiles.admin.UserProfileInline'>: (admin.E202) 'profiles.Profile' has more than one ForeignKey to 'authtools.User'.
obviously i want to select a user to be a supervisor to another user. I think the relationship in the model is OK, the one that's complaining is admins.py file. Any idea ?
You need to use multiple inline admin.
When you have a model with multiple ForeignKeys to the same parent model, you'll need specify the fk_name attribute in your inline admin:
class UserProfileInline(admin.StackedInline):
model = Profile
fk_name = "user"
class SupervisorProfileInline(admin.StackedInline):
model = Profile
fk_name = "supervisor"
class NewUserAdmin(NamedUserAdmin):
inlines = [UserProfileInline, SupervisorProfileInline]
Django has some documentation on dealing with this: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#working-with-a-model-with-two-or-more-foreign-keys-to-the-same-parent-model
Here is an example that I have just tested to be working
class Task(models.Model):
owner = models.ForeignKey(User, related_name='task_owner')
assignee = models.ForeignKey(User, related_name='task_assigned_to')
In admin.py
class TaskInLine(admin.TabularInLine):
model = User
#admin.register(Task)
class MyModelAdmin(admin.ModelAdmin):
list_display = ['owner', 'assignee']
inlines = [TaskInLine]