Django inlineformset_factory how to properlu override the __init__ function - django

everyone!
I'm trying to pass a value to the init function and fill one of my field with data from another model.
I hardcoded the value to get the right data in my field.
I want to know, how to pass initial values into init function?
I found a lot of solutions but they doesn't work for me.
I've tried to pass primary key into initial func:
forms.py
class ObservationPartsForm(forms.ModelForm):
def __init__(self, pk=None, *args, **kwargs):
super(ObservationPartsForm, self).__init__(*args, **kwargs)
primary = kwargs.get('pk')
print('Get pk',primary) #Get pk None
instance = kwargs.get("instance")
meteostation = MeteoStation.objects.get(id=pk)
if instance == None:
meteoparam = forms.ModelChoiceField(
queryset=meteostation.meteo_parametrs.select_related().filter(is_active=True),
label='Метеопараметр',
)
self.fields['meteoparam'] = meteoparam
else:
value_selected = forms.ChoiceField(label='Значение для выбора')
self.fields['value_selected'] = value_selected
#print(instance)
class Meta():
model = ObservationParts
fields = ('meteoparam',
'value_digit',
'value_selected',
'author_parts',
'who_updated')
ObservationEntireFormset = inlineformset_factory(ObservationEntire, ObservationParts,
form=ObservationPartsForm, extra=1,
)
views.py
class ObservePartsCreateView(CreateView):
template_name = 'dairy/test.html'
model = ObservationParts
#form_class = ObservationPartsForm
success_message = 'Метеопараметры добавлены к наблюдению.'
formset = None
def get_form(self, form_class=None, **kwargs):
pk_ = self.kwargs.get("pk")
print(pk_)
form = ObservationPartsForm(pk=pk_)
return form
def get_initial(self, **kwargs):
initial = super(ObservePartsCreateView, self).get_initial()
initial['value_selected'] = ObserveDate.objects.all()
return initial
def get(self, request, *args, **kwargs):
pk_ = kwargs.get("pk")
observe_entire = ObservationEntire.objects.get(pk=pk_)
self.formset = ObservationEntireFormset(instance=observe_entire)
return super(ObservePartsCreateView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(ObservePartsCreateView, self).get_context_data(**kwargs)
context['formset'] = self.formset
return context
def post(self, request, *args, **kwargs):
pk_ = self.kwargs.get("pk")
observe_entire = ObservationEntire.objects.get(pk=pk_)
self.formset = ObservationEntireFormset(request.POST, instance=observe_entire)
if self.formset.is_valid():
self.formset.save()
return redirect('test', pk=observe_entire.id)
else:
return super(ObservePartsCreateView, self).get(request, *args, **kwargs)
def get_form_kwargs(self, **kwargs):
pk_ = self.kwargs.get("pk")
kwargs = super(ObservePartsCreateView, self).get_form_kwargs()
kwargs['primary'] = pk_
return kwargs
When I'm passing any values into init function I've got an error:
Exception Value:
'ObservationPartsForm' object has no attribute 'name'
Traceback if i'm trying to pass value, like this
ObservationEntireFormset = inlineformset_factory(ObservationEntire, ObservationParts, form=ObservationPartsForm(pk=1), extra=1,)
Traceback:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/urls/resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/wess/Documents/Work/GreenTest/greenschool/greenApp/urls.py", line 14, in <module>
path('', include('dairy.urls')),
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/wess/Documents/Work/GreenTest/greenschool/dairy/urls.py", line 4, in <module>
from dairy.views import *
File "/home/wess/Documents/Work/GreenTest/greenschool/dairy/views.py", line 10, in <module>
from dairy.forms import *
File "/home/wess/Documents/Work/GreenTest/greenschool/dairy/forms.py", line 59, in <module>
form=ObservationPartsForm(pk=1), extra=1,
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/forms/models.py", line 1077, in inlineformset_factory
FormSet = modelformset_factory(model, **kwargs)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/forms/models.py", line 878, in modelformset_factory
validate_min=validate_min, validate_max=validate_max)
File "/home/wess/Documents/Work/Green/VPS/env_green/lib/python3.6/site-packages/django/forms/formsets.py", line 441, in formset_factory
return type(form.__name__ + 'FormSet', (formset,), attrs)
AttributeError: 'ObservationPartsForm' object has no attribute '__name__'

Related

Error when I try to rename fieldname in my models.py

