So I am trying to create a custom Manager that extends the default one and I am getting an error that for the life of me I cannot fix. I've read all the django docs and can't see what I've done wrong!
ERROR:
NameError at /
name 'article_finish_date' is not defined
Here is my models.py
import datetime
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class ArticleManager(models.Manager):
def get_queryset(self):
return super(ArticleManager, self).get_queryset().filter(article_finish_date==None)
class Article(models.Model):
article_name_text = models.CharField(max_length=200)
article_creation_date = models.DateTimeField('date created')
article_publish_date = models.DateTimeField('date published', null=True, blank=True)
article_finish_date = models.DateTimeField('date finished', null=True, blank=True)
def __str__(self):
return self.article_name_text
actives = ArticleManager()
I have tried filtering by all the different values of the Article model, however the same issue occurs. I have tried both migrated and makemigrations, however no progress has been made.
Many thanks in advance, ask if you need more details!
The error is in this part:
.filter(article_finish_date==None)
Python is trying to evaluate the expression article_finish_date==None, except article_finish_date hasn't been defined yet. Instead, you want to use a single =
.filter(article_finish_date=None)
Related
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
So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error.
models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = models.ForeignKey('User',User.username)
post_date = models.DateField(default=date.today,blank=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
The Error:
ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet
Remove the quotation from this line:
post_author = models.ForeignKey('User',User.username)
It should be like this:
post_author = models.ForeignKey(User,User.username)
I think the problem is this:
from django.contrib.auth.models import User
post_author = models.ForeignKey('User',User.username)
Your ForeignKey want's to use the attribute 'username' of the imported User. Not of your User object when related.
I think I just deleted the migrations and then migrated again from scratch...
I'm trying to have this third class noticeTime be constrained to the foreign key email. I am using the same syntax that worked for the 2nd class location, but when I use it on noticeTime it throws an error:
Exception Value: no such column: setupNotifications_noticetime.email_id
Here is the code:
from django.db import models
# Create your models here.
from django.db import models
class email(models.Model):
email = models.CharField(max_length=200)
def __unicode__(self):
return self.email`
class location(models.Model):
email = models.ForeignKey(email)
zip_code = models.CharField(max_length=5)
def __unicode__(self):
return self.zip_code
class noticeTime(models.Model):
email = models.ForeignKey(email)
time = models.CharField(max_length=200)
def __unicode__(self):
return self.time
here is admin.py:
from django.contrib import admin
# Register your models here.
from setupNotifications.models import email
from setupNotifications.models import location
from setupNotifications.models import noticeTime
admin.site.register(email)
admin.site.register(location)
admin.site.register(noticeTime)
I'm using the sqlite database
Perhaps your problem is that you ran syncdb, assuming that it would alter the table to match your model change. Unfortunately, it does not do that. There are some separate tools available, such as South, which can help with database migrations.
When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.
You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')
Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'
You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method
I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.
This question already has answers here:
What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?
(17 answers)
Closed 3 years ago.
I got an error I don't understand !
cannot import name Item
In my model, I have items. These items are required for actions. But some of these items have an effect on actions :
items
from django.db import models
from effects.models import Effect
class Type(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Item(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
type = models.ForeignKey(Type)
quality = models.IntegerField()
effects = models.ManyToManyField(Effect,through='ItemEffect',blank=True)
item_requirement = models.ManyToManyField('self',through='ItemCraft',symmetrical=False,blank=True)
points = models.IntegerField()
def __unicode__(self):
return self.name
class Food(Item):
ap = models.IntegerField()
class Tool(Item):
durability = models.IntegerField()
[....]
class ItemEffect(models.Model):
item = models.ForeignKey(Item)
effect = models.ForeignKey(Effect)
def __unicode__(self):
return self.item.name+':'+str.lower(self.effect.name)
class Meta:
verbose_name_plural = 'items effects'
class ItemCraft(models.Model):
item = models.ForeignKey(Item,related_name='%(class)s_item_crafted')
item_requirement = models.ForeignKey(Item,related_name='%(class)s_item_required')
number = models.IntegerField()
def __unicode__(self):
return self.item.name+' requires '+str.lower(self.item.name)+'('+self.number+')'
class Meta:
verbose_name_plural = 'items crafts'
actions
from django.db import models
from items.models import Item
class Action(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
pa = models.IntegerField()
def __unicode__(self):
return self.name
class CraftAction(Action):
item = models.ForeignKey(Item)
def __unicode__(self):
return self.item.name+'\'s craft'
class Meta:
verbose_name_plural = 'crafts actions'
effects
from django.db import models
from actions.models import Action
class Effect(models.Model):
action = models.ForeignKey
class ApEffect(Effect):
ap = models.IntegerField()
There is a circular import in your code, that's why the Item can't be imported in action.
You can solve the problem by removing the import of a class in one of your files, and replacing it with a string containing the name of the class, as explained in the documentation. For example :
effects = models.ManyToManyField('effects.Effect',through='ItemEffect',blank=True)
Like madjar suggested, there is likely a circular import in your code. If you're having trouble finding out where the circle is (which modules and imports are involved), you can use the traceback option to get an idea of where the problem lies:
python manage.py validate --traceback
Edit - Validate is deprecated from django 1.7. So please run the following command -
python manage.py check --traceback
Try to import Locally your model instead of as public one, Example
def sample_function():
from effects.models import Effect # import within function or class
or import model as String -> 'APP_NAME.MODEL_NAME'
pay_methods = models.ManyToManyField('payment_app.AllowedPayMethod')
This was the first post that came up on Google so I will post this alternative cause of error.
In my code there was no circular imports, I solved this problem by manually deleting all .pyc files in my project. Apparently restarting the application wasn't recompiling my code.
Similar situation to Pythonator - I had an alternate cause for the same error message.
In my case, I had forgotten to activate the virtual environment I set up for my project and was trying to run the server. After activating the environment and running the server again I had no issues.