I have defined a couple of models in a new Django 1.8 app.
When I visit the Django Admin, the list view (the table where you see one row per each objects instance) works fine.
My surprise is that when I click on any NSGateway item and enter the edit or create page, there are no fields; just the Save buttons.
How can this be possible? All the NSGateway fields are shown as columns in the list view. But the edit view shows no fields!
These are the models:
from django.db import models
class Enterprise(models.Model):
enterprise_id = models.CharField(max_length=40, primary_key=True)
description = models.CharField(max_length=500, null=True)
name = models.CharField(max_length=500)
creationDate = models.DateTimeField()
lastUpdatedDate = models.DateTimeField()
def __unicode__(self):
return self.description
class NSGateway(models.Model):
nsgateway_id = models.CharField(max_length=40, primary_key=True)
creationDate = models.DateTimeField()
description = models.CharField(max_length=500, null=True)
lastUpdatedDate = models.DateTimeField()
personality = models.CharField(max_length=50)
name = models.CharField(max_length=500)
# Each NSG belongs to 1 and only 1 Enterprise.
# Thus, when we delete de Enterprise, we delete its NSG
enterprise = models.ForeignKey(Enterprise, on_delete=models.CASCADE)
def __unicode__(self):
return self.description
This is how the corresponding admin.py:
from django.contrib import admin
from flexwan_import.models import Enterprise, NSGateway
class EnterpriseAdmin(admin.ModelAdmin):
list_display = ('enterprise_id', 'name', 'description', 'creationDate',
'lastUpdatedDate')
search_fields = ['enterprise_id', 'description']
class NSGatewayAdmin(admin.ModelAdmin):
list_display = ('nsgateway_id', 'name', 'description', 'creationDate',
'lastUpdatedDate')
search_fields = ['nsgateway_id', 'description']
admin.site.register(Enterprise, EnterpriseAdmin)
admin.site.register(NSGateway, NSGatewayAdmin)
Related
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.
The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.
As shown in the below image:
models.py
class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
address = models.CharField(max_length=50, default='', blank=True)
phone = models.CharField(max_length=50, default='', blank=True)
price = models.IntegerField()
date = models.DateField(default=datetime.datetime.today)
status = models.BooleanField(default=False)
admin.py
class AdminOrders(admin.ModelAdmin):
list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']
You need to define the __str__ method in the models Product and Customer
Example:
def __str__(self):
return self.name
If you call a function it have to return string if you want to display as word.
I know 2 ways to do this
First its repr Method
def __repr__(self):
return self.(Model You wanna Display)
or str Witch is akcually same
def __str__(self):
return self.(Model You wanna Display)
Have tried double underscore in order to access the foreign item field (product__name) and (customer__name).
class Product(models.Model):
name= models.CharField(max_length=50, default='', blank=True)
....
class Customer(models.Model):
name= models.CharField(max_length=50, default='', blank=True)
....
class AdminOrders(admin.ModelAdmin):
list_display = ['product__name', 'customer__name', 'quantity', 'address', 'phone', 'price', 'date', 'status']
I am Developing a E-commerce Application with Django
So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.
So Here is the code for this
This is the model for getting the Categories from the user
class ProjektCat(models.Model):
id = models.AutoField(primary_key=True)
Option_Name = models.CharField(max_length=50)
Option_Number = models.IntegerField()
Number_Visits = models.IntegerField(default=0)
def __str__(self):
return f'{self.Option_Name}'
and here is the code to list those categories as a dropdown in the CharField
class Software_And_Service(models.Model):
id = models.AutoField(primary_key=True)
Product_Name = models.CharField(max_length=100, default='')
projectKats = ProjektCat.objects.all()
choice = []
for i in projectKats:
option = (i.Option_Number, i.Option_Name)
choice.append(option)
Cateogary = models.CharField(
max_length=256, choices=choice)
Price = models.IntegerField(default=0)
Description = models.TextField(default='', max_length=5000)
pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
image = models.URLField(default='')
linkToDownload = models.URLField(default='')
def __str__(self):
return f'Projekt : {self.Product_Name}'
But it's Showing me an Error that there is no such table in app_name.projektcat
Is there is any solution for this??
It's not how you do this. First correctly assign the projectKats field i.e
# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)
You need to do this logic in django forms rather than django models.
So this is how you can do it.
forms.py
from django import forms
from .models import ProjektCat, Software_And_Service
def get_category_choices():
return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]
class SoftwareAndServiceForm(forms.ModelForm):
projectKats = forms.ChoiceField(choices=get_category_choices)
class Meta:
model = Software_And_Service
fields = [
'projectKats',
# whatever fields you want
]
I have a Django app with the following models.py
from django.db import models
class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
delivered = models.BooleanField(default=False)
class OrderItem(models.Model):
order = models.ForeignKey(Order,
related_name='items',
on_delete=models.CASCADE)
product = models.ForeignKey(Product,
related_name='order_items',
on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
And in my admin.py, I have this
from django.contrib import admin
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['id', 'first_name', 'last_name', 'email',
'paid', 'delivered']
list_filter = ['paid', 'delivered']
This only shows the Order table.
I would like to join the Order with the OrderItem table and display it in the Django admin. I am not sure this is relevant but for one Order, there could be many OrderItem(s).
As far as I know, you can't show OrderItems in OrderAdmin directly. But you can show Order in OrderItemAdmin, or use InLineModelAdmin to show OrderItems in Order Detail page. Like this:
class OrderItemInline(admin.TabularInline):
model = OrderItem
class OrderAdmin(admin.ModelAdmin):
inlines = [
OrderItemInline,
]
If you still want to display OrderItems (or parts of order item) in admin page, then you can add a method in list_display field, and use that method to fetch OrderItems. Like this:
class OrderAdmin(admin.ModelAdmin):
list_display = (..., 'get_order_items')
def get_order_items(self, obj):
return return ", ".join(obj.items.values_list("pk", flat=True))
get_order_items.short_description = 'Order Items'
I am trying to give posts category choices , everything works fine but if I add posts from admin panel I get error something like this
Select a valid choice. SSC is not one of the available choices.
this is my Posts/models.py
from django.db import models
from django.core.validators import FileExtensionValidator
# Create your models here.
CATEGORIES = (
('SSC', 'SSCQUESTION'),
('CAT', 'CATQUESTION'),
)
class Category(models.Model):
title = models.CharField(max_length = 120, verbose_name="Title" )
updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at")
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Posts(models.Model):
title = models.CharField(max_length=60)
file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])])
content = models.TextField()
category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE,choices = CATEGORIES)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
# class Meta:
# verbose_name = "Post"
# verbose_name_plural = "Posts"
# ordering = ['-created_at']
def __unicode__(self):
return self.title
def __str__(self):
return self.title
In admin panel this gives error like this
remove choices
category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE)
Go to the Category table in the admin panel and create some categories there.. Those categories will now be populated in the dropdown in the Post creation page
Here are my two models:
class Provider(models.Model):
name = models.CharField(max_length=75, null=True, blank=True)
code = models.CharField(max_length=15)
provider_parent = models.ForeignKey('self', null=True, blank=True)
accounts = models.ManyToManyField('Account', blank=True)
data_types = models.ManyToManyField('DataType', blank=True,
through='ProviderDataType')
class Account(models.Model):
name = models.CharField(max_length=75, unique=True)
prefixes = models.ManyToManyField('AccountPrefix', blank=True)
Here is my admin.py
class ProviderAdmin(admin.ModelAdmin):
list_display = ('code', '__unicode__')
class AccountAdmin(admin.ModelAdmin):
list_display = ('__unicode__')
admin.site.register(Provider, ProviderAdmin)
admin.site.register(Account, AccountAdmin)
I was wondering if it is possible to have a selection of the parent provider when I try to add or update my account model and upon saving it. The Parent model has already set the account on its manytomany field
If I understood your question correctly you can use TubularInline. Like this:
class ProviderInline(admin.TabularInline):
model = Provider.accounts.through
extra = 1
class AccountAdmin(admin.ModelAdmin):
inlines = [ProviderInline,]
...