Annoying problem. I want to rename a field in my model from reconciled_type to import_type. As soon as I change the fieldname I get the error below and can't proceed to MakeMigrations.
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'reconciled_type' into field. Choices are: account, amount, category, category_id, created, currency, data, description, id, import_journal_entry, import_journal_entry_id, import_type, is_load, merchant, merchant_id, monzo_id, settled, transaction_datetime, updated
The field in Models.py:
IMPORT_TYPE_CHOICES = (
('r', 'Reconciled'),
('i', 'Ignore'),
)
reconciled_type = models.CharField(
max_length=1,
choices=IMPORT_TYPE_CHOICES,
blank=True, null=True,
)
The full traceback is:
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\urls\resolvers.py",
line 406, in check
for pattern in self.url_patterns:
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\urls\resolvers.py",
line 587, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\urls\resolvers.py",
line 580, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Philip\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Philip\CodeRepos\Acacia2\acacia2\urls.py", line 6, in <module>
import monzo.views
File "C:\Users\Philip\CodeRepos\Acacia2\monzo\views.py", line 11, in <module>
from .forms import ReconciliationForm
File "C:\Users\Philip\CodeRepos\Acacia2\monzo\forms.py", line 8, in <module>
class ReconciliationForm(forms.Form):
File "C:\Users\Philip\CodeRepos\Acacia2\monzo\forms.py", line 9, in ReconciliationForm
transaction = forms.ModelChoiceField(queryset=Transaction.objects.filter(reconciled_type__isnull=True),required=True)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\sql\query.py", line 1337, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\sql\query.py", line 1362, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\sql\query.py", line 1239, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\sql\query.py", line 1077, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\sql\query.py", line 1466, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'reconciled_type' into field. Choices are: account, amount, category, category_id, created, currency, data, description, id, import_journal_entry, import_journal_entry_id, import_type, is_load, merchant, merchant_id, monzo_id, settled, transaction_datetime, updated
In your ReconciliationForm you wrote a line like:
class ReconciliationForm(forms.ModelForm):
transaction = forms.ModelChoiceField(
queryset=Transaction.objects.filter(reconciled_type__isnull=True),
required=True
)
# …
but since you renamed that field, the construction of the queryset will thus raise an error, you need to alter the query as well:
class ReconciliationForm(forms.ModelForm):
transaction = forms.ModelChoiceField(
queryset=Transaction.objects.filter(import_type=None),
required=True
)
# …
You might need to change more querysets that had a dependency on that field.
The cause of this error might be because django is not able to resolve your choices,
The choices, should be a list
IMPORT_TYPE_CHOICES = [ # converted to list from tuple
('r', 'Reconciled'),
('i', 'Ignore'),
]

django rest framework DefaultRouter error

