Django admin site adding "city object" instead of "City" - python

I'm trying to create a basic weather forecast site on Django and this error arises. I successfully made a "Cities" section but when adding any city name, "City Object 1" is added. This then creates errors when reading JSON from the API key.
from django.db import models
class City(models.Model):
name = models.CharField(max_length=25)
def _str_(self): #show the actual city name on the dashboard
return self.name
class Meta: #show the plural of city as cities instead of citys
verbose_name_plural = 'cities'
admin.py
from django.contrib import admin
from .models import City
admin.site.register(City)

two undersccore
def __str__(self):
https://docs.djangoproject.com/en/3.0/ref/models/instances/#other-model-instance-methods

Related

How to register inherited sub class in admin.py file in django?

Project Name : fusion
App Name : admin_lte
Python 3.7
Django 2
MySql
Question is "I want to register sub model in django admin-panel",when i write code for model registration in admin.py file that time occurred below error.
django.core.exceptions.ImproperlyConfigured: The model Device is abstract, so it cannot be registered with admin.
NOTE : I used multiple separated model file.
device.py (Model File)
from django.db import models
class Device(models.Model):
device_type = models.CharField(max_length=100,blank=False)
price = models.IntegerField()
status = models.CharField(max_length=10, default="SOLD")
issues = models.CharField(max_length=100, default="No Issues")
class Meta:
abstract = True
def __str__(self):
return 'Device_type:{0} Price:{1}'.format(self.device_type,self.price)
#Inheritance Concept
class Laptop(Device):
pass
class Meta:
db_table = "laptop"
class Desktop(Device):
pass
class Meta:
db_table = "Desktop"
class Mobile(Device):
pass
class Meta:
db_table = "Mobile"
__init__.py File
from django_adminlte.models.employee import Employee
from django_adminlte.models.device import Device
admin.py
from django.contrib import admin
from.models import Employee
from.models import Device
admin.site.register (Employee)
admin.site.register (Device)
I want to show sub model (Desktop,Laptop,Mobile) in admin panel so admin can add some data from admin panel.
Project Structure Image :
I can see in your code Device is a abstract model. So, we should not register it because abstract models do not have associated tables in databases.
from django.contrib import admin
from .models import Employee, Laptop, Mobile, Desktop
admin.site.register(Employee)
admin.site.register(Laptop)
admin.site.register(Mobile)
admin.site.register(Desktop)
I also got a problem when trying to generate an admin CRUD for a class inheriting from an abstract class. But the cause was different so I'll leave my case here in case it helps someone else.
In my case, the problem was that I forgot to make the abstract class inherit from django's models.Model.
Example Code:
time.py
from django.db import models
from applications.utils import UniqueNameMixin
class Month(UniqueNameMixin):
starting_date = models.DateField()
ending_date = models.DateField()
class TimeSensible(models.Model): # Here '(models.Model)' was missing.
class Meta:
abstract = True
month = models.ForeignKey(Month, models.PROTECT)
transaction.py
from django.db import models
from applications.core.models.cash_flow import Concept
from applications.core.models.financial_position import Account
from applications.core.models.time import TimeSensible
class Transaction(models.Model, TimeSensible):
concept = models.ForeignKey(Concept, models.PROTECT, blank=True, null=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
account = models.ForeignKey(Account, models.PROTECT)
detail = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return '{} - {} - {} - {}'.format(self.month, self.concept, self.amount, self.account)
The error I got:
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: The model Transaction is abstract, so it cannot be registered with admin.

django-import-export admin: how to export model name in a Many to Many relationship

Given the models:
#models.py
class Author(models.Model):
name = models.CharField(max_length=200)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ManyToManyField(Author, through = 'AuthorBook')
class AuthorBook(models.Model):
author = models.ForeignKey(Author)
book = models.ForeignKey(Book)
some_info = models.CharField(max_length=200)
and
#admin.py
from django.contrib import admin
from .models import Author, Book, AuthorBook
from import_export.admin import ExportMixin
from import_export import resources, fields
from import_export.widgets import ManyToManyWidget
class BookResource(resources.ModelResource):
author = fields.Field(widget=ManyToManyWidget(Author))
class Meta(object):
model = Book
exclude = ('id',)
def dehydrate_author(self,Author):
return Author.name
When I try to export the data on Book's Admin panel I'm getting the error:
'Book' object has no attribute 'name'
I'm stuck in this for hours, and the closest answer I could find was this, but did not solve my problem.
You're specifying that your model is Book, which has no name attribute. I'm guessing your function dehydrate_livro() is being called with a book as a parameter, which you are misleadingly calling Author (just because a variable starts with an uppercase letter doesn't make it an instance of any class). Your method is then trying to access the name attribute in this book, Author.name, but there is none.
Try:
def dehydrate_livro(self,book):
return book.author.all()
This will return a list of your book's authors.

django admin fails using TabularInline

I built a simple django application and now have a really confusing error message. I think it's because of Tabularinline, but I use it properly according to this documentation.
models.py
from django.db import models
class Person(models.Model):
company = models.CharField(max_length=120)
name = models.CharField(max_length=120)
birthday = models.DateField(null=True, blank=True)
def __unicode__(self):
return self.name
class Note(models.Model):
person = models.ForeignKey(Person)
datetime = models.DateTimeField()
text = models.TextField()
admin.py
from addressbook.models import Person, Note
from django.contrib import admin
class NoteInline(admin.TabularInline):
model = Note
class PersonAdmin(admin.ModelAdmin):
model = Person
inlines = [NoteInline, ]
admin.site.register(Note, NoteInline)
admin.site.register(Person, PersonAdmin)
But I always get this error message:
<class 'addressbook.admin.NoteInline'>: (admin.E202) 'addressbook.Note' has no ForeignKey to 'addressbook.Note'.
Which I would understand but why should have Note a reference to itself If I am using it from Person?
I don't think you need to separately register the NoteInline admin template. Just register the PersonAdmin template and that should include your NoteInline

With Django, representing foreignkeys in Admin

Building a generic app to practice learning with Django.
Two classes in Models:
class HouseInformation(models.Model):
house_name = models.CharField(max_length=200)
house_type = models.CharField(max_length=40)
address = models.CharField(max_length=200)
latitude = models.CharField(max_length=200)
longitude = models.CharField(max_length=200)
def __str__(self):
return self.house_name
class HouseReport(models.Model):
the_house = models.ForeignKey(HouseInformation)
visit_date = models.DateField()
In Admin view, I'd like to see a list of the houses with the dates they were visited. The admin.py so far is like so, and its not working:
from django.contrib import admin
from housing.models import HouseInformation
from housing.models import HouseReport
class HouseReport(admin.ModelAdmin)
list_display = ('the_house')
admin.site.register(HouseInformation, HouseReport)
I hope the one-to-many is represented correctly (one house can have many visits).
The problem is the missing ::
class HouseReport(admin.ModelAdmin):
^
Speaking about the task you've initially wanted to solve, check the InlineModelAdmin classes:
The admin interface has the ability to edit models on the same page as
a parent model. These are called inlines.
Add this to the admin.py:
from django.contrib import admin
from housing.models import HouseInformation, HouseReport
class HouseReportInline(admin.TabularInline):
model = HouseReport
class HouseAdmin(admin.ModelAdmin):
inlines = [
HouseReportInline,
]
admin.site.register(HouseInformation, HouseAdmin)
And you will see the House information and all of the HouseReports associated with a House on the House admin page.
You forgot the : after the class definition in line 5
class HouseReport(admin.ModelAdmin):
And you have to write
...
list_display = ('the_house',)
...
notice the trailing comma? It tells python, that it should create a tuple

Django populate choice from ForeignKey

In the following code I am trying to have the Owner form with a drop-down menu that has car brands from the Car model as choices. I do get the drop-down menu but the elements listed as "Car object" each, instead of the brands. How do I get the brands from the Car model into the menu? Thanks.
models.py
from django.db import models
class Car(models.Model):
brand = models.CharField(max_length=20)
class Owner(models.Model):
name = models.CharField(max_length=20)
car_brand = models.ForeignKey(Car)
forms.py
from django.forms import ModelForm, ModelChoiceField
from app.models import Owner
class OwnerForm(ModelForm):
car_brand = ModelChoiceField(queryset=Car.objects.all())
class Meta():
model = Owner
Add a __unicode__ function to your model definition.
class Car(models.Model):
brand = models.CharField(max_length=20)
def __unicode__(self):
return u'%s' % (self.brand)
This way you can control what to be displayed
Thanks so much for sharing this, it helped me! In Django 1.8, try:
brand = models.ForeignKey(Car)
Dont put car_ in front of the foreign key

Categories

Resources