I have 5 models in one of my apps
Report ReportData Customer ..etc
For some reason, ever since my last deployment, I can no longer change or create new Report or Customer objects, but everything else works? Any idea why this would be happening? The admin page just outputs nothing on the add link and the change link outputs nothing as well.
Django==1.9.1
I have tried restarting servers, running migrations, and restarting database. The development version works fine. Such a strange problem.
As you can see, there are no fields even though this object has been populated with tons of data in the database.
Here is my Report model:
class Report(models.Model):
public_uuid = models.UUIDField(max_length=256,default=util.make_uuid,unique=True)
customer = models.ForeignKey('Customer')
has_payed = models.BooleanField(default=False)
#... etc
Here is how I register items in the admin:
admin.site.register(Customer)
admin.site.register(Report)
admin.site.register(...etc)
The other 3 models I have work fine. The only difference between these two models and the other three (that work and are editable with the admin tool) is that these two models have #property and #staticmethod methods attached to them.
Just had this issue
When using auto_now_add=True or editable=False in the field definition, the admin will not show the corresponding fields unless you specify them in the readonly_fields of the admin form definition.
if in models.py
class TransmissionLog(models.Model):
dataSource = models.ForeignKey(Browser, editable=False)
dateCreated = models.DateTimeField(auto_now_add=True, editable=False)
then admin.py needs
class TransmissionAdminManager(admin.ModelAdmin):
readonly_fields = ['dataSource', 'dateCreated']
admin.site.register(TransmissionLog, TransmissionAdminManager)
Related
I have decided to implement registration option for my website, I used this tutorial (signup with confirmation part). Following this material I have created Profile module to hold some info. Everything (seems to be) working now, but the problem is that old profiles throws relatedObjectDoesNotExist error. According to these two questions (first, second) I need to make a migration to create profiles for old user accounts. I tried to follow this doc as suggested in one of the answers, but then I try to run a migration I get following error: KeyError: ('stv', 'bazinekaina')
stv is the name of my app and bazinekaina is the name of the next model after the one I need to create profiles.
How to limit migration to only the first model?
My relevant models.py code:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=254)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.get(user=instance)
instance.profile.save()
#next model, this one throws an error, despite the fact it should not be touched at all
class BazineKaina(models.Model):
#bazines kainos modelis
bazka = models.DecimalField(max_digits=5, decimal_places=2)
data = models.DateField(auto_now=False, auto_now_add=True)
def __str__(self):
return str(self.bazka)
class Meta:
verbose_name_plural = "BazinÄ— kaina"
get_latest_by = 'data'
Migration file crated after using python manage.py makemigrations --empty stv command, named 0001_initial.py:
from django.db import migrations, models
def sukurti_profilius(apps, schema_editor):
Profile = apps.get_model("stv", "Profile")
for user in Profile.objects.all():
Profile.objects.get_or_create(user=user)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
How and what I should fix to stop migrations from applying to the unrelated models (and throwing error)?
Sorry if it is basic question, but whole django is still very new to me.
If your migration is named 0001_initial then it means that you don't have a migration that actually creates the table for the profile model.
Remove that migration and run:
python manage.py makemigrations stv
python manage.py makemigrations stv --empty --name create_profiles
Then you should have a file 0002_create_profiles.py and put the logic to create profiles there.
I have an app called 'Product' with the following models.py:
class Product(models.Model):
product_id = models.CharField(max_length=50)
pub_date = models.DateTimeField(default=datetime.now)
title = models.CharField(max_length=255)
price = models.DecimalField(max_digits=8, decimal_places=2)
user = models.ForeignKey(User, on_delete=models.CASCADE)
featured = models.BooleanField(default=False)
I want to have two separate sections in Django Admin: Products and Featured Products, depending if featured = True or False.
So by default all products are listed under the Products section. But if featured = True they will be moved to Featured Products section. Can you please help me how to do that? Thanks in advance.
Three steps:
Write a proxy model for model Product.
Change the default manager to only returns featured products.
Register your proxy model in the admin like any other model.
You can read more about it here: Using Proxy Models to Customize the Django Admin
There are a couple of ways to do this. The simplest perhaps is to create a database view, and then encapsulate it using a django model. You can create a view like so in your database console:
CREATE VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];
Once you have done that, you can reference the view in django like so:
class FeaturedProduct(modes.Model):
attr1 = models.CharField()
class Meta:
managed = False
db_table = '<name of your view here>'
Make sure that managed is set to False. Here is the relevant documentation for that. You want to do that because django is not creating this model for you, but rather you are creating it yourself.
Another way to do this would be to create a custom Manager. These managers allow you to modify the objects attribute of your model, allowing you to set a queryset that you want. I think you'd want to take a look at the Manager documentation and you can take a look at defining custom querysets for your objects.
I am making a website through Django and I want to create a similar model for the Users model (default user model came with Django)
I have tried everything I have found from google django docs and I couldn't.
Can anyone help?
Or help me to make a login system for my normal model
For an instance,
I have created a normal model called accounts and there is a field in it called loggedin.
Whenever I try to login system set it to True means logged in. And if i logged out by the logout button i set it to false now lets take in consideration if i have closed the web browser Immediately i want to set it to False
Any help?
There are two common ways to deal with is extending django's AbstractUser:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# Some other fields to go along with the default fields
info = models.TextField(max_length=500, blank=True)
phone_number = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
After this, just change the default user model on your settings.py adding AUTH_USER_MODEL = my_app.models.user
I am trying to use Cookiecutter to help me to deploy a web app with Heroku and Amazon S3.
This is an app that I developed locally without Cookiecutter so I am copy-pasting the files into the new project and debug step by step.
The original app used the build-in Django User Model so I would like to switch to the Abstract User Model that comes with Cookiecutter.
I started to create a new database for this project to start from scratch.
Then I thought it would be as simple as replacing User by AUTH_USER_MODEL
models.py
from config.settings.base import AUTH_USER_MODEL
class Category(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=140,blank=True,null=True)
date_created = models.DateField(default=timezone.now)
date_updated = models.DateField(auto_now=True)
created_by = models.ForeignKey(AUTH_USER_MODEL, related_name="categories")
def __str__(self):
return self.name
I get this error when running manage.py migrate
accounts.User.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'
In settings.py
AUTH_USER_MODEL = 'users.User'
Where I am missing something ?
Your error message seems to indicate that the problem is coming from another model called accounts.User, but it's not included in the snippet you provide. The error shows a model in the accounts app but the setting AUTH_USER_MODEL points to a model in the users app. Are these 2 different models? Did you rename the users app as accounts but forgot to update the setting?
I'm working on this project and i'm extending Django's base user model in order to have emails as usernames. I've got the following project structure with two apps (client and showroom)
. project
.. client
... models
.... Client
.. showroom
... models
.... Image
Client inheritates AbstractBaseUser like this:
class Client(AbstractBaseUser):
email = models.CharField(max_length=255, unique=True)
firstname = models.CharField(max_length=50)
etc...
Image has a Foreign Key to my Client model:
class Image(models.Model):
client = models.ForeignKey(_('Client'), settings.AUTH_USER_MODEL, blank=True, null=True, limit_choices_to=Q(groups__name = 'website_user'))
etc...
And in my settings.py (which is not called settings.py, don't think it's relevant but just in case) I have got this:
INSTALLED_APPS = (
'django.contrib.auth',
etc...
'client',
'showroom',
etc...
)
AUTH_USER_MODEL = 'client.Client'
Now, when I try to run the project, syncdb, migrate or whatever else that has to do with the database, I get this error:
showroom.Image.client: (fields.E300) Field defines a relation with model 'Client', which is either not installed, or is abstract.
Of course, when I remove the foreign key to Client in my Image model, everything works fine.
I have googled this a lot and most solutions suggest that my apps are not properly installed, but they seem to be as shown in my config file. So I guess this has something to do with inheriting django's AbstractBaseUser, but i can't see why this wont work for me, as my code is very similar to the one in the official docs.
Anyway, thanks in advance for your help.
First argument of ForeignKey should be a model or a name of a model. You pass _('Client') what I think is verbose_name.
Try this:
client = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Client'), blank=True, null=True, limit_choices_to=Q(groups__name = 'website_user'))