I'm writing a Django Model that will link to another app Model. I know that we should link the ForeginKeys with "nameoftheapp.nameofthemodel" but I'm not successful doing it with this use case.
Here is my installed_apps:
INSTALLED_APPS = (
...
'signup',
'paypal.standard.ipn',
...
)
Basically I'm creating a model in the app "signup" and I need to do a foreignkey to "paypal.standard.ipn".
Here is my model:
class SignupPaymentPayPal(models.Model):
gettingstarted = models.ForeignKey('GettingStarted')
paypalipn = models.ForeignKey('paypal.standard.ipn.PayPalIPN')
The model I need to link is this one, https://github.com/spookylukey/django-paypal/blob/master/paypal/standard/ipn/models.py
When I try to do a shemamigration I got this:
$ python manage.py schemamigration signup --auto
Here is the error I got:
CommandError: One or more models did not validate:
signup.signuppaymentpaypal: 'paypalipn' has a relation with model paypal.standard.ipn.PayPalIPN, which has either not been installed or is abstract.
Any clues on what I'm doing wrong?
Best Regards,
from paypal.standard.ipn.models import PayPalIPN
class SignupPaymentPayPal(models.Model):
gettingstarted = models.ForeignKey('GettingStarted')
paypalipn = models.ForeignKey(PayPalIPN)
André solution works, and in fact I'd recommend using the actual model instead of a string whenever possible, to avoid any unexpected errors when the string can't be resolved to a model, but here's an explanation why your previous method didn't work:
Django has a model cache that keeps track of all Model subclasses that are created. Each model is uniquely identified by an appname and modelname, but not by a fully qualified import path.
Let's say I have two models, one is myapp.reviews.Review, the other is myapp.jobs.reviews.Review. If myapp.reviews.Review comes first in my INSTALLED_APPS, both classes will actually be the myapp.reviews.Review model:
>>> from myapp.jobs.reviews import Review
>>> Review
<class 'myapp.reviews.Review'>
To specify a ForeignKey using a string instead of a class (e.g. to avoid circular imports), you need to follow the '<appname>.<modelname>' format, i.e.:
class SignupPaymentPayPal(models.Model):
paypalipn = models.ForeignKey('ipn.PayPalIPN')
Related
It seems like oscar is not picking up my pointed local folder.
INSTALLED_APP = [] + get_core_apps(['myoscar.partner'])
My error is
Conflicting 'partner' models in application 'partner': <class "oscar.app.partner.models.Partner"> and <class "myoscar.partner.models.Partner">
This also leads me to another related question - there's two settings.py. I've tried adding in both. When I remove myoscar.partner in my main app, I obviously dont get the error but it gives me oscar's default model - which makes sense but then I run into the above error when I add it in. I don't know of anywhere else I'm registering the partner model before this override - at least not that I know of.
My question is
1) which settings.py is the right one? I want to make sure.
2) why do I get this error when I pointed to the forked folder? Is it not picking up my folder?
App/myoscar/partner/models.py
from django.contrib.auth import get_user_model
from django.db import models
from oscar.apps.partner.abstract_models import AbstractPartner
User = get_user_model()
class Partner(AbstractPartner):
users = models.OneToOneField(User,related_name='partner_user')
from oscar.apps.partner.models import *
#per some answers on stackoverflow, I've also tried removing this but the docs say this should be added here to keep the other models.
my folder structure:
App
|--app
|----__init.py__
|----settings.py
|----urls.py
|--myoscar
|----partner
|-------models.py
|----myoscar
|------settings.py
|------urls.py
|--mysub
|----migrations
The problem seems with related_name value. Try using a different value for it.
I'm having some issues using the Algolia Django integration with one of my models which contains a TaggitManager() field. I'm currently being thrown back the following error when running this command:
$ python manage.py algolia_reindex
AttributeError: '_TaggableManager' object has no attribute 'name'
I've had a look at the Taggit documentation, but I'm just not sure exactly how I would marry the method outlined with the Algolia search index method.
index.py:
import django
django.setup()
from algoliasearch_django import AlgoliaIndex
class BlogPostIndex(AlgoliaIndex):
fields = ('title')
settings = {'searchableAttributes': ['title']}
index_name = 'blog_post_index'
models.py:
from taggit.managers import TaggableManager
class Post(models.Model):
...some model fields...
tags = TaggableManager()
To index the taggit tags with your Post fields, you will need to expose a callable that returns a Blog Post's tags as a list of strings.
The best option is to store them as _tags, which will let you filter on tags at query time.
Your PostIndex would look like this:
class PostIndex(AlgoliaIndex):
fields = ('title', '_tags')
settings = {'searchableAttributes': ['title']}
index_name = 'Blog Posts Index'
should_index = 'is_published'
As for Post:
class Post(models.Model):
# ...some model fields...
tags = TaggableManager()
def _tags(self):
return [t.name for t in self.tags.all()]
Following these instructions, your records will be indexed with their respective tags:
You can check the taggit branch of our Django demo, which demonstrates these steps.
To answer my own question. I have now passed in both the model and the model index so Algolia now knows what to index and what not to index. Although I would like a method to allow Algolia to index taggit tags, alas, it is probably not possible.
My apps.py file:
import algoliasearch_django as algoliasearch
from django.apps import AppConfig
from .index import PostIndex
class BlogConfig(AppConfig):
name = 'blog'
def ready(self):
Post = self.get_model('Post')
algoliasearch.register(Post, PostIndex)
My index.py file:
from algoliasearch_django import AlgoliaIndex
class PostIndex(AlgoliaIndex):
fields = ('title')
settings = {'searchableAttributes': ['title']}
index_name = 'Blog Posts Index'
should_index = 'is_published'
And that should pretty much work! Simple when you know how, or after trying about 10 different options!
So since nobody is answering I tell you how I solved this issue but I have to say that it is not a nice Way and not a "clean" Solution at all. So what I did is went into "taggit managers" in the site-packages (env->lib->python2.x/3.x-> site_packages->taggit->managers.py) In the managers.py file you will find at line 394 this beautiful piece of code:
def __get__(self, instance, model):
if instance is not None and instance.pk is None:
raise ValueError("%s objects need to have a primary key value "
"before you can access their tags." % model.__name__)
manager = self.manager(
through=self.through,
model=model,
instance=instance,
prefetch_cache_name=self.name, # this is the line I comment out when building the index,
name=self.name #this is the line I added and needs to be commented out after the index is build.
)
return manager
So what I do when I want to rebuild the search index is comment out (putting"#" infront of the line) prefetch_cache_name=self.name, and replace it with name=self.name. So building the index will work. After the Index is finished building, you have to bring everything back as it was before (switch the "#" to name=self.name again and leave prefetch_cache_name=self.name, visible again).
As already mentioned this is probably not the best way but I had the same pain and this is working for me. It takes one minute when you have the routine. Since I have to rebuild the Index maybe once every two weeks, that isn't such a deal for me but if you have to do it very often this might be annoying...
Anyway I hope that helps you.
It can help you if you using django==2+
The problem is in get_queryset() method of TaggableManager
Open file with it (my path was: Pipenv(project_name)/lib/site-packages/taggit/manager.py)
Find _TaggableManager class and change method name get_queryset to get_query_set
Done. I wish taggit's developers will fixed this in future updates
I am trying to implement django-localflavors into my Django app.
I import USStateSelect & USZipCodeField at the beginning of my models.py and then include them as a field in my model along with other fields, like so:
from localflavor.us.forms import USStateSelect, USZipCodeField
...
Class MyModel(models.Model):
...
state = USStateSelect()
zip_5 = USZipCodeField()
However, when I go to Django admin and try to create a new Model object, I see every other field I wrote (CharFields, etc.) EXCEPT any of the localflavor fields. They are simply not showing up at all as an input field in my Model object form. I have done migrations on my database so that is not the issue.
Am I misunderstanding how to use django-localflavor? I read in an answer to a different post that localflavor doesn't actually create input fields, only stores data... but then I've also read that it DOES let you input data. At this point I am confused. Any help would be appreciated!
I think what you are looking for are the model fields. The form fields are used when building your own forms (usually outside the admin, such as a contact form). Localflavor has a couple fields that should do what you need. Note that these are essentially CharFields that have some extra validation to make sure the follow the desired format.
You need to specify choices option.
Change your code a little as below:
from localflavor.us.forms import USStateSelect, USZipCodeField
...
Class MyModel(models.Model):
...
state = USStateSelect(choices=STATE_CHOICES) # add choices
zip_5 = USZipCodeField() # no change on this line
I'm trying to implement a list of foreignKeys in django-nonrel (I'm using mongo as db).
Here is the code:
# models.py
from django.db import models
from django_mongodb_engine.contrib import MongoDBManager
from djangotoolbox.fields import ListField
class FriendList(models.Model):
objects = MongoDBManager()
list = ListField(models.ForeignKey('AWUser'))
def add_friend(self, awuser):
# awuser must be an instance of AWUser - I removed tests for more clarity
self.list.append(awuser)
self.save()
class AWUser(models.Model):
objects = CustomUserManager()
user = EmbeddedModelField('User')
friends = EmbeddedModelField('FriendList')
The problem is that when I call user.friends.add_friend(user1), I have the error "AttributeError: 'str' object has no attribute '_meta'".
Breaking example (made using ./manage shell console):
$>user = AWUser.objects.all()[0]
$>user1 = AWUser.objects.all()[1]
$>user.friends.add_friend(user1)
#ask me if you need the complete error - I don't put it more more clarity
AttributeError: 'str' object has no attribute '_meta'
What I basically need is to create friend lists.
Please feel free to recommend a different implementation if you think mine is not good. :) I would love to have my implementation working though...
Also, I did not put all the variables of AWUser for more clarity but I can add them if necessary.
Related project dependencies:
django 1.3.1 (installed as django-nonrel)
django-mongodb-engine 0.4.0
djangotoolbox==0.9.2
List item
pymongo==2.1.1
Thanks for your help.
UPDATE:
I tried to change the code as said in the post "ListField with ForeignField in django-nonrel" but I still have the same error...
According to the Django MongoDB Engine documentation, it suggests to use EmbeddedModel from djangotoolbox:
from djangotoolbox.fields import ListField, EmbeddedModelField
class Post(models.Model):
...
comments = ListField(EmbeddedModelField('Comment'))
class Comment(models.Model):
text = models.TextField()
Edit: Forgot the link: http://django-mongodb-engine.readthedocs.org/en/latest/topics/embedded-models.html
I actually just figured out what was wrong.
It is apparently impossible to declare the foreign key class type as a string when in a Listfield. Weird...
If it happens to you, just do the following change:
list = ListField(models.ForeignKey('AWUser'))
becomes:
list = ListField(models.ForeignKey(AWUser))
If anyone as a good explanation of what is going on, I'd love to hear it :)
I am using dumpdata with Django 1.2.3 on the following model:
class Bar(models.Model):
...
class Foo(models.Model):
bars = models.ManyToManyField(Bar, through="Foo_bar", blank=True, null=True)
...
class Foo_bar(models.Model):
foo = models.ForeignKey(Foo)
bar = models.ForeignKey(Bar)
status = models.IntegerField()
...
The json fixture serializes the bars associated with Foos in the Foo objects, resulting in an AttributeError when I try to run loaddata with the fixture:
AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use App.Foo_bar's Manager instead.
Based on what I've read, dumpdata may have been fixed to not serialize m2m, or loaddata fixed to properly deal with them, but it doesn't seem so. I've tried the --natural flag, still no luck. Any ideas?
Thanks in advance.
Depending on what you need to do with your fixtures, the command "dumpscript" from the django_extension package is really useful for handling fixture with complex relations.
No primary keys are used in the file, it's just a python script which only uses objects, and as such can re-create your whole db simply using object.save() calls.