I imported a project from Django builder, managed to install the dependencies, and start the admin, but I have an issue.
All of the fields in admin are not editable! None of them.
Here's a screenshot of the issue:
Here's the relevant files:
Admin.py
from django.contrib import admin
from django import forms
from .models import Tours, Locations, Photos, PlaceLocations, Information
class ToursAdminForm(forms.ModelForm):
class Meta:
model = Tours
fields = '__all__'
class ToursAdmin(admin.ModelAdmin):
form = ToursAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration']
admin.site.register(Tours, ToursAdmin)
class LocationsAdminForm(forms.ModelForm):
class Meta:
model = Locations
fields = '__all__'
class LocationsAdmin(admin.ModelAdmin):
form = LocationsAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description']
admin.site.register(Locations, LocationsAdmin)
class PhotosAdminForm(forms.ModelForm):
class Meta:
model = Photos
fields = '__all__'
class PhotosAdmin(admin.ModelAdmin):
form = PhotosAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo']
admin.site.register(Photos, PhotosAdmin)
class PlaceLocationsAdminForm(forms.ModelForm):
class Meta:
model = PlaceLocations
fields = '__all__'
class PlaceLocationsAdmin(admin.ModelAdmin):
form = PlaceLocationsAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Latitude', 'Longitude', 'Radius']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Latitude', 'Longitude', 'Radius']
admin.site.register(PlaceLocations, PlaceLocationsAdmin)
class InformationAdminForm(forms.ModelForm):
class Meta:
model = Information
fields = '__all__'
class InformationAdmin(admin.ModelAdmin):
form = InformationAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo', 'Description']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo', 'Description']
admin.site.register(Information, InformationAdmin)
models.py
from django.core.urlresolvers import reverse
from django_extensions.db.fields import AutoSlugField
from django.db.models import *
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model
from django.contrib.auth import models as auth_models
from django.db import models as models
from django_extensions.db import fields as extension_fields
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
class Tours(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Tags = models.TextField(max_length=100)
Photo = models.ImageField(upload_to="/upload/images/")
Description = models.TextField(max_length=2000)
Duration = models.IntegerField()
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_tours_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_tours_update', args=(self.slug,))
class Locations(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
MainLocLat = models.TextField(max_length=100)
MainLocLon = models.TextField(max_length=100)
MainLocRad = models.TextField(max_length=100)
Audio = models.FileField(upload_to="/upload/files/")
Description = models.TextField(max_length=2000)
# Relationship Fields
Photos = models.ForeignKey('app_name.Photos', )
PlaceLocations = models.ForeignKey('app_name.PlaceLocations', )
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_locations_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_locations_update', args=(self.slug,))
class Photos(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_photos_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_photos_update', args=(self.slug,))
class PlaceLocations(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Latitude = models.TextField(max_length=100)
Longitude = models.TextField(max_length=100)
Radius = models.IntegerField()
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_placelocations_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_placelocations_update', args=(self.slug,))
class Information(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
Description = models.TextField(max_length=2000)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_information_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_information_update', args=(self.slug,))
You should better remove the readonly_fields attribute on each ModelAdmin class. Doing that, the fields, in the admin panel, will not be read-only!
Related
Models.py
Categories:
class Category_product(models.Model):
category_name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.category_name
Products:
class Warehouse(models.Model):
category_product = models.ForeignKey(
Category_product, on_delete=models.CASCADE)
product_name = models.CharField(max_length=200, unique=True)
condition = models.BooleanField(default=False)
amount = models.IntegerField()
barcode = models.BigIntegerField()
f_price = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product_name
urls.py
path('products-list/', views.WarehouseList.as_view()),
Views.py
class WarehouseList(generics.ListCreateAPIView):
queryset = Warehouse.objects.all()
serializer_class = WarehouseSerializer
Serializers.py
# SERIALIZER OF CATEGORY PRODUCTS
class Category_productSerializer(serializers.ModelSerializer):
class Meta:
model = Category_product
fields = ['id', 'category_name']
# SERIALIZER OF WAREHOUSE
class WarehouseSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(
source='category_product.category_name')
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super(Category_productSerializer, self).get_serializer(*args, **kwargs)
class Meta:
model = Warehouse
fields = ['id', 'category_product', 'category_name', 'condition',
'product_name', 'amount', 'barcode', 'f_price', 'created_at', 'updated_at']
I want to get products by exact category
For example:
I have product category
{
"id": 1
"category_name": "Electronics"
}
If I send GET request to api/products-list/?cat=1
I want to get products which have this category
Create a get_queryset method as follow.
class WarehouseList(generics.ListCreateAPIView):
queryset = WareHouse.objects.all()
serializer_class = WarehouseSerializer
def get_queryset(self):
cat = self.request.query_params.get('cat', None)
if cat is not None:
self.queryset = self.queryset.filter(category_product__id=cat)
return self.queryset
I have data models like:
from django.db import models
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
def __str__(self):
return self.first_name + ' ' + self.last_name
class Course(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
def __str__(self):
return self.name
class CourseParticipant(models.Model):
course = models.ForeignKey(Course, related_name='courses', on_delete=None)
student = models.ForeignKey(Student, related_name='students', on_delete=None)
completed = models.BooleanField(null=True, default=False)
def __str__(self):
return self.course
I have some serializer like:
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ('name', 'end_date', 'start_date')
I need return data in json like:
{
"courses": [
{
"name": "Math",
"end_date": "2019-06-26",
"start_date": "2019-06-26",
"participant_students_count: 10
}
]
}
How I can get "participant_students_count" and return its data in json with other fields.
Thanks for help!
You can use SerializerMethodField of DRF serializer field. Also, see about how to follow Backward access of Foreign key relationship.
from rest_framework import serializers
class CourseSerializer(serializers.ModelSerializer):
participant_students_count = serializers.SerializerMethodField()
class Meta:
model = Course
fields = ('name', 'end_date', 'start_date', 'participant_students_count')
def get_participant_students_count(self, obj):
return obj.courseparticipant_set.count()
class CourseSerializer(serializers.ModelSerializer):
participant_students_count = serializers.SerializerMethodField()
def get_participant_students_count(self, obj):
return CourseParticipant.objects.filter(course=obj).count()
class Meta:
model = Course
fields = ('name', 'end_date', 'start_date', 'participant_students_count')
I registred Category admin in models.py. I added that model in Post model via ForenKey. But when i log into admin console i cannot see my Categories, I just see Category Object(1), Category Object(2) and so on.
I will provide you a print screen and a code.
http://prntscr.com/nxt25y
instead if Japanese Kitchen or any other category (im working blog for chef),
i see Category Object, the one that i highlighted on printscreen.
I think its not a big deal but i didnt worked on django for quite some time so i forgot a lot.
Can you spot a mistake?
Thanks guys
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
from ckeditor_uploader.fields import RichTextUploadingField
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(
help_text="A short label, generally used in URLs.", default='', max_length=100)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, default='New category')
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
content = RichTextUploadingField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug})
def __str__(self):
return self.title
this is admin.py
from .models import Post, Category
from django.forms import ModelForm
from django.contrib.admin import ModelAdmin
from suit_ckeditor.widgets import CKEditorWidget
class PostForm(ModelForm):
class Meta:
widgets = {
'name': CKEditorWidget(editor_options={'startupFocus': True})
}
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['title', 'slug', 'date_posted', 'author']
list_filter = ['title', 'date_posted']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
You need to override __str__ method in your models to handle what you intend to display on admin.
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name
I'm new to web development, and i'm building a blog web app in Django.
I'm having problems adding new posts through django-admin. Clicking the "add" button gives me an "Error during template rendering - 'str' object has no attribute 'utcoffset'" error message.
models.py
from django.db import models
from django.utils import timezone
import datetime
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(blank=True, null=True)
post_date = models.DateTimeField(default='date posted')
def published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.post_date <= now
published_recently.admin_order_field = 'post_date'
published_recently.boolean = True
published_recently.short_description = 'Recent post?'
def __str__(self):
return self.title
class Customer(models.Model):
username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.CharField(max_length=50)
country = models.CharField(max_length=50)
reg_date = models.DateTimeField(default='date reg')
def __str__(self):
return self.username
class Comment(models.Model):
comment_cont = models.TextField(max_length=200)
user_name = models.ForeignKey(Customer, default=0, on_delete=models.CASCADE)
comment_post = models.ForeignKey(Post, on_delete=models.CASCADE)
votes = models.BigIntegerField(default=0)
comment_date = models.DateTimeField(default='date commented')
def __str__(self):
return self.comment_cont
class Feedback(models.Model):
feedback_title = models.CharField(max_length=50)
feedback_detail = models.CharField(max_length=200)
user_name = models.ForeignKey(Customer, default=1, verbose_name='user_name', on_delete=models.SET_DEFAULT)
admin.py
from django.contrib import admin
from .models import Post, Customer, Feedback, Comment
# Register your models here.
class CommentInLine(admin.TabularInline):
model = Comment
extra = 1
fields = ['comment_cont', 'votes', 'comment_date']
class CustomerAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['firstname', 'lastname', 'username', 'email', 'country', 'reg_date']})
]
class PostAdmin(admin.ModelAdmin):
fieldsets = [
('Post', {'fields': ['title', 'content']}),
('Date information', {'fields': ['post_date'], 'classes':['collapse']}),
]
inlines = [CommentInLine]
list_display = ('title', 'content', 'post_date', 'published_recently')
list_filter = ['post_date']
search_fields = ['title']
class FeedbackAdmin(admin.ModelAdmin):
fieldsets = [
('Feedback', {'fields': ['feedback_title', 'feedback_detail', 'user_name']}),
]
list_display = ('user_name', 'feedback_title', 'feedback_detail')
# inlines = [CustomerInLine]
# list_display = ('user_name', 'feedback_title', 'feedback_detail')
class CommentAdmin(admin.ModelAdmin):
fields = ['user_name', 'comment_post', 'comment_cont', 'votes', 'comment_date']
admin.site.register(Post, PostAdmin)
admin.site.register(Feedback, FeedbackAdmin)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(Comment, CommentAdmin)
I want to be able to add posts through Django admin. Any other corrections to the code is highly welcome. I appreciate the help. Thanks.
post_date = models.DateTimeField(default='date posted')
the post_date is DateTimeField and you have provided a string as default . It should be an instance of datetime.datetime.
post_date = models.DateTimeField(default=timezone.now)
# or
post_date = models.DateTimeField(auto_now_add=True, verbose_name='Publish Time')
should fix the problem
What I want: I have the model classes named Book and Issue. In Book, there is a field named quantity that defines how many books are there. When the Admin issue a book to a student, there will be a -1 in quantity. how may I implement this. N.B: I want to implement this in Django Admin Dashboard
from django.db import models
from datetime import date, timedelta, datetime
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
depertment_name = models.CharField(max_length=30)
roll_number = models.CharField(max_length=10, primary_key=True)
semester = models.CharField(max_length=10)
def __str__(self):
return self.depertment_name.upper() + ', ' + self.roll_number + ', ' + self.first_name.upper()
class Book(models.Model):
name = models.CharField(max_length=30)
author_name = models.CharField(max_length=30)
category = models.CharField(max_length=30)
quantity = models.IntegerField()
def __str__(self):
return self.name
class Issue(models.Model):
issue_id = models.CharField(max_length=10)
roll = models.ForeignKey(User, on_delete=models.CASCADE)
book_name = models.ForeignKey(Book, on_delete=models.CASCADE)
issue_date = models.DateField(auto_now=False, auto_now_add=True)
def return_date(self):
return datetime.now()+timedelta(days=3)
def fine(self):
return_date = datetime.now() + timedelta(days=3)
if datetime.now() > return_date:
return 'Fine'
else:
return 'No Fine'
UPDATE: IMPLEMENTATION IS SOLVED. NEED TO SHOW RESULT
please take a look here
ADMIN.PY CODE
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import User, Book, Issue
admin.site.site_header = 'Library Management System'
class UserAdmin(admin.ModelAdmin):
list_display = ('roll_number', 'first_name', 'last_name', 'depertment_name')
list_filter = ('depertment_name', 'semester')
search_fields = ('roll_number', 'first_name')
class BookAdmin(admin.ModelAdmin):
list_display = ('name', 'author_name', 'remaining', 'category')
list_filter = ('category', 'author_name')
search_fields = ('name', 'author_name')
class IssueAdmin(admin.ModelAdmin):
list_display = ('issue_id', 'issue_date', 'return_date', 'fine', 'save')
list_filter = ('issue_date',)
search_fields = ('issue_id',)
admin.site.register(User, UserAdmin)
admin.site.register(Book, BookAdmin)
admin.site.register(Issue, IssueAdmin)
admin.site.unregister(Group,)
I think, overriding save() method of Issue model would solve the problem,
class Issue(models.Model):
# your code
def save(self, *args, **kwargs):
if not self.pk:
super().save(*args, **kwargs)
self.book_name.quantity -= 1
self.book_name.save()
else:
super().save(*args, **kwargs)
Update-1
Inorder to get see the quantity of books, use book_name__quantity in list_display of IssueAdmin.
class IssueAdmin(admin.ModelAdmin):
list_display = ('issue_id', 'issue_date', 'return_date', 'fine', 'book_name__quantity')
list_filter = ('issue_date',)
search_fields = ('issue_id',)