I'm facing the problem when creating the many to many relation with through model using factory. I followed this link factory recipies.
I'm getting the TypeError: 'datetime.date' object is not callable this error. Help me to find the solution.
I got an another error:
File "/local/lib/python2.7/site-packages/factory/base.py", line 492, in _generate
obj = cls._prepare(create, **attrs)
File "/local/lib/python2.7/site-packages/factory/base.py", line 467, in _prepare
return cls._create(model_class, *args, **kwargs)
File "/local/lib/python2.7/site-packages/factory/django.py", line 174, in _create
return manager.create(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'a1' is an invalid keyword argument for this function
models.py
class TimeStampModel(models.Model):
start_date = models.DateField(_('Start Date'))
end_date = models.DateField(_('End Date'))
class Meta:
abstract = True
class User(models.Model):
name = models.CharField()
class Aclass(models.Model):
name = models.CharField()
user = models.ForeignKey(User)
report = models.ManyToManyField('self', through='Bcalss')
class Bcalss(TimeStampModel):
a1 = models.ForeignKey(Aclass)
b1 = models.ForeignKey(Aclass)
factories.py
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
name = "John Doe"
class AclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Aclass
user = factory.SubFactory(UserFactory)
name = "Admins"
class BclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Bclass
a1 = factory.SubFactory(AclassFactory)
b1 = factory.SubFactory(AclassFactory)
start_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=2))
end_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=6))
class AclassWithBclassFactory(AclassFactory):
reports = factory.RelatedFactory(BclassFactory, 'a1')
tests.py
class A1classModelTestCase(TestCase):
def test_a1class_create(self):
a1 = factories.AclassWithBclassFactory.create()
In this line:
start_date = factory.LazyAttribute(datetime.today)
You need to actually call the function with ():
start_date = factory.LazyAttribute(datetime.today())
Related
I am trying to call a get api but it gives me this error everytime.
The error:
AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.
Original exception text was: 'int' object has no attribute 'name'.
My models:
class Destination(models.Model):
Continent_Name = (
('Europe', 'Europe',),
('Asia', 'Asia',),
('North America', 'North America',),
('South America', 'South America',),
('Africa', 'Africa',),
('Oceania', 'Oceania',),
('Polar', 'Polar',),
('Regions', 'Regions',),
)
name = models.CharField(max_length=255, unique=True)
continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
top = models.BooleanField(default=False)
dest_image = models.ImageField(blank=True)
def __str__(self):
return self.name
class Package(models.Model):
TOUR_TYPE = (
('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
('Group Tour', 'Group Tour',),
('Cruise Tour', 'Cruise Tour',),
)
operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
package_name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
featured = models.BooleanField(default=False)
price = models.IntegerField(verbose_name="Price in Nrs")
price_2 = models.IntegerField(verbose_name="Price in $")
duration = models.IntegerField(default=5)
duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
discount = models.IntegerField(verbose_name="Discount %", default=15)
#discounted_price = models.IntegerField(default=230)
#savings = models.IntegerField(default=230)
tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
new_activity = models.ManyToManyField(NewActivity)
accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
transport = models.CharField(max_length=150, default='Flight')
age_range = models.CharField(max_length=100, default='6 to 79 years old')
fix_departure = models.BooleanField(default=False)
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")
content =RichTextField()
highlights = RichTextField()
inclusions = RichTextField()
exclusions = RichTextField()
# itinerary = models.ManyToManyField(Itinerary)
itinerary_text = RichTextField()
faqs = RichTextField(blank=True)
image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
date_created = models.DateField()
def __str__(self):
return self.package_name
My views:
class PackageSearchAPi(ListAPIView):
queryset = Package.objects.all().order_by('package_name')
serializer_class = PackageSerializer
def get(self, request, *args, **kwargs):
search = self.request.query_params.get('search',None)
if search is not None:
qs = Package.objects.filter(Q(destination__name__icontains=search)|
Q(destination__continent__icontains=search)|
Q(package_name__icontains=search)|
Q(city__icontains=search)).disctinct()
else:
qs = Package.objects.values('id','destination','package_name','city')
serializer = PackageSerializer(qs,many=True)
return Response(serializer.data,status=200)
My serializers:
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
depth = 1
Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.
Traceback:
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
return Response(serializer.data,status=200)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
ret = super().data
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
return [
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.
For nested relations you have to define nested serializer
class DestinationSerializer(serializers.Serializer):
name = serializers.CharField()
top = serializers.BooleanField()
continent = serializers.CharField()
class PackageSerializer(serializers.ModelSerializer):
destination = DestinationSerializer()
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
When trying to access serialized.data, throws error for type models.ArrayField, but is successfully stored in mongodb.
models.py
class testStep(models.Model):
number = models.PositiveSmallIntegerField(max_length=100)
payload = models.JSONField(blank=True)
header = models.JSONField(blank=False)
assertors = models.EmbeddedField(model_container=assertStep, blank=True)
class Meta:
abstract = True
class test(models.Model):
_id = models.ObjectIdField(primary_key=True)
appId = models.ForeignKey(application, on_delete=models.PROTECT)
name = models.TextField(blank=False, unique=True)
step = models.ArrayField(model_container=step, blank=True, default=list)
serializers.py
class testStepSerializer(serializers.ModelSerializer):
class Meta:
model = models.testCase
fields = '__all__'
read_only_fields = ['dateCreated', 'dateUpdated', ]
def update(self, instance, validated_data):
instance.testStep = validated_data.get('testStep', instance.testStep)
instance.save()
return instance
views.py
def put(self, request, testCaseId, format=None):
tcDetails = self.getTcDetails(testCaseId)
reqData = request.data.copy()
if serialized.is_valid():
serialized.save()
return Response(json.loads(json_util.dumps(serialized.data)), status=status.HTTP_200_OK)
trace back:
line 355, in value_to_string
post_dict = self._obj_thru_fields('value_to_string', container_obj)
File "C:\Users\XYZ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\djongo\models\fields.py",
line 177, in _obj_thru_fields
processed_value[field.attname] = getattr(field, func_name)(obj, *other_args)
File "C:\Users\XYZ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\djongo\models\fields.py",
line 201, in value_to_string
raise TypeError(f'Type: {type(value)} cannot be serialized')
TypeError: Type: <class 'NoneType'> cannot be serialized
update
when i comment out
"assertors = models.EmbeddedField(model_container=assertStep, blank=True)"
i am not seeing this error. Why is this causing error?
i am using graphene and getting 'name' is an invalid keyword argument for GuestMutation error what is it related to?
//models.py
class Guest(models.Model):
name = models.CharField(max_length=100)
phone = models.IntegerField()
def __str__(self):
return self.name
//schema.py
class GuestType(DjangoObjectType):
class Meta:
model = Guest
fields = ('id','name','phone')
class GuestMutation (graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
phone = graphene.Int(required=True)
guest = graphene.Field(GuestType)
#classmethod
def mutate(cls, root,info,name,phone):
guest = Guest(name=name, phone=phone)
guest.save()
return GuestMutation(name=name, phone=phone)
class Mutation(graphene.ObjectType):
add_guest = GuestMutation.Field()
error message
Traceback (most recent call last):
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor
executor(resolve, reject)
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 756, in executor
return resolve(f(*args, **kwargs))
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
return next(*args, **kwargs)
File "/home/ahmed/Documents/Django/Shalleh/booking/schema.py", line 66, in mutate
return GuestMutation(name=name, phone=phone)
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphene/types/objecttype.py", line 169, in init
raise TypeError(
graphql.error.located_error.GraphQLLocatedError: 'name' is an invalid keyword argument for GuestMutation
You're returning the wrong information:
class GuestMutation (graphene.Mutation):
# What you accept as input
class Arguments:
name = graphene.String(required=True)
phone = graphene.Int(required=True)
# What you return as output
guest = graphene.Field(GuestType)
So as mentioned, you need to return the guest you created.
I'm advancing with the web app I asked about earlier.
Currently, my models.py is
from django.db import models
from unittest.util import _MAX_LENGTH
class Alimento(models.Model):
INTOLERANCIAS = (
('00', 'Ninguna'),
('GL', 'Gluten'),
('CR', 'Crustáceos'),
('HU', 'Huevos'),
('FS', 'Frutos Secos'),
('AP', 'Apio'),
('MO', 'Mostaza'),
('SE', 'Sésamo'),
('PE', 'Pescado'),
('CA', 'Cacahuetes'),
('SO', 'Sulfitos'),
('SJ', 'Soja'),
('LA', 'Lácteos'),
('AL', 'Altramuz'),
('ML', 'Moluscos'),
('CA', 'Cacao'),
)
nombre = models.CharField(max_length=60)
intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS)
def __str__(self):
return self.nombre
class Receta(models.Model):
nombre = models.CharField(max_length=100)
raciones = models.IntegerField(default=1)
preparacion = models.TextField(default='')
consejos = models.TextField(blank=True)
ingredientes = models.ManyToManyField(Alimento, through='Ingrediente', related_name='ingredientes')
def __str__(self):
return self.nombre
def getIntolerancias(self):
ing = self.ingredientes.all()
intolerancias = []
for i in ing:
alimentos = i.alimento.all()
for a in alimentos:
intolerancias.append(a.get_intolerancia_display())
return intolerancias
class Ingrediente(models.Model):
receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE)
alimento = models.ManyToManyField(Alimento)
cantidad = models.FloatField(default=0)
descripcion = models.CharField(max_length=60, blank=True)
def __str__(self):
return self.alimento.__str__()
the method getIntolerancias is supposed to list the food intolerances related to each of the ingredients of a given recipe (Receta). To do that, I try to get the queryset of ingredients (Ingrediente) with ing = self.ingredientes, but when I try it on shell I get this error message
Traceback (most recent call last): File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals) File "<console>", line 1, in <module> File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 758, in __init__
self.target_field_name = rel.field.m2m_reverse_field_name() File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 15, in _curried
return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs)) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related.py", line 1504, in _get_m2m_reverse_attr
return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I've searched for the error, but the answers I've found don't seem to have what I need (I may just don't understand enough to see it does?)
UPDATE
When I run this on the shell I do
g = Receta.objects.get(nombre = 'Gazpacho')
g.getIntolerancias()
I get an error
intolerancias.append(a.get_intolerancia_display()) AttributeError:
'Ingrediente' object has no attribute 'get_intolerancia_display'
However, if I iterate and get the first element of g.ingredientes.all() and call get_intolerancia_display() it does work OK
a = g.ingredientes.all().first()
a.get_intolerancia_display()
'Gluten'
Update after comments:
Documentation about Many-to-many relation
def get_intolerancias(self):
alimentos = self.ingredientes.all() # Give us all alimento of a recetta
intolerancias = []
for a in alimentos:
intolerancias.append(a.get_intolerancia_display())
return intolerancias
Anyone can find what is causing the error in my code? I already searched, but didn't find an answer. I think the problem is with the function objects.get(param), but I'm not sure.
What I wanted to do with my code was to retrieve the objects Genre, Country, Language and Directors if they were already added to the database.
Here's the code:
Models.py
from django.db import models
from numpy import unique
class Director(models.Model):
director = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.director
def __init__(self, director):
super(Director, self).__init__()
self.director = director
class Language(models.Model):
language = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.language
def __init__(self, language):
super(Language, self).__init__()
self.language = language
class Genre(models.Model):
genre = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.genre
def __init__(self, genre):
super(Genre, self).__init__()
self.genre = genre
class Country(models.Model):
country = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.country
def __init__(self, country):
super(Country, self).__init__()
self.country = country
class Movie(models.Model):
id_movie = models.CharField(max_length=200, unique=True)
rating = models.CharField(max_length=200)
votes = models.CharField(max_length=200)
year = models.CharField(max_length=10)
genre = models.ManyToManyField(Genre)
country = models.ManyToManyField(Country)
language = models.ManyToManyField(Language)
directors = models.ManyToManyField(Director)
def __init__(self, id_movie, rating, votes, year):
super(Movie, self).__init__()
self.id_movie = id_movie
self.rating = rating
self.votes = votes
self.year = year
def __unicode__(self):
return self.id_movie
crawler.py
from movie_info.models import Movie, Genre, Director, Language, Country
def get_movie_info(codigo_do_filme):
import imdb
ia = imdb.IMDb()
movie = ia.get_movie(codigo_do_filme)
return {'titulo': movie['title'], 'rating': movie['rating'], 'votes': movie['votes'], 'ano': movie['year'], 'genero': movie['genre'][0], 'pais': movie['countries'][0], 'idioma': movie['lang'][0], 'directors': movie['director']}
def read_sheet(file_name, fieldnames=None, delimiter=",", quotechar="\n"):
from csv import DictReader
reader = DictReader(open(file_name,'rb'), fieldnames = fieldnames, delimiter = delimiter, quotechar=quotechar)
return reader
def fill_db_movie_info(the_sheet_file):
file_csv = read_sheet(the_sheet_file)
for movie in file_csv:
id_filme = movie['id_move']
if not Movie.objects.filter(id_movie=id_filme).exists():
info = get_movie_info(id_filme)
rating_imdb = info['rating']
movie_votes = info['votes']
movie_year = info['ano']
movie_genre = info['genero']
movie_country = info['pais']
movie_lang = info['idioma']
movie_directors = info['directors']
addToDB = Movie(id_filme, rating_imdb, movie_votes, movie_year)
addToDB.save()
if not Genre.objects.filter(genre=movie_genre).exists():
genreToDB = Genre(movie_genre)
genreToDB.save()
addToDB.genre.add(genreToDB)
else:
addToDB.genre.add(Genre.objects.get(genre=movie_genre))
if not Country.objects.filter(country=movie_country).exists():
countryToDB = Country(movie_country)
countryToDB.save()
addToDB.country.add(countryToDB)
else:
addToDB.country.add(Country.objects.get(country=movie_country))
if not Language.objects.filter(language=movie_lang).exists():
langToDB = Language(movie_lang)
langToDB.save()
addToDB.language.add(langToDB)
else:
addToDB.language.add(Language.objects.get(language=movie_lang))
for m_director in movie_directors:
if not Director.objects.filter(director=m_director['name']).exists():
directorsToDB = Director(m_director['name'])
directorsToDB.save()
addToDB.directors.add(directorsToDB)
else:
addToDB.directors.add(Director.objects.get(director=m_director['name']))
print "salvou: " + id_filme, rating_imdb, movie_votes, movie_year, movie_genre, movie_country, movie_lang, movie_directors[0]
The Traceback:
pydev debugger: starting (pid: 1424)
Traceback (most recent call last):
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1845, in <module>
debugger.run(setup['file'], None, None)
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1373, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/main.py", line 7, in <module>
fill_db_movie_info('/Users/rubenspessoa/Documents/Workspace/DATASET/test_subdataset.csv')
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/crawler.py", line 49, in fill_db_movie_info
addToDB.country.add(Country.objects.get(country=movie_country))
File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 230, in iterator
obj = model(*row_data)
TypeError: __init__() takes exactly 2 arguments (3 given)
You have defined __init__ methods for all your models. You should not do that.