approaching attribute in django auth.user model extension - django

#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,
}

Related

graphene_django DjangoFilterConnectionField - The type * doesn't have a connection

I have a problem with graphene_django. When I create a DjangoObjectType and pass this to DjangoFilterConnectionField in my Query, I get an AssertionError that The type {my DjangoObjectType class} doesn't have a connection.
Here is part of my code:
class TradeType(DjangoObjectType):
class Meta:
model = Trade
filter_fields = {
'id': ['exact', 'range', 'in', 'gte', 'lt'],
'updated': ['gte', 'lt'],
'created': ['gte', 'lt']
}
interface = (graphene.relay.Node,)
class Query(graphene.ObjectType):
trades = DjangoFilterConnectionField(TradeType)
I did all of this based on this page.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in
_bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/channels/management/commands/runserver.py", line 69, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check
all_issues = checks.run_checks(
File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/local/lib/python3.8/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 "/app/tabdeal/urls.py", line 45, in <module>
path('utils/', include('utils.urls')),
File "/usr/local/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/local/lib/python3.8/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 "/app/utils/urls.py", line 6, in <module>
from utils.schema import schema
File "/app/utils/schema.py", line 200, in <module>
schema = graphene.Schema(query=Query)
File "/usr/local/lib/python3.8/site-packages/graphene/types/schema.py", line 78, in __init__
self.build_typemap()
File "/usr/local/lib/python3.8/site-packages/graphene/types/schema.py", line 167, in build_typemap
self._type_map = TypeMap(
File "/usr/local/lib/python3.8/site-packages/graphene/types/typemap.py", line 80, in __init__
super(TypeMap, self).__init__(types)
File "/usr/local/lib/python3.8/site-packages/graphql/type/typemap.py", line 31, in __init__
self.update(reduce(self.reducer, types, OrderedDict())) # type: ignore
File "/usr/local/lib/python3.8/site-packages/graphene/types/typemap.py", line 88, in reducer
return self.graphene_reducer(map, type)
File "/usr/local/lib/python3.8/site-packages/graphene/types/typemap.py", line 117, in graphene_reducer
return GraphQLTypeMap.reducer(map, internal_type)
File "/usr/local/lib/python3.8/site-packages/graphql/type/typemap.py", line 109, in reducer
field_map = type_.fields
File "/usr/local/lib/python3.8/site-packages/graphql/pyutils/cached_property.py", line 22, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/usr/local/lib/python3.8/site-packages/graphql/type/definition.py", line 198, in fields
return define_field_map(self, self._fields)
File "/usr/local/lib/python3.8/site-packages/graphql/type/definition.py", line 212, in define_field_map
field_map = field_map()
File "/usr/local/lib/python3.8/site-packages/graphene/types/typemap.py", line 275, in construct_fields_for_type
map = self.reducer(map, field.type)
File "/usr/local/lib/python3.8/site-packages/graphene_django/fields.py", line 98, in type
assert _type._meta.connection, "The type {} doesn't have a connection".format(
AssertionError: The type TradeType doesn't have a connection
graphene==2.1.9, graphene_django==2.15, django-filter==2.4
I think the issue is it can't find what interface to use because you mistype interfaces in the Meta class as interface.
class TradeType(DjangoObjectType):
class Meta:
...
interfaces = (graphene.relay.Node,)

Return just the last object in Django REST Framework

I'm new to asking on StackOverflow and to Django so I'm sorry if I made any mistakes.
So far, I have a basic API with Django and REST Framework. I want to return just the last object that was added to the database, which could be done with the highest ID.
This is the models.py:
from django.db import models
class Humidity(models.Model):
value = models.FloatField()
class Temperature(models.Model):
value = models.FloatField()
isFarenheit = models.BooleanField()
I don't have any time fields, but I can add them if necessary.
This is the serializers.py:
class HumiditySerializer(serializers.ModelSerializer):
class Meta:
model = Humidity
fields = ('id', 'value')
class TemperatureSerializer(serializers.ModelSerializer):
class Meta:
model = Temperature
fields = ('id', 'value', 'isFarenheit')
And this is the views.py:
from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Humidity, Temperature
from .serializers import HumiditySerializer, TemperatureSerializer
class HumidityView(viewsets.ModelViewSet):
queryset = Humidity.objects.order_by('-id')[0]
serializer_class = HumiditySerializer
class TemperatureView(viewsets.ModelViewSet):
queryset = Temperature.objects.order_by('-id')[0]
serializer_class = TemperatureSerializer
This is the traceback of the error:
Traceback (most recent call last):
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\iotSensors\urls.py", line 21, in <module>
path('', include('api.urls')),
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\api\urls.py", line 6, in <module>
router.register('humidity', views.HumidityView)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 75, in register
basename = self.get_default_basename(viewset)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 162, in get_default_basename
return queryset.model._meta.object_name.lower()
AttributeError: 'Humidity' object has no attribute 'model'
This error is only thrown when I change in the views.py from Humidity.objects.all() to Humidity.objects.order_by('-id')[0] and the same with temperature.
How do I return the last object saved?
Since you don't have time or date fields in your model, you may retrieve the latest object only through id.
Humidity.objects.all().order_by('-id')[:1]
-id retrieves the objects in the reverse order.
Since QueryDict object of django is lazily loaded, this will only retrieve the latest value.
You can use the last function to retrieve the latest object
Humidity.objects.all().latest()
or just retrieve the object with the latest id by
Humidity.objects.latest('id')
# To get last object or record
Humidity.objects.last()

Django inlineformset_factory how to properlu override the __init__ function

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__'

why does my exception give a syntax error

well new to django and python the website i'm making is an ecommerce website and it has a carts app which deals with the shopping cart in the views.py file i have this function :
def get(self, request):
try:
item_id = request.GET.get('item')
quantity = request.GET.get('qty', 1)
delete = request.GET.get('delete', 'n')
cart, is_deleted, cart_item = self._process_cart(item_id, int(quantity), delete, request)
cart_count = cart.total_count
request.session['cart_count'] = cart_count
return Response({'success': True,
'deleted': is_deleted,
'count': cart.count,
'item_total': cart_item.item_total,
'cart_price': cart.cart_price,
'cart_count': cart_count}, status=status.HTTP_200_OK)
except Exception as error:
print error
it always gives an invalid syntax error
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\management\commands\runserver.py", line 117, in
inner_run
self.check(display_num_errors=True)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\management\base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\urls\resolvers.py", line 396, in check
for pattern in self.url_patterns:
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\urls\resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-
32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in
_call_with_frames_removed
File "C:\ecommerce-django-master\src\ecommerce\urls.py", line 15, in
<module>
url(r'^cart/', include('carts.urls')),
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37-
32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in
_call_with_frames_removed
File "C:\ecommerce-django-master\src\carts\urls.py", line 4, in <module>
from . import views
File "C:\ecommerce-django-master\src\carts\views.py", line 56
return Response({'success': True, 'deleted': is_deleted, 'count':
cart.count, 'item_total': cart_item.item_total, 'cart_price':
cart.cart_price, 'cart_count':cart_count}, status = status.HTTP_200_OK)
^
SyntaxError: invalid syntax
so i tried using an if instead of try but the result was my shopping cart didn't work properly afterwards it never updated it's badge and never got anything in it even after an order

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.