I got the these two errors below:
<class 'blog.admin.CommentAdmin'>: (admin.E108) The value of
'list_display[4]' refers to 'active', which is not a callable, an
attribute of 'CommentAdmin', or an attribute or method on
'blog.Comment'.
<class 'blog.admin.CommentAdmin'>: (admin.E116) The value of
'list_filter[0]' refers to 'active', which does not refer to a Field.
This is my models.py code:
from django.contrib.auth.models import User
# Create your models here.
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updatedOn = models.DateTimeField(auto_now= True)
content = models.TextField()
createdOn = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-createdOn']
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
createdOn = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=False)
class Meta:
ordering = ['createdOn']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
This is my admin.py code:
from django.contrib import admin
from .models import Post, Comment
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status','createdOn')
list_filter = ("status", 'createdOn')
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'body', 'post', 'createdOn', 'active')
list_filter = ('active', 'createdOn')
search_fields = ('name', 'email', 'body')
actions = ['approveComments']
def approveComments(self, request, queryset):
queryset.update(active=True)
admin.site.register(Post, PostAdmin)
This is my forms.py code:
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
Any help is greatly appreciated.
The message is clear 'active' is not a field
class Comment(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
createdOn = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=False)
your fields are: post, name, email, createdOn, status
Therefore create a field named active or suppress active in list_display &
list_filter
status = models.IntegerField(choices=STATUS, default=0)
should be:
active = models.IntegerField(choices=STATUS, default=0)
I got the same error below:
ERRORS: <class 'store.admin.PersonAdmin'>: (admin.E116) The value of
'list_filter[0]' refers to 'PersonAgeFilter', which does not refer to
a Field.
When assigning the custom filter PersonAgeFilter to list_filter() with parentheses as shown below:
# "store/admin.py"
from django.contrib import admin
from .models import Person
class PersonAgeFilter(admin.SimpleListFilter):
# ...
#admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
list_filter = ("PersonAgeFilter",)
# ↑ Parentheses ↑
So, I removed the parentheses from "PersonAgeFilter" as shown below then the error was solved.
# "store/admin.py"
from django.contrib import admin
from .models import Person
class PersonAgeFilter(admin.SimpleListFilter):
# ...
#admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
list_filter = (PersonAgeFilter,)
# Without parentheses
Related
I've made a nested serializers which has slugs in both models. Now I learn that in order to be able to do the update on (unique=True) I need to turn off the validator. But somehow I can't seem to turn it off and it'S still throwing the same error. Any way I should be approaching on this problem?
serializers.py
from rest_framework import serializers
from .models import Question, Answer
class AnswerSerializer(serializers.ModelSerializer):
"""Serialize Answer model"""
class Meta:
model = Answer
fields = ('title', 'body', 'slug', 'author', 'question')
# https://stackoverflow.com/questions/57249850/overwriting-nested-serializers-create-method-throws-typeerror-create-got-mul
read_only_fields = ('question',)
lookup_field = 'slug'
# https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework
class QuestionSerializer(serializers.ModelSerializer):
"""Serialize Question model"""
#This answer variable and the fields 'answer' you refer to has to be the SAME but
#These can change exp: 'aaa'
answer = AnswerSerializer(read_only=False, source='answers', many=True,)
class Meta:
model = Question
fields = ('title', 'body', 'slug', 'author', 'category', 'answer',)
lookup_field = 'slug'
def create(self, validated_data):
answers_data = validated_data.pop('answers')
question = Question.objects.create(**validated_data)
for answer_data in answers_data:
#The above stackoverflow link at the answer serializers is realted to this
Answer.objects.create(question=question, **answer_data)
return question
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.body = validated_data.get('body', instance.body)
instance.slug = validated_data.get('slug', instance.slug)
instance.author = validated_data.get('author', instance.author)
instance.category = validated_data.get('category', instance.category)
instance.save()
# https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/
answers_data = validated_data.pop('answers')
aas = (instance.answers).all()
print("######")
print(aas)
print("######")
aas2 = list(aas)
for answer_data in answers_data:
aas3 = aas2.pop(0)
aas3.title= answer_data.get('title', aas3.title)
aas3.body= answer_data.get('body', aas3.body)
aas3.slug= answer_data.get('slug', aas3.slug)
aas3.author= answer_data.get('author', aas3.author)
aas3.question= answer_data.get('question', aas3.question)
aas3.save()
return instance
views.py
from django.shortcuts import render
from .models import Question, Answer
from django.conf import settings
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import QuestionSerializer
#from .permissions import UpdateOwnPrice
from rest_framework.permissions import IsAdminUser
class QuestionViewSet(viewsets.ModelViewSet):
"""CRUD """
serializer_class = QuestionSerializer
queryset = Question.objects.all()
authentication_classes = (TokenAuthentication,)
#permission_classes = (UpdateOwnPrice,)
lookup_field = 'slug'
extra_kwargs = {'slug': {'validators': []}}
models.py
from django.db import models
from django.conf import settings
from django.db.models import Q
from django.utils import timezone
from django.urls import reverse
class Category(models.Model):
name= models.CharField(max_length=100)
def __str__(self):
return self.name
class Question(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'questions')
category= models.ForeignKey(Category, on_delete= models.CASCADE, related_name = 'questions')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
class Answer(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'answers')
question= models.ForeignKey(Question, on_delete= models.CASCADE, related_name = 'answers')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
I'm trying to define create() method in my nested serializers learning from the documentation.
When I print the validated_data.pop and it HAS DATA that I requested but its returning keyerror which doesnt make sense since it has data in it.
Error:
answers_data = validated_data.pop('answers')
KeyError: 'answers'
serializers
from rest_framework import serializers
from .models import Question, Answer
class AnswerSerializer(serializers.ModelSerializer):
"""Serialize Answer model"""
class Meta:
model = Answer
fields = ('title', 'body', 'slug', 'author', 'question')
lookup_field = 'slug'
# https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework
class QuestionSerializer(serializers.ModelSerializer):
"""Serialize Question model"""
#This answer variable and the fields 'answer' you refer to has to be the SAME but
#These can change exp: 'aaa'
answer = AnswerSerializer(read_only=False, source='answers', many=True,)
print("######")
print(answer)
print("######")
print(type(answer))
class Meta:
model = Question
fields = ('title', 'slug', 'author', 'category', 'answer',)
lookup_field = 'slug'
def create(self, validated_data):
print("######")
print("######")
print(validated_data.pop('answers'))
print("######")
print("######")
answers_data = validated_data.pop('answers')
question = Question.objects.create(**validated_data)
for answer_data in answers_data:
Answer.objects.create(question=question, **answer_data)
return question
views.py
from django.shortcuts import render
from .models import Question, Answer
from django.conf import settings
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import QuestionSerializer
#from .permissions import UpdateOwnPrice
from rest_framework.permissions import IsAdminUser
class QuestionViewSet(viewsets.ModelViewSet):
"""CRUD """
serializer_class = QuestionSerializer
queryset = Question.objects.all()
authentication_classes = (TokenAuthentication,)
#permission_classes = (UpdateOwnPrice,)
lookup_field = 'slug'
modesl.py
from django.db import models
from django.conf import settings
from django.db.models import Q
from django.utils import timezone
from django.urls import reverse
class Category(models.Model):
name= models.CharField(max_length=100)
def __str__(self):
return self.name
class Question(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'questions')
category= models.ForeignKey(Category, on_delete= models.CASCADE, related_name = 'questions')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
class Answer(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'answers')
question= models.ForeignKey(Question, on_delete= models.CASCADE, related_name = 'answers')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
At the moment I'm working on an e-commerce application.
It contains a sub-app called "blog".
The idea is that the superuser creates an account for the *Trainer.
And yeah, I already created a new AbstractUser
Trainer logins into his account and creates Post
I logged in here using my Trainer`s credentials
After I want the superuser to see WHO created post, but DjangoAdmin displays me admin`s email
How could I display the email of the 'creator' of the post in Django admin?
Code:
#models.py
class UserTrainer(AbstractUser):
email = models.EmailField(verbose_name='email', max_length=100, unique=True)
age = models.PositiveIntegerField(null=True)
info = RichTextField(blank=True, null=True)
image = models.ImageField(upload_to='media/stuff_images')
inst = models.URLField(blank=True)
REQUIRED_FIELDS = ['email', ]
def __str__(self):
return self.email
def get_email(self):
return self.object.email
class Post(models.Model):
DEFAULT_TRAINER_ID = 1
article = models.CharField(max_length=50, default='Article text')
slug = models.SlugField(max_length=30)
keywords = models.CharField(max_length=100)
text = RichTextField(blank=True, null=True)
trainer = models.ForeignKey(UserTrainer, on_delete=models.CASCADE, null=False, default=1)
def __str__(self):
return self.article
class Meta:
verbose_name = 'Post'
verbose_name_plural = 'Posts'
#admin.py
class CustomUserAdmin(UserAdmin):
model = UserTrainer
add_form = CustomUserCreationForm
fieldsets = (
*UserAdmin.fieldsets,
(
'TrainerInfo',
{
'fields': (
'age', 'info', 'image', 'inst',
)
}
)
)
admin.site.register(UserTrainer, CustomUserAdmin)
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('article', 'slug','trainer')
list_display_links = ('article',)
fields = ('article', 'slug', 'keywords', 'text',)
readonly_fields = ('trainer',)
The problem is that you are are not specifying user when you save your post, so you should override your save method in admin.py, try this (OFFICIAL DOCS):
admin.site.register(UserTrainer, CustomUserAdmin)
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('article', 'slug','trainer')
list_display_links = ('article',)
fields = ('article', 'slug', 'keywords', 'text',)
readonly_fields = ('trainer',)
def save_model(self, request, obj, form, change):
obj.trainer = request.user
super().save_model(request, obj, form, change)
I am new to Django and I am trying to learn by practicing with some project but I am stuck with this problem,
NOT NULL constraint failed: shop_product.user_id
models.py
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created')
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
Here is my views.py but am not sure if there is problem with my views and I think the problem will have to be with my models....
views.py
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ("category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductUpdate(UpdateView):
model = Product
fields = ('name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
Please let me know what could be done.
Either Add User into list:
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price','stock','available', 'negiotiable', 'user']
OR make sure Field must be null=true and blank=True.
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null=True, blank=True)
Add a form for your product,
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = "__all__"
Also, your user field must be null=True and blank=True.
Then in your create view,
class ProductCreate(CreateView):
model = Product
form_class = ProductForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(ProductCreate, self).form_valid(form)
Now, whenever a product is created, the user who created would be added as the user of the product.
I'm pretty new at Django and am stuck trying to implement Django import-export. My three pertinent model are Officer, Incident, and Details. Officer and Incident are in a M2M relationship through Details. I have gotten all of the functionality to work besides importing details. When I try to import via the import button, I get "NOT NULL constraint failed: police_archive_details.incident_id" for each row in the .xls or .csv file I'm importing.
Here's my (current) admin.py
from django.contrib import admin
from import_export import resources, widgets, fields
from import_export.admin import ImportExportModelAdmin, ImportExportActionModelAdmin
from forms import AdminTextForm, OfficerTextForm
from .models import Officer, Incident, Details, SiteText
class FullNameForeignKeyWidget(widgets.ForeignKeyWidget):
def get_queryset(self, value, row):
return self.model.objects.filter(
first_name__iexact=row["first_name"],
last_name__iexact=row["last_name"]
)
class DetailsInlineAdmin (admin.TabularInline):
model = Details
extra = 5
class OfficerResource(resources.ModelResource):
class Meta:
model = Officer
class OfficerAdmin(ImportExportModelAdmin):
list_display = ('first_name', 'last_name', 'badge', 'department')
search_fields = ['first_name', 'last_name']
inlines = [DetailsInlineAdmin]
resource_class = OfficerResource
form=OfficerTextForm
class Media:
js = ('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js','/static/admin/js/admin/popup.js')
class IncidentResource(resources.ModelResource):
officer = fields.Field(
column_name='officer',
attribute='officer',
widget=widgets.ForeignKeyWidget(Officer, 'badge'))
class Meta:
fields = ('officer',)
model = Incident
class IncidentAdmin(ImportExportModelAdmin):
list_display = ('office','case_number')
search_fields = ['case_number']
inlines = [DetailsInlineAdmin]
resource_class = IncidentResource
class DetailsResource(resources.ModelResource):
officer = fields.Field(
column_name='officer',
attribute='officer',
widget=FullNameForeignKeyWidget(Officer))
incident = fields.Field(
column_name='incident',
attribute='incident',
widget=widgets.ForeignKeyWidget(Incident, 'case_number'))
class Meta:
fields = ('id','incident','officer__last_name','officer__first_name','allegation', 'finding', 'action')
model = Details
class DetailsAdmin(ImportExportModelAdmin):
list_display=('incident','officer', 'allegation', 'finding', 'action')
search_fields = ['officer__last_name', 'incident__case_number']
resource_class = DetailsResource
class SiteTextAdmin(admin.ModelAdmin):
form=AdminTextForm
admin.site.register(Officer, OfficerAdmin)
admin.site.register(Incident, IncidentAdmin)
admin.site.register(Details, DetailsAdmin)
admin.site.register(SiteText, SiteTextAdmin)
And here's models.py
from __future__ import unicode_literals
from django.db import models
from tinymce import models as tinymce_models
class Officer(models.Model):
first_name = models.CharField(max_length=80, blank=True, null=True)
last_name = models.CharField(max_length=80, blank=True, null=True)
badge = models.IntegerField(blank=True, null=True)
department = models.CharField(max_length=50, blank=True, null=True)
model_pic = models.ImageField(upload_to = "police_archive/officer_photos", default= 'noimage', blank=True, null=True)
description = tinymce_models.HTMLField(blank=True, null=True)
def __str__(self):
return self.last_name + ', ' + self.first_name
class Meta():
ordering = ['last_name']
class Incident(models.Model):
officer = models.ManyToManyField(Officer, through='Details')
case_number = models.CharField(max_length=50, blank=True)
OFFICE_CHOICES = (
('CRA', 'Civilian Review Authority'),
('IA', 'Internal Affairs'),
('OPCR', 'Office of Police Conduct Review'),
)
office = models.CharField(max_length=10,
choices=OFFICE_CHOICES,
)
def __str__(self):
return self.case_number
class Meta():
ordering = ['-case_number']
class Details(models.Model):
officer = models.ForeignKey(Officer, on_delete=models.CASCADE, blank=True)
incident = models.ForeignKey(Incident, on_delete=models.CASCADE, blank=True)
allegation = models.CharField(max_length=50, blank=True)
finding = models.CharField(max_length=50, blank=True)
action = models.CharField(max_length=50, blank=True)
def __str__(self):
return self.officer.first_name + ' '+ self.officer.last_name+ ', ' + self.incident.case_number
class Meta():
verbose_name_plural = "details"
ordering = ['incident__case_number']
class SiteText(models.Model):
content1 = tinymce_models.HTMLField()
content2 = models.TextField(max_length=500, blank=True)
OK, I spent all day debugging yesterday and got everything working properly. Here's my admin.py now, models.py is unchanged. I forget exactly which change solved the original error I posted about.
from django.contrib import admin
from import_export import resources, widgets, fields
from import_export.admin import ImportExportModelAdmin, ImportExportActionModelAdmin
from forms import AdminTextForm, OfficerTextForm
from .models import Officer, Incident, Details, SiteText
class DetailsInlineAdmin (admin.TabularInline):
model = Details
extra = 5
class OfficerResource(resources.ModelResource):
class Meta:
model = Officer
class OfficerAdmin(ImportExportModelAdmin):
list_display = ('first_name', 'last_name', 'badge', 'department')
search_fields = ['first_name', 'last_name']
inlines = [DetailsInlineAdmin]
resource_class = OfficerResource
form=OfficerTextForm
class Media:
js = ('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js','/static/admin/js/admin/popup.js')
class IncidentResource(resources.ModelResource):
class Meta:
fields = ('officer','case_number', 'office')
model = Incident
import_id_fields = ['case_number']
class IncidentAdmin(ImportExportModelAdmin):
list_display = ('office','case_number')
search_fields = ['case_number']
inlines = [DetailsInlineAdmin]
resource_class = IncidentResource
class DetailsResource(resources.ModelResource):
class BadgeForeignKeyWidget(widgets.ForeignKeyWidget):
def get_queryset(self, value, row):
return self.model.objects.filter(
badge__iexact=row["badge"]
)
officer = fields.Field(
column_name='officer',
attribute='officer',
widget=BadgeForeignKeyWidget(Officer, 'last_name'))
incident = fields.Field(
column_name='incident',
attribute='incident',
widget=widgets.ForeignKeyWidget(Incident, 'case_number'))
class Meta:
fields = ('id','officer','incident', 'allegation', 'finding', 'action')
model = Details
class DetailsAdmin(ImportExportModelAdmin):
list_display=('incident','officer', 'allegation', 'finding', 'action')
search_fields = ['officer__last_name', 'incident__case_number']
resource_class = DetailsResource
class SiteTextAdmin(admin.ModelAdmin):
form=AdminTextForm
admin.site.register(Officer, OfficerAdmin)
admin.site.register(Incident, IncidentAdmin)
admin.site.register(Details, DetailsAdmin)
admin.site.register(SiteText, SiteTextAdmin)
Another note is that you need to put an 'id' column in your spreadsheet. I was able to leave mine blank and then Django would generate an id to use as a primary key.