I wrote a program to learn django rest framework, but the program I wrote is not executed correctly. I have been looking for it for a long time. I can't find the error. I need someone to help me check the problem from another perspective. Thank you.
models.py
from django.db import models
class Subsystem(models.Model):
name = models.CharField(max_length=36)
class Menu(models.Model):
subsystem = models.ForeignKey(Subsystem, on_delete=models.CASCADE)
name = models.CharField(max_length=36)
serializers.py
from rest_framework.serializers import ModelSerializer
from subsystem.models import Subsystem, Menu
class SubsystemSerializer(ModelSerializer):
class Meta:
model = Subsystem
fields = ('name', )
class MenuSerializer(ModelSerializer):
class Meta:
model = Menu
fields = ('name', 'subsystem')
views.py
from rest_framework.viewsets import ModelViewSet
from subsystem.models import Subsystem, Menu
from subsystem.api.serializers import SubsystemSerializer, MenuSerializer
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer(queryset)
class MenuViewSet(ModelViewSet):
queryset = Menu.objects.all()
serializer_class = MenuSerializer
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from subsystem.api.views import SubsystemViewSet
router = DefaultRouter()
router.registry(r'subsystems', SubsystemViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
I started trying to run python manage.py runserver but it can't run
error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06125FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable
I modified views.py
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
But the error still exists
detail:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x065F5FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable
ViewSet's serializer_class should be class itself, not it's instance. You should use serializer_class = SubsystemSerializer instead of serializer_class = SubsystemSerializer(queryset).Rewrite SubsystemViewSet to this:
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
Also it should be register instead of registry:
router.register(r'subsystems', SubsystemViewSet)
You can find example of routers usage here.

Django - "Relation Does Not Exist" on Fresh Migrations

I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!
Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?
pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
utility.execute()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
self.check()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
issues.extend(super(Command, self)._run_checks(**kwargs))
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/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 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/cvcexport/genius/Genius/urls.py", line 12, in <module>
url(r'^', include('Inventory.urls', namespace="Inventory")),
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/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 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/cvcexport/genius/Inventory/urls.py", line 3, in <module>
from Inventory import views
File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
class SummaryView(InventoryView):
File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
summary_table = build_summary_table()
File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
table_query = Purchase.inventory.current_summary_data(**kwargs)
File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
for item in totals:
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
for row in compiler.results_iter():
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
results = self.execute_sql(MULTI)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
My files are kinda bulky, but this is the Manager that is tripping it up:
class EntryManager(Manager):
def user_create(self, request):
type = request.POST.get('type', None)
label = request.POST.get('label', None)
details = request.POST.get('details', None)
date_added = date.today()
sequence = 1 + self.model.objects.filter(type=type, active=True).count()
label = type + str(sequence) + "- " + label
entry = self.model.objects.create(
type=type,
label=label,
details=details,
date_added=date_added,
sequence=sequence,
user=request.user
)
return entry
def user_update(self, request, pk):
entry = self.model.objects.get(id=pk)
entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
entry.details = request.POST.get("details")
entry.user = request.user
entry.save()
return entry
def user_delete(self, pk):
entry = self.model.objects.get(id=pk)
successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
for obj in successors:
obj.sequence -= 1
obj.label = obj.label.split(" ", 1)[1]
obj.label = obj.type + str(obj.sequence) + "- " + obj.label
obj.save()
key = entry.id
entry.delete()
return key
def get_entry_set(self, request):
"""
Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
setStratEntries method.
Args:
Request Delivers two relevant variables:
s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
o_or_t: Indicates "X-axis" (opportunity or threat) requirement.
Returns:
All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
"""
# Build Dictionary of active Strengths or Weaknesses
s_or_w = request.GET.get("s_or_w")
strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
s_or_w_data = []
for entry in strengths_or_weaknesses:
s_or_w_data.append({
"id": entry.id,
"label": entry.label
})
# Build Dictionary of active Opportunities or Threats
o_or_t = request.GET.get("o_or_t")
opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
o_or_t_data = []
for entry in opportunities_or_threats:
o_or_t_data.append({
"id": entry.id,
"label": entry.label,
})
# Combine for for JSON delivery.
data = {
"s_or_w": s_or_w_data,
"o_or_t": o_or_t_data
}
return data
This is the associated model:
class Entry(GenericObject):
type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
sequence = models.IntegerField()
label = models.CharField(max_length=124)
actions = managers.EntryManager()
objects = models.Manager()
class Meta:
ordering = ["id"]
Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?
first migrate that particular app. python manage.py migrate app_name. Which will resolve the dependency.
I never figured out what was wrong. The error would trip at different points in my managers here and there, but would always be triggered first in the views. I simply commented out all of the views and urlpatterns, ran the migrations and then reverted the files.

ArrayField to store custom Field value

I want to use an arrayfield to store a list of json strings which represent a specific custom class. What I have done is:
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models
# other imports
class MyCustomField(models.Field):
a = models.FloatField(blank=True, null=True)
b = models.DateTimeField()
c = JSONField(blank=True, null=True)
def db_type(self, connection):
return 'Text'
def rel_db_type(self, connection):
return 'integer UNSIGNED'
def to_python(self, value):
return json.loads(value)
def get_prep_value(self, value):
return json.dumps(value)
class A(models.Model):
# ... various normal fields here, then:
pres = ArrayField(MyCustomField)
def get_absolute_url(self):
return reverse('foo:bar', kwargs={'pk': self.id})
But:
python manage.py makemigrations
throws the following error
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/contrib/postgres/fields/array.py", line 75, in set_attributes_from_name
self.base_field.set_attributes_from_name(name)
TypeError: set_attributes_from_name() missing 1 required positional argument: 'name'
The full traceback is:
Traceback (most recent call last):
File "manage.py", line 13, in <module>
execute_from_command_line(sys.argv)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/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 673, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "<path_to_my_app>/models.py", line 62, in <module>
class SolarPrediction(models.Model):
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/base.py", line 157, in __new__
new_class.add_to_class(obj_name, obj)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/base.py", line 316, in add_to_class
value.contribute_to_class(cls, name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 689, in contribute_to_class
self.set_attributes_from_name(name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/contrib/postgres/fields/array.py", line 75, in set_attributes_from_name
self.base_field.set_attributes_from_name(name)
TypeError: set_attributes_from_name() missing 1 required positional argument: 'name'
Any thoughts on what I might be doing wrong?
Thanks
Try to define base_field attribute as standalone field - MyCustomField() istead of MyCustomField:
pres = ArrayField(MyCustomField())

approaching attribute in django auth.user model extension

#models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
birthday = models.DateField(blank=True, null=True)
I extended the django.contrib.auth.views.models.User with additional infomations such as birthday etc.
The problem is that I can't access birthday with request.user.profile in the views.py.
I had to use extra widget to make the app more intuitive.
I did it like this :
#forms.py
class ProfileEditForm(forms.ModelForm):
birthday = forms.DateField(widget=extras.SelectDateWidget)
class Meta:
model = Profile
fields = ('photo', 'phone_num', 'nationality', 'gender')
#views.py
#login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance = request.user,
data = request.POST)
profile_form = ProfileEditForm(instance = request.user.profile,
data = request.POST,
files = request.FILES)
if user_form.is_valid() and profile_form.is_valid():
request.user.profile.birthday = user_form.cleaned_data['birthday']
user_form.save()
profile_form.save()
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(
instance = request.user.profile
)
return render(request,
'views/edit_profile.html',
{'user_form' : user_form,
'profile_form' : profile_form})
The full traceback:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fac3cbfa488>
Traceback (most recent call last):
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/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 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/bravepeach/urls.py", line 23, in <module>
url(r'', include('webapp.urls')),
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/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 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/urls.py", line 2, in <module>
from . import views
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/views.py", line 4, in <module>
from .forms import UserRegistrationForm, UserEditForm, ProfileEditForm
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/forms.py", line 37, in <module>
class UserEditForm(forms.ModelForm):
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (birthday) specified for User
As #Alasdair mentioned, you need to correct your UserEditForm class. Coming back to custom widget you can do
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('photo', 'phone_num', 'nationality', 'gender', 'birthday')
widgets = {
'birthday': extras.SelectDateWidget,
}