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'm currently writing an application in django called account, now everything was working fine (as it usually happens), but I had to add more information in my models.py file, and all of the sudden, I got problems running the migrations, certainly as django enthusiast the usual approach is to delete all the migrations in the migration folder, delete the Database and finally run the usual set of commands.
Unfurtunetely this time, that trick is not solving my problem, and I'm getting the following error:
ValueError: Field 'id' expected a number but got 'company'.
That error appears when I type python manage.py migrate, the run migration runs without problems, and a migration 0001 file and a database is created, but I still get the error when running the migrate command.
models.py
from django.db import models
from django.conf import settings
from django_countries.fields import CountryField
from phone_field import PhoneField
from djmoney.models.fields import MoneyField
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
email = models.EmailField(blank=True,null=True)
role = models.TextField(blank=True)
location = models.TextField(blank=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
def __str__(self):
return self.user
class Company(models.Model):
company = models.CharField(blank=True, max_length=30)
def __str__(self):
return self.company
class Client(models.Model):
firstname = models.CharField(blank=True, max_length=30)
lastname = models.CharField(blank=True, max_length=15)
company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company")
position = models.CharField(blank=True, max_length=15)
country = CountryField(blank_label='(select country)')
email = models.EmailField(blank=True, max_length=100, default="this_is#n_example.com")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
phone = PhoneField(default="(XX)-XXX-XXX")
def __str__(self):
return f'{self.firstname}'
class Leads(models.Model):
CHOICES = (
('Illumination Studies','Illumination Studies'),
('Training','Training'),
('Survey Design','Survey Design'),
('Software License','Software License')
)
STATUS = (('Open','Open'),
('Closed','Closed'),
('Canceled', 'Canceled')
)
project_id = models.BigAutoField(primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company")
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
created_at = models.DateTimeField(auto_now_add=True)
point_of_contact = models.CharField(blank=True, max_length=30)
expected_revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
expected_licenses = models.IntegerField(blank=True)
country = CountryField(blank_label='(select country)')
status = models.CharField(max_length=10,choices=STATUS)
estimated_closing_date = models.DateField(blank=True)
services = models.CharField(max_length=20,choices=CHOICES)
def __str__(self):
return f'{self.company}'
class CallReport(models.Model):
CHOICES = (
('Video Conference','Video Conference'),
('Phone Call','Phone Call'),
('Lunch Meeting', 'Lunch Meeting'),
('Client Offices', "Client Offices")
)
company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company")
minutes_of_meeting = models.TextField(blank=True, null=True)
client_POC = models.ForeignKey(Client, on_delete=models.CASCADE, default='client')
date = models.DateField(blank=True)
ACTeQ_representative = models.ForeignKey(Profile, on_delete=models.CASCADE, default='agent')
def __str__(self):
return f'Call Report for {self.company}, on the {self.date}'
class Deal(models.Model):
project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default='id')
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
service = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='service')
closing_date = models.DateField(auto_now_add=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client')
licenses = models.ForeignKey(Leads,on_delete=models.CASCADE, related_name='licenses')
revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
comments = models.TextField(blank=True,null=True)
Traceback
Traceback (most recent call last):
tial...Traceback (most recent call last):
File "C:\Users\fcolina\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'company'
ValueError: Field 'id' expected a number but got 'company'.
Any ideas?, please refrain yourself from suggesting deleting the db, migrations files, yes of course that solves some issues in particular when a table is added, then obviously the DB has not knowledge of that, but in this case, that trick won't fix the issue
The option default='company' in Client, Leads and CallReport must be the error, make sure after remove it run the following commands:
python manange.py makemigrations
And after that run the following:
python manage.py migrate
"A ForeignKey contains the primary key of the target table. If the primary key of that table relating to the company value is an integer, then your default value must be that integer", not that string
then, Remember to delete the database, and the migrations inside the migrations folder, and Then
python manange.py makemigrations
Run the following:
python manage.py migrate
This should resolve your issue.
I'm trying to create a subscription style service on Django (using Django3)
Basically, I had it working..ish, but my stripe customer keys weren't being added in, so I fiddled around to get that sorted.
Now I'm getting this error - Membership matching query does not exist. this is whenever I'm trying to create an account, login or login to the admin of my Django project.
I can't really figure out what the issue is, as I've reverted the changes I made to get the cust-Id (any tips here would be appreciated! lol) working again, but it's still throwing it up at me.
Here's my code in my models, I can't even pinpoint where this issue is coming from if I'm honest. (I got this mostly from the JustDjango tutorial btw!)
The debug thing is saying it's to do with the free_membership variable in the post_save_usermembership_create method though.
So far I just have models.py and admin.py done to get this up & running -
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from datetime import datetime
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
MEMBERSHIP_CHOICES = (
('Regular', 'reg'),
('Premium', 'premium'),
('Free', 'free')
)
class Membership(models.Model):
slug = models.SlugField()
membership_type = models.CharField(
choices=MEMBERSHIP_CHOICES,
default='Free',
max_length=30)
price = models.IntegerField(default=15)
stripe_plan_id = models.CharField(max_length=40)
def __str__(self):
return self.membership_type
class UserMembership(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
stripe_customer_id = models.CharField(max_length=40)
membership = models.ForeignKey(
Membership, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username
def post_save_usermembership_create(sender, instance, created, *args, **kwargs):
user_membership, created = UserMembership.objects.get_or_create(
user=instance)
if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '':
new_customer_id = stripe.Customer.create(email=instance.email)
free_membership = Membership.objects.get(membership_type='Free')
user_membership.stripe_customer_id = new_customer_id['id']
user_membership.membership = free_membership
user_membership.save()
post_save.connect(post_save_usermembership_create,
sender=settings.AUTH_USER_MODEL)
class Subscription(models.Model):
user_membership = models.ForeignKey(
UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.user_membership.user.username
I have a blog project and users can create posts with similar titles, How can I prevent a user or even the admin from proceeding without getting an error that the title already exists so that I can avoid future errors in the website such as get() returned more than one Post-it returned 2!
I have tried to use class meta for unique together but still, post was saved with the same title
Here is the post model
class Post(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, null=True, max_length=120)
def __str__(self):
return self.title
class Meta:
unique_together = ('title', 'slug')
You can add unique=True
title = models.CharField(max_length=100, unique=True)
See the docs here.
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!