I have problem about the abstract model in chapter "Adding Easy Admin Emails, Helpers, Sitemaps, and More" (the hello web app intermediate book)
here is my models.py code:
from django.contrib.auth.models import User
from django.db import models
class Timestamp(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Thing(Timestamp):
name = models.CharField(max_length=225)
class Thing(models.Model):
name = models.CharField(max_length=225)
description = models.TextField()
slug = models.SlugField(unique=True)
user = models.OneToOneField(User, blank=True, null=True)
def get_absolute_url(self):
return "/things/%s/" % self.slug
class Social(models.Model):
SOCIAL_TYPES = (
('twitter','Twitter'),
('facebook','Facebook'),
('pinterest','Pinterest'),
('instagram','Instagram'),
)
network = models.CharField(max_length=255, choices=SOCIAL_TYPES)
username = models.CharField(max_length=255)
thing = models.ForeignKey(Thing,related_name="social_accounts")
class Meta:
verbose_name_plural = "Social media links"
when I run
$python manage.py makemigrations
$python manage.py migrate
the error message shows:
/helloApp/venv/lib/python2.7/site-packages/django/db/models/base.py:309: RuntimeWarning: Model 'collection.thing' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
No changes detected
that does not show like in the book :
You are trying to add a non-nullable field 'added' to thing without a defaul,,,,,,,
any answer would very greatful thank you!
Related
I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address...
So I modified admin.py:
from django.contrib import admin
from .models import Todo, Account
from django.contrib.auth.models import User
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class TodoAdmin(admin.ModelAdmin):
readonly_fields = ('created',)
inlines = (AccountInline, )
admin.site.unregister(User)
admin.site.register(Todo, TodoAdmin)
But got back:
<class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'.
So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE):
from django.db import models
from django.contrib.auth.models import User
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.CharField(max_length=100)
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=50)
company = models.CharField(max_length=5)
def __str__(self):
return self.user.username
class Todo(models.Model):
title = models.CharField(max_length=100)
datetime = models.DateTimeField()
memo = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
def __str__(self):
return self.title
But I still have the error, and I don't have any Users in the admin panel anymore
You accidentally wrote unregister for Users in your admin.py file. It should be admin.site.register(User)
You misinterpretted the error: the error states that you don't have a foreign key in your Account model to Todo.
This means your inline admin code isn't correct as it's expecting the other way around.
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users.
I have made custom models as shown below.
Database is MySQL.
models.py
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
food_pref = models.CharField(max_length=10, default='veg')
class Restaurant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
restaurant_name = models.CharField(max_length=100, blank=False)
Regisrar your models inadmin.py file.
from . models import Model_Name
Then you can register your models in two ways:
I) admin.site.register(Model_Name)
II)
#admin.register(Model_Name)
Class Xyz(admin.ModelAdmin):
pass
Second method gives you more flexibility like list_display, list_filter, date_hierarchy, etc. for customising your Admin section/site.
You can look more about customising admin site at https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#module-django.contrib.admin
Have You registered them in admin.py?
from .models import ModelName
admin.site.register(ModelName)
I am new on Python and Django. While trying out an example on a book, I did what the book says and created a models file as follows
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='published')
author = models.ForeignKey(User,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices = STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
When I run the command, python manage.py makemigrations blog
Its says NameError: name 'STATUS_CHOICES' is not defined
I typed exactly as it is from the book and I am unable to run this command
try to indent your code,you must respect coding style:
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
Change
choices = STATUS_CHOICES,
to
choices = 'STATUS_CHOICES',
You are missing ''.
This is the problem of indent and spacing ,anyways after adding default in publish field and code formatting it worked.
The model.py is hosted here and DONOT edit or open in notepad like editor otherwise it will again create spacing, just import in your IDE
I am trying to build a simple social network.
Say I have two models: Status and my custom UserProfile model to implement followers/followings feature:
from django.contrib.auth.models import User
class Status(models.Model):
user = models.ForeignKey(User, related_name='statuses')
title = models.CharField(max_length=50)
status = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Status"
verbose_name_plural = "Statuses"
ordering = ('-created',)
get_latest_by = 'created'
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
followings = models.ManyToManyField(
'self', related_name='followers', symmetrical=False, blank=True)
What is the most efficient way to access newsfeed i.e. recent statuses of all of my(User) followings?
I am new to Django. Any help will be much appreciated.
Simply filter Status queryset by users that you are following. Query above will show all statuses for all users followed by user.
Status.objects.filter(user__followers=user)