In my application, I'm calling API to create choices for DecimalField in models.py.
# -*- coding: utf-8 -*-
from django.db import models
import re
from suds.client import Client
from datetime import datetime
from django.utils import timezone
class Allegro:
def __init__(self):
self.webapi_key = 'hidden key'
self.country = 1
self.client = Client('https://webapi.allegro.pl/service.php?wsdl')
self.client.options.cache.setduration(hours=1)
self.starting_time = '24h'
def get_categories(self):
category_list = self.client.service.doGetCatsData(
countryId=self.country,
webapiKey=self.webapi_key
).catsList.item
categories = []
for item in category_list:
categories.append({'id': item.catId, 'name': item.catName, 'parent': item.catParent})
return categories
# search for free only, with time fixed at 24h. User can set phrase and category only.
def search(self, category, phrase):
params = [{
'item': ({'filterId': 'category', 'filterValueId': {'item': category}},
{'filterId': 'startingTime', 'filterValueId': {'item': self.starting_time}},
{'filterId': 'search', 'filterValueId': {'item': phrase}})
}]
search_raw_result = self.client.service.doGetItemsList(
countryId=self.country,
webapiKey=self.webapi_key,
filterOptions=params,
).itemsList.item
search = []
for item in search_raw_result:
search.append({'id': item.itemId, 'name': item.itemTitle,
'type': item.priceInfo.item[0].priceType, 'price': item.priceInfo.item[0].priceValue})
return search
def choices():
choice_prep = Allegro()
choice = choice_prep.get_categories()
choice_list = []
add = "'"
for item in choice:
if item['parent'] == 0:
item_name = add + item['name'] + add
choice_list.append([item['id'], item_name])
return choice_list
class FreeSearch(models.Model):
a = choices()
mail = models.CharField(verbose_name='mail', max_length=100)
phrase = models.CharField(verbose_name='phrase', max_length=150)
category = models.DecimalField(verbose_name='category', max_digits=6, decimal_places=0, choices=a)
end_date = models.DateTimeField(verbose_name="Data końcowa", blank=True)
activation_key = models.CharField(max_length=40, blank=True)
key_expires = models.DateTimeField(default=timezone.now)
def __str__(self):
return '%s, %s, %s' % (self.mail, self.phrase, self.category)
class Meta:
verbose_name = "Wyszukanie"
verbose_name = "Wyszukania"
Choices should be list of lists where are only two values, id which is decimal max 5 digits and name which contains category names in Allegro auction service.
After calling python manage.py makemigrations in cmd following problem occurs:
C:\Users\Dom\allewatcher>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line
351, in execute_from_command_line
utility.execute()
File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line
343, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python35\lib\site-packages\django\core\management\base.py", line 394,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python35\lib\site-packages\django\core\management\base.py", line 445,
in execute
output = self.handle(*args, **options)
File "C:\Python35\lib\site-packages\django\core\management\commands\makemigrat
ions.py", line 63, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 47,
in __init__
self.build_graph()
File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 176,
in build_graph
self.load_disk()
File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 102,
in load_disk
migration_module = import_module("%s.%s" % (module_name, migration_name))
File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 658, in exec_module
File "<frozen importlib._bootstrap_external>", line 764, in get_code
File "<frozen importlib._bootstrap_external>", line 724, in source_to_code
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\Dom\allewatcher\search\migrations\0001_initial.py", line 20
('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_nam
e='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro
i Reklama], [19732, Biżuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dziec
i], [5, Dom i Ogród], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9,
Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i a
utomaty], [7, Książki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, Nieruch
omości], [1454, Odzież, Obuwie, Dodatki], [16696, Przemysł], [76593, Rękodzieło]
, [10, RTV i AGD], [3919, Sport i Turystyka], [122332, Sprzęt estradowy, studyjn
y i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882
, Zdrowie]])),
^
SyntaxError: invalid syntax
I also don't know why in error description there's no quotation marks added by add variable in choices function.
# -*- coding: utf-8 -*-
from future import unicode_literals
from django.db import migrations, models import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='FreeSearch',
fields=[
('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),
('mail', models.CharField(max_length=100, verbose_name='mail')),
('phrase', models.CharField(max_length=150, verbose_name='phrase')),
('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_name='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro i Reklama], [19732, Biżuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dzieci], [5, Dom i Ogród], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9, Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i automaty], [7, Książki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, Nieruchomości], [1454, Odzież, Obuwie, Dodatki], [16696, Przemysł], [76593, Rękodzieło], [10, RTV i AGD], [3919, Sport i Turystyka], [122332, Sprzęt estradowy, studyjny i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882, Zdrowie]])),
('end_date', models.DateTimeField(blank=True, verbose_name='Data końcowa')),
('activation_key', models.CharField(max_length=40, blank=True)),
('key_expires', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name': 'Wyszukania',
},
),
]
The problems seems to be in this item:
You have a ',' sign there which causes syntax error - this value is put directly into
0001_initial.pyfile and then makes impression that list item has 4 items instead of two.To fix it just remove comma from it's value or just escape it somehow (for example by using HTML entity
,- but it depends on how you are using it further)EDIT
Although commas cause problem directly it seems that issue lays deeper. You migration's code's strings were generated without aphostrophes what causes the problem.
I have checked your code - I have created app, copied your code and run
stack is name of my application BTW
String have been generated with aphostrophes
If it is possible I recommend you to delete all files in your_application/migrations (avoiding delete
__init__.py!) and then try to recreate migration by using standardmakemigrationscommand.I have been using Django in 1.9.2 version, suds 0.4 and Python 2.7