AttributeError: module 'tensorflow' has no attribute 'ConfigProto'
- AttributeError: module 'tensorflow' has no attribute 'ConfigProto'
- AttributeError: 'NoneType' object has no attribute 'message_types_by ...
- Resolve the Error “AttributeError: 'Tensor' object has no attribute ...
- Built-in Functions — Python 3.11.1 documentation
- How to fix "AttributeError: module 'tensorflow' has no attribute 'get ...
- 3. Data model — Python 3.11.1 documentation
- AttributeError: 'Tensor' object has no attribute 'numpy'
- Built-in Types — Python 3.11.1 documentation
- Château de Versailles Site officiel
- AttributeError:‘Options‘ object has no attribute ‘binary‘
PhotoshopBattles
Photoshop contests on reddit. A place to battle using image manipulation software, play photoshop tennis, create new images from old photos, or even win reddit gold.
Miniscule worlds in the wild
For the tiny places you discover (or make) that look like they could be a world of their own.
Pro-choice
A sub for pro-choice redditors who care about the reproductive rights for girls, women, and all pregnant people. Abortion bans are reproductive abuse and sex based violence on people afab. We are united in our cause to end reproductive abuse for all people who can experience pregnancy. We welcome others of opposing views when they're expressed with respect in discussions, but if you are only here to criticize, change minds, or tell people they are wrong you will be instantly banned.
AttributeError 'NoneType' object has no attribute 'group'
**What the script is about**
the script is used for scraping off Instagram and putting it in a compilation to upload it on youtube but it runs into some errors
**source**
https://github.com/nathan-149/automated_youtube_channel
**Error code**
```
Exception has occurred: AttributeError
'NoneType' object has no attribute 'group'
File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\scrape_videos.py", line 29, in scrapeVideos
looter = ProfileLooter(acc, videos_only=True, template="{id}-{username}-{width}-{height}")
File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\
main.py", line 91, in routine
scrapeVideos(username = IG_USERNAME,
File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\
main.py", line 137, in attemptRoutine
routine()
File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\
main.py", line 146, in
attemptRoutine()
```
I somehow cand find any attribute called "group" in any file in the project and dont know what could be the issue, anyone who knows what is going wrong there?
**Tried**
Code to run a fully automated youtube that can scrape content, edit a compilation, and upload to youtube daily. Fixing it by removing the attribute "group"
**Ended up with**
Not finding any attribute that is called group or even the word itself across all the files.
submitted by Fun_Caregiver_4006 to pythonhelp [link] [comments]
Lutris shows " attributeerror 'nonetype' object has no attribute 'lower'" when installing using Epic laucher
So I'm new to Linux in general I usually play games of Steam but I found recently I can play games from Epic games using Lutris so I installed it and signed in using my account but I can't install any games from my Library except " Attribute Error 'nonetype' object has no attribute 'lower' " shows up.Can someone let me know how to fix this and suggest me some any-other alternative how run games from epic or GOG ( Ubuntu user)
submitted by generalBlue55 to linuxquestions [link] [comments]
AttributeError at / 'OrderedDict' object has no attribute 'register' in Django REST framework from quickstart documentation
Django
I am trying to work with Django REST framework but I am getting the AttributeError at /'OrderedDict' object has no attribute 'register'. I think I have followed the documentation properly Can someone help with this.
Link to the tutorial:
https://www.django-rest-framework.org/tutorial/quickstart/ I have already used Django now I am trying to work with the Django REST framework but following the quickstart tutorial is resulting in:AttributeError at /'OrderedDict' object has no attribute 'register'.
tutorial.py/urls.py
from rest_framework import routersfrom quickstart import viewsfrom django.contrib import adminrouter = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'groups', views.GroupViewSet)urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest\_framework.urls', namespace='rest\_framework')),] tutorial/quickstart/serializers.py
from rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups']class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] tutorial/quickstart/views.py
from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom .serializers import UserSerializer, GroupSerializerclass UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date\_joined') serializer_class = UserSerializerclass GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer tutorial/settings.py
import os# Build paths inside the project like this: os.path.join(BASE\_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = '&m8r-k(#%7tw6u31r-83ld\
[email protected]+86xrztepov4&=+s(&uapy2'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest\_framework',]MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'tutorial.urls'TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP\_DIRS': True, 'OPTIONS': { 'context\_processors': [ 'django.template.context\_processors.debug', 'django.template.context\_processors.request', 'django.contrib.auth.context\_processors.auth', 'django.contrib.messages.context\_processors.messages', ], }, },]WSGI_APPLICATION = 'tutorial.wsgi.application'# Database# https://docs.djangoproject.com/en/2.2/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Password validation# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password\_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password\_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password\_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password\_validation.NumericPasswordValidator', },]# Internationalization# https://docs.djangoproject.com/en/2.2/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = TrueSTATIC_URL = '/static/'REST_FRAMEWORK = { 'DEFAULT\_PAGINATION\_CLASS': [ 'rest\_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ]} The error response is :
Environment:Request Method: GETRequest URL: http://127.0.0.1:8000/Django Version: 2.2.3Python Version: 3.7.1Installed Applications:['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest\_framework']Installed Middleware:['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']Traceback:File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request)File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response 143. response = response.render()File "D:\ProgrammingFiles\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_contentFile "D:\ProgrammingFiles\lib\site-packages\rest\_framework\response.py" in rendered_content 70. ret = renderer.render(self.data, accepted_media_type, context)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\renderers.py" in render 725. context = self.get_context(data, accepted_media_type, renderer_context)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\renderers.py" in get_context 687. 'description': self.get_description(view, response.status_code),File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\renderers.py" in get_description 602. return view.get_view_description(html=True)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\views.py" in get_view_description 245. return func(self, html)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\views.py" in get_view_description 61. return formatting.markup_description(description)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\utils\formatting.py" in markup_description 63. description = apply_markdown(description)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\compat.py" in apply_markdown 156. md_filter_add_syntax_highlight(md)File "D:\ProgrammingFiles\lib\site-packages\rest\_framework\compat.py" in md_filter_add_syntax_highlight 213. md.preprocessors.register(CodeBlockPreprocessor(), 'highlight', 40)Exception Type: AttributeError at /Exception Value: 'OrderedDict' object has no attribute 'register' The result should be :
https://www.django-rest-framework.org/img/quickstart.png Answer link :
https://codehunter.cc/a/django/attributeerror-at-ordereddict-object-has-no-attribute-register-in-django-rest-framework-from-quickstart-documentation submitted by code_hunter_cc to codehunter [link] [comments]
Django AttributeError Model object has no attribute 'filter'
Django
I'm trying to do my own blog using Django. I have a view to show an article which is extended from DetailView.To avoid any trouble with slugs, I'm trying to classify the articles with its date of publication. The url for an article is like so (where pk correspond to the slug of the article):
r'articles/(?P
\d{4})/(?P\d{2})/(?P\d{2})/(?P[\w-]+)/$' In my view I want to do this:
def get\_queryset(self): year = self.kwargs.get("year", None) month = self.kwargs.get("month", None) day = self.kwargs.get("day", None) publication_date = year + "-" + month + "-" + day return Article.objects.get(created_at__startswith=publication_date, slug=self.kwargs.get("pk", None)) But it doesn't work and I don't get it...In fact it works when I do this:
return Article.objects.filter(created_at__startswith=publication_date, slug=self.kwargs.get("pk", None)) But it returns a QuerySet and I just want one article! ([0] returns the same error)
Here is the error:
AttributeError at /articles/2015/03/04/nouveau-site/'Article' object has no attribute 'filter'Django Version: 1.6.2Exception Location: C:\Python27\lib\site-packages\django\views\generic\detail.py in get_object, line 37Python Version: 2.7.6 And the full traceback:
Environment:Request Method: GETRequest URL: http://localhost:8000/articles/2015/03/04/nouveau-site/Django Version: 1.6.2Python Version: 2.7.6Installed Applications:('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'groups', 'posts', 'users')Installed Middleware:('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware')Traceback:File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs)File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch 87. return handler(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django\views\generic\detail.py" in get 110. self.object = self.get_object()File "C:\Python27\lib\site-packages\django\views\generic\detail.py" in get_object 37. queryset = queryset.filter(pk=pk)Exception Type: AttributeError at /articles/2015/03/04/nouveau-site/Exception Value: 'Article' object has no attribute 'filter' Thanks in advance!
Answer link : https://codehunter.cc/a/django/django-attributeerror-model-object-has-no-attribute-filter
submitted by code_hunter_cc to codehunter [link] [comments]
AttributeError 'int' object has no attribute 'self
Hello.
New to Pycharm- can anyone point me to a basic explanation of the AttributeError above? My sources have not been helpful.
Thanks.
submitted by Consistent_Number509 to pycharm [link] [comments]
AttributeError 'tuple' object has no attribute 'get'
Django
I have a Django application. But i can't an error that i have been struggling with for some time now.
Exception Value: 'tuple' object has no attribute 'get'Exception Location: /Library/Python/2.7/site-packages/django/middleware/clickjacking.py in process_response, line 30 And this is the traceback django provides me.
Traceback:File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response201. response = middleware_method(request, response)File "/Library/Python/2.7/site-packages/django/middleware/clickjacking.py" in process_response30. if response.get('X-Frame-Options', None) is not None: I have a hard time figuring out why this error occurs. How can i find out where that tuple is in my code?
The view:
def products(request, category=None, gender=None, retailer\_pk=None, brand\_pk=None): # If the request it doesn't have a referer use the full path of the url instead. if not request.META.get("HTTP\_REFERER", None): referer = request.get_full_path() else: referer = request.META.get("HTTP\_REFERER") if gender: products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0) & Q(productmatch__slave_product__master_product__gender=gender)).distinct() elif brand_pk: products = ProductSlave.objects.filter(Q(master_product__brand__pk=brand_pk)) brand = Brand.objects.get(pk=brand_pk) elif retailer_pk: retailer = Retailer.objects.get(pk=retailer_pk) products = retailer.productmatch_set.all() else: products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0)) if not retailer_pk: filt = create_filtering(productslaves=products, request=request) elif retailer_pk: filt = create_filtering(productmatches=products, request=request) sorting_selected = request.GET.get("sorter", None) # q\_list is used to store all the Q's # Then they are reduced. And then filtered if "brand" in request.GET: brand_filtering = request.GET.get("brand", None) if brand_filtering: brand_filtering = brand_filtering.split("|") q_list = [] for filter in brand_filtering: if retailer_pk: q_list.append(Q(slave_product__master_product__brand__slug=filter)) else: q_list.append(Q(master_product__brand__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "kategori" in request.GET: category_filtering = request.GET.get("kategori", None) if category_filtering: category_filtering = category_filtering.split("|") q_list = [] for filter in category_filtering: if retailer_pk: q_list.append(Q(slave_product__master_product__product_category__slug=filter)) else: q_list.append(Q(master_product__product_category__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "stoerrelse" in request.GET: size_filtering = request.GET.get("stoerrelse", None) if size_filtering: size_filtering = size_filtering.split("|") q_list = [] for filter in size_filtering: if retailer_pk: q_list.append(Q(slave_product__productmatch__stockitem__size__pk=filter)) else: q_list.append(Q(productmatch__stockitem__size__pk=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "farve" in request.GET: color_filtering = request.GET.get("farve", None) if color_filtering: color_filtering = color_filtering.split("|") q_list = [] for filter in color_filtering: if retailer_pk: q_list.append(Q(slave_product__sorting_color__slug=filter)) else: q_list.append(Q(sorting_color__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "pris" in request.GET: price_filtering = request.GET.get("pris", None) if price_filtering: price_filtering = price_filtering.split("|") q_list = [] if retailer_pk: q_list.append(Q(price__gte=price_filtering[0])) q_list.append(Q(price__lte=price_filtering[1])) else: q_list.append(Q(productmatch__price__gte=price_filtering[0])) q_list.append(Q(productmatch__price__lte=price_filtering[1])) reduced_q = reduce(operator.and_, q_list) products = products.filter(reduced_q) if sorting_selected: if sorting_selected == filt["sorting"][0]["name"]: filt["sorting"][0]["active"] = True if retailer_pk: products = products.annotate().order_by("-price") else: products = products.annotate().order_by("-productmatch\_\_price") elif sorting_selected == filt["sorting"][1]["name"]: if retailer_pk: products = products.annotate().order_by("price") else: products = products.annotate().order_by("productmatch\_\_price") filt["sorting"][1]["active"] = True elif sorting_selected == filt["sorting"][2]["name"]: filt["sorting"][2]["active"] = True if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") else: if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") else: if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") if brand_pk: return render(request, 'page-brand-single.html', { 'products': products, "sorting": filt["sorting"], "filtering": filt["filtering"], "brand": brand, }) elif retailer_pk: return (request, 'page-retailer-single.html', { "products": products, "sorting": filt["sorting"], "filtering": filt["filtering"], "retailer": retailer, }) else: return render(request, 'page-product-list.html', { 'products': products, "sorting": filt["sorting"], "filtering": filt["filtering"] })
Answer link :
https://codehunter.cc/a/django/attributeerror-tuple-object-has-no-attribute-get submitted by code_hunter_cc to codehunter [link] [comments]
Caught AttributeError while rendering: 'WSGIRequest' object has no attribute 'get'
Django
Ok more on forms. I have finally got my form to validate, post and redirect to page it needs to. Now my issue is when I return to the page with the form I get this error:
Caught AttributeError while rendering: 'WSGIRequest' object has no attribute 'get'
Seems the only way to restore it to work is to delete the forms.py replacing what was not working before. Add what is working and I can get it to work ONCE. Any ideas what can cause this issue?
FORMS: class LeadSubmissionForm(forms.ModelForm): """ A simple default form for messaging. """ class Meta: model = Lead fields = ( 'parent\_or\_student', 'attending\_school', 'how\_much', 'year\_of\_study', 'zip\_code', 'email\_address', 'graduate\_year', 'graduate\_month', 'email\_loan\_results' )
VIEWS: @render\_to("lendemain\_views/home.html")def home(request): if request.method == 'POST': form = LeadSubmissionForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("search\_results")) else: form = LeadSubmissionForm(request) testimonials = Testimonial.objects.filter(published=True)[:3] return {'lead\_submission\_form':form, 'testimonials': testimonials,}
MODELS: class Lead(TitleAndSlugModel): """ A lead submitted through the site (i.e. someone that has at-least submitted the search form """ PARENT_OR_STUDENT = get_namedtuple_choices('PARENT\_OR\_STUDENT', ( (0, 'PARENT', 'Parent'), (1, 'STUDENT', 'Student'), )) YEARS_OF_STUDY = get_namedtuple_choices('YEARS\_OF\_STUDY', ( (0, 'ONE', '1'), (1, 'TWO', '2'), (2, 'THREE', '3'), (3, 'FOUR', '4'), )) parent_or_student = models.PositiveIntegerField(choices=PARENT_OR_STUDENT.get_choices(), default=0) attending_school = models.ForeignKey(School) how_much = models.DecimalField(max_digits=10, decimal_places=2) year_of_study = models.PositiveIntegerField(choices=YEARS_OF_STUDY.get_choices(), default=0) zip_code = models.CharField(max_length=8) email_address = models.EmailField(max_length=255) graduate_year = models.IntegerField() graduate_month = models.IntegerField() email_loan_results = models.BooleanField(default=False) def __unicode__(self): return "%s - %s" % (self.email_address, self.attending_school) Again any help is great help. Thank you!!
Answer link :
https://codehunter.cc/a/django/caught-attributeerror-while-rendering-wsgirequest-object-has-no-attribute-get submitted by code_hunter_cc to codehunter [link] [comments]
Django AttributeError 'tuple' object has no attribute 'regex'
Django
I'm using
django 1.8 and having trouble with it. I am trying to import tinymce in my project. When I render it caught
AttributeError: tuple' object has no attribute 'regex'
When I remove the url in url.py it is working. Here is my codes.
url.py from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [ # Examples: # url(r'^$', 'hizlinot.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), (r'^tinymce/', include('tinymce.urls')),]
settings.py """Django settings for hizlinot project.Generated by 'django-admin startproject' using Django 1.8.For more information on this file, seehttps://docs.djangoproject.com/en/1.8/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/1.8/ref/settings/"""# Build paths inside the project like this: os.path.join(BASE\_DIR, ...)import osBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'b-4jipu5t(+)g(2-7g#s=1rs19dhpj-1-!x1b-*v7s85f-m%&q'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'edebiyat', 'tinymce',)MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware',)ROOT_URLCONF = 'hizlinot.urls'TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP\_DIRS': True, 'OPTIONS': { 'context\_processors': [ 'django.template.context\_processors.debug', 'django.template.context\_processors.request', 'django.contrib.auth.context\_processors.auth', 'django.contrib.messages.context\_processors.messages', ], }, },]WSGI_APPLICATION = 'hizlinot.wsgi.application'# Database# https://docs.djangoproject.com/en/1.8/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Internationalization# https://docs.djangoproject.com/en/1.8/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/1.8/howto/static-files/STATIC_URL = '/static/'
Answer link :
https://codehunter.cc/a/django/django-attributeerror-tuple-object-has-no-attribute-regex submitted by code_hunter_cc to codehunter [link] [comments]
How to fix " AttributeError at /api/doc 'AutoSchema' object has no attribute 'get_link' " error in Django
Django
We are practicing an example of REST API on the Internet.
However, the following error occurred.
I tried a way in this link, but the situation hasn't changed.
why swagger raises unclear error - Django from django.contrib import adminfrom django.conf.urls import url, includefrom rest_framework import routersfrom rest_framework_swagger.views import get_swagger_viewimport consumer.apiapp_name = 'consumer'router = routers.DefaultRouter()router.register('consumers', consumer.api.ConsumerViewSet)urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/doc', get_swagger_view(title='Rest API Document')), url(r'^api/v1/', include((router.urls, 'consumer'), namespace='api')),]
Exception Type: AttributeError at /api/docException Value: 'AutoSchema' object has no attribute 'get\_link'
Answer link :
https://codehunter.cc/a/django/how-to-fix-attributeerror-at-api-doc-autoschema-object-has-no-attribute-get-link-error-in-django submitted by code_hunter_cc to codehunter [link] [comments]
AttributeError at /api/updateorder/71 'RelatedManager' object has no attribute 'save'
I am trying to make update api for order objects. OrderItem model is in many to one relationship (with Foreignkey) with Order Model. Also, Billing Details model is one to one relationship with Order model. I am able to update Billing details fields and also Order fields, but cant update the OrderItem fields.
I got this error saying
'RelatedManager' object has no attribute 'save' My models:
class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) # def price(self): # total_item_price = self.quantity * self.item.varaints.price # return total_item_price total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): PAYMENT_TYPE = ( ('cash_on_delivery', 'Cash On Delivery',), ('credit/debit_card', 'Credit/Debit Card',), ('connect_ips', 'Connect IPS',), ('fonepay', 'Fonepay',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details') address = models.CharField(max_length=100,blank=True,null=True) postal = models.CharField(max_length=50,blank=True,null=True) payment_type = models.CharField(max_length=50,blank=True,null=True,choices=PAYMENT_TYPE,default='cash_on-delivery') def __str__(self): return self.address class Meta: verbose_name_plural= "Shipping Address" MY VIEWS: class UpdateOrderView(UpdateAPIView): permission_classes = [AllowAny] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer My serializers: class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['ordered','order_status','order_items','billing_details'] def update(self, instance, validated_data): instance.order_status = validated_data.get('order_status') instance.ordered = validated_data.get('ordered') billing_details_data = validated_data.pop('billing_details',None) if billing_details_data is not None: instance.billing_details.address = billing_details_data['address'] instance.billing_details.save() order_items_data = validated_data.pop('order_items') for order_items_data in order_items_data: instance.order_items.quantity = order_items_data['quantity'] instance.order_items.order_item_status = order_items_data['order_item_status'] instance.order_items.save() #super(OrderUpdateSerializer, self).update(instance.order_items,validated_data).save() #super().save() return super().update(instance,validated_data) There is no error in instance.billing_details.save(), but the same code instance.order_items.save() generates the above error. If I remove instance.order_items.save(), then it works but it doesnt save the updated data in the db.
submitted by KOP79 to djangolearning [link] [comments]
AttributeError at /login 'QuerySet' object has no attribute 'password'
why this error ? the tutorial has same code as typed here but still getting an error.
AttributeError at /login
'QuerySet' object has no attribute 'password'
error is here in this line = flag = check_password(password, customer.password)
def login(request): if request.method == 'GET': return render(request, 'store/login.html') else: email = request.POST.get('email') password = request.POST.get('password') customer = Customer.get_customer_by_email(email) error_message = None if customer: flag = check_password(password, customer.password) if flag: return redirect('homepage') else: error_message = 'Email or Password invalid!' else: error_message = 'Email or Password invalid!' return render(request, 'login.html', {'error':error_message})
submitted by Archode1 to django [link] [comments]
Exception has occurred: AttributeError type object 'Tk' has no attribute 'tk'
Hi I am working on a simple paint program and get this error
Exception has occurred: AttributeError type object 'Tk' has no attribute 'tk'
This is my code
import tkinter as tk window = tk.Tk import pickle Canvas = tk.Canvas canvas = Canvas(window, width=200, height=200) red = 0 green = 0 blue = 0 def sliderUpdate(source): red = redSlider.get() green = greenSlider.get() blue = blueSlider.get() colour = "#%02x%02x%02x" % (red, green, blue) canvas.config(bg=colour) redSlider = tk.Scale(window, from_=0, to=225, command=sliderUpdate) greenSlider = tk.Scale(window, from_=0, to=225, command=sliderUpdate) blueSlider = tk.Scale(window, from_=0, to=225, command=sliderUpdate) canvas = tk.Canvas(window, width=200, height=200) redSlider.grid(row=1, column=1) greenSlider.grid(row=2, column=1) blueSlider.grid(row=3, column=1) canvas.grid(row=2, column=1, columnspan=3) tk.mainloop()
Halp.
submitted by Drwhatishisname to learnpython [link] [comments]
Attributeerror: 'function' object has no attribute 'variable'
https://paste.pythondiscord.com/obunusefop.yaml I know I should try to remove the global statements at line 100 and beyond but I don't know how to get rid of them. Should I use classes or is it possible to solve those bugs? I am stuck I guess /:
submitted by vincentdelegend to learnpython [link] [comments]
AttributeError at /api/updateorder/71 'RelatedManager' object has no attribute 'save'
I am trying to make update api for order objects. OrderItem model is in many to one relationship (with Foreignkey) with Order Model. Also, Billing Details model is one to one relationship with Order model. I am able to update Billing details fields and also Order fields, but cant update the OrderItem fields.
I got this error saying
'RelatedManager' object has no attribute 'save' My models:
class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) # def price(self): # total_item_price = self.quantity * self.item.varaints.price # return total_item_price total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): PAYMENT_TYPE = ( ('cash_on_delivery', 'Cash On Delivery',), ('credit/debit_card', 'Credit/Debit Card',), ('connect_ips', 'Connect IPS',), ('fonepay', 'Fonepay',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details') address = models.CharField(max_length=100,blank=True,null=True) postal = models.CharField(max_length=50,blank=True,null=True) payment_type = models.CharField(max_length=50,blank=True,null=True,choices=PAYMENT_TYPE,default='cash_on-delivery') def __str__(self): return self.address class Meta: verbose_name_plural= "Shipping Address" MY VIEWS: class UpdateOrderView(UpdateAPIView): permission_classes = [AllowAny] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer My serializers: class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['ordered','order_status','order_items','billing_details'] def update(self, instance, validated_data): instance.order_status = validated_data.get('order_status') instance.ordered = validated_data.get('ordered') billing_details_data = validated_data.pop('billing_details',None) if billing_details_data is not None: instance.billing_details.address = billing_details_data['address'] instance.billing_details.save() order_items_data = validated_data.pop('order_items') for order_items_data in order_items_data: instance.order_items.quantity = order_items_data['quantity'] instance.order_items.order_item_status = order_items_data['order_item_status'] instance.order_items.save() #super(OrderUpdateSerializer, self).update(instance.order_items,validated_data).save() #super().save() return super().update(instance,validated_data) There is no error in instance.billing_details.save(), but the same code instance.order_items.save() generates the above error. If I remove instance.order_items.save(), then it works but it doesnt save the updated data in the db.
submitted by KOP79 to django [link] [comments]
AttributeError at /api/logout 'AnonymousUser' object has no attribute 'auth_token'
I have successfully deployed the login view and it returns the token, but when i try to logout it returns the following error. I am new to this so cant figure out the reason.
These are my login and logout views.
class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) #return response.Response(new_data, status=status.HTTP_200_OK) return response.Response({"token": token.key}, status=status.HTTP_200_OK) # return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Logout(GenericAPIView): def get(self, request, format=None): # simply delete the token to force a login request.user.auth_token.delete() return Response(status=status.HTTP_200_OK) path('api/login', views.LoginUserView.as_view(), name='api-login'), path('api/logout', views.Logout.as_view(), name='api-login'),
submitted by KOP79 to djangolearning [link] [comments]
Django AttributeError type object 'CommonInfo' has no attribute 'filepath'
I keep receiving this error when trying to run the makemigrations command to my app in django even though the filepath function is no longer in the CommonInfo model that I have. I looked over my migrations files in my django app and I did notice that one file still referenced CommonInfo.filepath and I assume that is what is causing the issue. When I changed assets.models.CommonInfo.filepath to 'assetsimages' in the 0007_auto_20200611_2202.py file I'm able to migrate successfully. I should note that the CommonInfo class is an abstract base class for 3 other models for this app.
However, I am a bit confused on why this problem occurred. Would anyone be willing to let me know what mistake I made that caused this problem so I can avoid it in the future and if what I did was the correct way to fix it? Below is the model, the migration files that I referenced and the Traceback.
Thank you in advance for any help you may be able to provide. Below is the code, I believe I have everything but if I am missing something please let me know and I will update my question.
Most Recent Migration File
class Migration(migrations.Migration): dependencies = [ ('assets', '0007_auto_20200611_2202'), ] operations = [ migrations.AlterField( model_name='model1', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to='assetimages', verbose_name='Helpful Image'), ), migrations.AlterField( model_name='model2', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to='assetimages', verbose_name='Helpful Image'), ), migrations.AlterField( model_name='model3', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to='assetimages', verbose_name='Helpful Image'), ), ]
Previous Migration file - 0007_auto_20200611_2202.py
class Migration(migrations.Migration): dependencies = [ ('assets', '0006_auto_20200611_2155'), ] operations = [ migrations.AlterField( model_name='model1', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to=assets.models.CommonInfo.filepath, verbose_name='Helpful Image'), ), migrations.AlterField( model_name='model2', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to=assets.models.CommonInfo.filepath, verbose_name='Helpful Image'), ), migrations.AlterField( model_name='model3', name='image', field=models.ImageField(default='assetsimages/defaultpic.png', upload_to=assets.models.CommonInfo.filepath, verbose_name='Helpful Image'), ), ]
models.py
class CommonInfo(models.Model): # def filepath(instance, filename): # today = datetime.now() # today_path = today.strftime("%Y/%m/%d") # return f'assetsimages/{today_path}/{filename}' name = models.CharField("Name", max_length=150) image = models.ImageField("Helpful Image", default='assetsimages/defaultpic.png', upload_to='assetimages') datecreated = models.DateField("Date Created", auto_now_add=True) notes = models.TextField("Additional Details", blank=True) def save(self): super().save() img = Image.open(self.image.path) if img.height > 400 or img.width > 400: output_size = (400, 400) img.thumbnail(output_size) img.save(self.image.path) class Meta: abstract = True class model1(CommonInfo): .... class model2(CommonInfo): .... class model3(CommonInfo): ....
Traceback
Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/djangoproject/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/djangoproject/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/djangoproject/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 206, in build_graph self.load_disk() File "/djangoproject/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 108, in load_disk migration_module = import_module(migration_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "/djangoproject/assets/migrations/0007_auto_20200611_2202.py", line 7, in class Migration(migrations.Migration): File "/djangoproject/assets/migrations/0007_auto_20200611_2202.py", line 17, in Migration field=models.ImageField(default='assetsimages/defaultpic.png', upload_to=assets.models.CommonInfo.filepath, verbose_name='Helpful Image'), AttributeError: type object 'CommonInfo' has no attribute 'filepath'
submitted by czrs113 to learndjango [link] [comments]
AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute
Python
The following code:
Base = declarative_base()engine = create_engine(r"sqlite:///" + r"d:\foo.db", listeners=[ForeignKeysListener()])Session = sessionmaker(bind = engine)ses = Session()class Foo(Base): __tablename__ = "foo" id = Column(Integer, primary_key=True) name = Column(String, unique = True)class Bar(Base): __tablename__ = "bar" id = Column(Integer, primary_key = True) foo_id = Column(Integer, ForeignKey("foo.id")) foo = relationship("Foo")class FooBar(Base): __tablename__ = "foobar" id = Column(Integer, primary_key = True) bar_id = Column(Integer, ForeignKey("bar.id")) bar = relationship("Bar")Base.metadata.create_all(engine)ses.query(FooBar).filter(FooBar.bar.foo.name == "blah") is giving me this error:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with FooBar.bar has an attribute 'foo' Any explanations, as to why this is happening, and guidance to how such a thing could be achieved?
Answer link :
https://codehunter.cc/a/python/attributeerror-while-querying-neither-instrumentedattribute-object-nor-comparator-has-an-attribute submitted by code_hunter_cc to codehunter [link] [comments]
AttributeError at /Post/ 'Post' object has no attribute 'get'
Hi. I have this problem "AttributeError at /Post/ 'Post' object has no attribute 'get'"
and have no clue why it happens. I am using a django filter and it's my first time trying "foreignkey"
There are two simple models and Post_price is the one that has a foreignkey attribute.
Thank you for your help in advance.
class Post(models.Model):
name= models.CharField(max_length=11,default='')
class Post_price(models.Model):
post= models.ForeignKey('Post', blank=True, null=True, on_delete=models.SET_NULL)
content= models.IntegerField(default='')
class PostFilter(django_filters.FilterSet):
class Meta:
model = Post
fields = {
'name': ...(I just handled it well)
def Post(request):
s = Post.objects.all()
aq = PostFilter(request.GET, queryset=s)
return render(request,'app/Post.html',{'s':aq})
path('Post/',Post,name='Post'),
submitted by nimbusmettle to django [link] [comments]
meet a bug of dreambooth train , 'Options' object has no attribute 'tag_drop_out'
when i train model with dreambooth extension, i meet a question above, does anybody fix it.
Traceback (most recent call last): File "/home/stdfusestable-diffusion-webui/extensions/sd_dreambooth_extension/dreambooth/train_dreambooth.py", line 972, in main for step, batch in enumerate(train_dataloader): File "/home/stdfusestable-diffusion-webui/venv/lib/python3.10/site-packages/accelerate/data_loader.py", line 376, in __iter__ current_batch = next(dataloader_iter) File "/home/stdfusestable-diffusion-webui/venv/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 628, in __next__ data = self._next_data() File "/home/stdfusestable-diffusion-webui/venv/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 671, in _next_data data = self._dataset_fetcher.fetch(index) # may raise StopIteration File "/home/stdfusestable-diffusion-webui/venv/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 58, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/stdfusestable-diffusion-webui/venv/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 58, in data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/stdfusestable-diffusion-webui/extensions/sd_dreambooth_extension/dreambooth/train_dreambooth.py", line 422, in __getitem__ example["instance_prompt"] = self.text_getter.create_text(instance_prompt, File "/home/stdfusestable-diffusion-webui/extensions/sd_dreambooth_extension/dreambooth/finetune_utils.py", line 41, in create_text if shared.opts.tag_drop_out != 0: File "/home/stdfusestable-diffusion-webui/modules/shared.py", line 412, in __getattr__ return super(Options, self).__getattribute__(item) AttributeError: 'Options' object has no attribute 'tag_drop_out' Exception while training: 'Options' object has no attribute 'tag_drop_out' Allocated: 4.0GB Reserved: 4.1GB
submitted by jackaluo to StableDiffusion [link] [comments]
Noob question: script only runs in first instance of kernal – AttributeError 'NoneType' object has no attribute 'literal_eval' on subsequent runs
Hi All.
As the title suggests, I'm learning spaCy and I've run into an issue right off the bat. I've been googling for a couple hours and not been able to solve it.
So, I have a very basic script that runs as expected in the first instance of the kernal, "In [1]:".
import spacy nlp=spacy.load("nl_core_news_sm") nlp = spacy.load('nl_core_news_sm') ruzie = open("ruzie.txt", "r").read().decode('utf-8') ruzie = nlp(ruzie) print(ruzie) for token in ruzie: print str(token.text), str(token.pos_), str(token.dep_)
Any subsequent runs returns the error:
AttributeError: 'NoneType' object has no attribute 'literal_eval'
Here's the full traceback:
Traceback (most recent call last): File "", line 1, in runfile('/home/BaaBob/Python/2/nlp/ruzie_spacy.py', wdir='/home/bob/Python/2/nlp') File "/uslib/python2.7/dist-packages/spydeutils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/uslib/python2.7/dist-packages/spydeutils/site/sitecustomize.py", line 94, in execfile builtins.execfile(filename, *where) File "/home/BaaBob/Python/2/nlp/ruzie_spacy.py", line 9, in nlp=spacy.load("nl_core_news_sm") File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/__init__.py", line 27, in load return util.load_model(name, **overrides) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/util.py", line 134, in load_model return load_model_from_package(name, **overrides) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/util.py", line 155, in load_model_from_package return cls.load(**overrides) File "/home/BaaBob/.local/lib/python2.7/site-packages/nl_core_news_sm/__init__.py", line 12, in load return load_model_from_init_py(__file__, **overrides) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/util.py", line 193, in load_model_from_init_py return load_model_from_path(data_path, meta, **overrides) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/util.py", line 176, in load_model_from_path return nlp.from_disk(model_path) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/language.py", line 811, in from_disk util.from_disk(path, deserializers, exclude) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/util.py", line 633, in from_disk reader(path / key) File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/language.py", line 801, in deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk(p, exclude=["vocab"]) File "tokenizer.pyx", line 391, in spacy.tokenizer.Tokenizer.from_disk File "tokenizer.pyx", line 435, in spacy.tokenizer.Tokenizer.from_bytes File "/home/BaaBob/.local/lib/python2.7/site-packages/spacy/compat.py", line 178, in unescape_unicode return ast.literal_eval("u'''" + string + "'''") AttributeError: 'NoneType' object has no attribute 'literal_eval'
It seems to ahve something to do with the line "nlp=spacy.load("nl_core_news_sm")", (line 9 in the script), but I don't understand what's wrong. Or is this the desired behavior? It's rather annoying to have to restart the kernel each time. If it makes any difference, I'm working in Python 2.7, Spyder 3.2.5, Linux Mint 19.1.
Have I done something wrong? Is there a way to not have to restart the kernel each time in order to get the script to run as it does "In [1]:"?
Edit: Now tried on another machine (same OS though) and the behavior is the same. I've looked at some other code examples and I don't see anything particularly wrong with mine. Maybe a package missing or something
submitted by BaaBob to spacynlp [link] [comments]
(Exception has occurred: AttributeError 'dict' object has no attribute 'lab') in a little maze game I'm exercising one.
Class :
class Labyrinthe(Carte): """Classe représentant un labyrinthe.""" def __init__(self, nom_carte, lab): super().__init__(nom_carte) self.lab = lab self.robot = "X" self.obstacles = "O" self.porte = "." self.sortie = "U" self.commande = ["N", "S", "E", "O", "Q"] # ...
Dictionnary I use as a map :
dictionnary = { 1 : "OOOOOOOOOOOOOOOOOOOO", 2 : "OXO . O O . O", 3 : "O.O O O O O O", 4 : "O O O O O O O", 5 : "O.O O . O O O", 6 : "O O O OOOOOO O O", 7 : "O O O O O", 8 : "O O OOOOOOOOOO O", 9 : "O.O . O O", 10 :"O O O O O", 11 :"O O O O O", 12 :"O O.O O O", 13 :"O.O . O O", 14 :"O O O O O", 15 :"O O O O O", 16 :"O O O O O", 17 :"O O O O O", 18 :"O.O O O O", 19 :"O O O U", 20 :"OOOOOOOOOOOOOOOOOOOO" }
Functions :
#To get the position = (key, index in string) def get_position(recherche, dictionnaire): coordonnee = None #Probleme avec la variable coordonne for key, value in dictionnaire.items(): if recherche in dictionnaire[key]: coordonnee = (key, dictionnaire[key].index(recherche)) return coordonnee
#To get the position of all "." in the map and store them as tuple in list def get_c(recherche, dictionnaire): #Probablement devoir changer dans ma classe aussi list_c = [] c = None for key, value in dictionnaire.items(): if recherche in dictionnaire[key]: c = (key, dictionnaire[key].index(recherche)) list_c.append(c) return list_c
#To get movement done... #Awfully repetitive def vers(direction, dico, liste_position_portail, x = "X", depla = 1): for i in range(depla) : coor_x = get_position(x, dico) print(coor_x) #VERS LE NORD if direction.upper() == "N": ncoor = (coor_x[0] - 1, coor_x[1]) # print(ncoor) if dico[ncoor[0]][ncoor[1]] == "O": print("OBSTACLES !!") else: val = [] for element in dico[ncoor[0]]: val.append(element) val[ncoor[1]] = x val = "".join(val) dico[ncoor[0]] = val val = [] for element in dico[coor_x[0]]: val.append(element) val[coor_x[1]] = " " val = "".join(val) dico[coor_x[0]] = val #VERS LE SUD if direction.upper() == "S": ncoor = (coor_x[0] + 1, coor_x[1]) # print(ncoor) if dico[ncoor[0]][ncoor[1]] == "O": print("OBSTACLES !!") else: val = [] for element in dico[ncoor[0]]: val.append(element) val[ncoor[1]] = x val = "".join(val) dico[ncoor[0]] = val val = [] for element in dico[coor_x[0]]: val.append(element) val[coor_x[1]] = " " val = "".join(val) dico[coor_x[0]] = val #VERS L'EST if direction.upper() == "E": ncoor = (coor_x[0], coor_x[1] - 1) # print(ncoor) if dico[ncoor[0]][ncoor[1]] == "O": print("OBSTACLES !!") else: val = [] for element in dico[ncoor[0]]: val.append(element) val[ncoor[1]] = x val = "".join(val) dico[ncoor[0]] = val val = [] for element in dico[coor_x[0]]: val.append(element) val[coor_x[1]] = " " val = "".join(val) dico[coor_x[0]] = val #VERS L'OUEST if direction.upper() == "O": ncoor = (coor_x[0], coor_x[1] + 1) # print(ncoor) if dico[ncoor[0]][ncoor[1]] == "O": print("OBSTACLES !!") else: val = [] for element in dico[ncoor[0]]: val.append(element) val[ncoor[1]] = x val = "".join(val) dico[ncoor[0]] = val val = [] for element in dico[coor_x[0]]: val.append(element) val[coor_x[1]] = " " val = "".join(val) dico[coor_x[0]] = val relab(liste_position_portail, dico) printd(dico) return dico return dico
How I run it:
- Entry can only be of maximum length of 2 and the first part being a string while the other an integer EX : s1 works, 11 or ss don't.
- the str for the direction and the int for the number of time you go In that direction
- action_split[0] -> the str part, action_split[1] -> the int part (if there's one)
-Simple command
lab_carte_a_jouer.lab = vers(action_split[0], lab_carte_a_jouer.lab,liste_position_portail, lab_carte_a_jouer.robot)
This one work well with simple command like s or n, but when I try with action_split[1] (EX : s2); I get error (
Exception has occurred: AttributeError 'dict' object has no attribute 'lab')
-double command
lab_carte_a_jouer = vers(action_split[0], lab_carte_a_jouer.lab,liste_position_portail, lab_carte_a_jouer.robot, action_split[1])
I've gone through StackOverflow, I think I understand what this error mean but I don't know why it occur in my case.
They said
AttributeError
is an exception thrown when an object does not have the attribute you tried to access.
I thought the problem might come when there's no "X" or any other things missing in the maze when I'm trying to move it again, but figured that when I repeat multiple time simple action like "s" to go south it works, but when I put the very same action inside a loop to repeat it two times like if I doing ."s2" the same error come out.
In hope that somebody will be able to point out what I did wrong.
submitted by VoodD to learnpython [link] [comments]
Why do i get AttributeError , 'Document' object has no attribute 'read' ?
I have wesbite where i upload .docx files successfully, edit them and when trying to save them i get AttributeError at /my_blanks/2/, i want to save file in another root called
PRIVATE_STORAGE_ROOT 'Document' object has no attribute 'read' . Note i that i want to save them
NOT with default in MEDIA_ROOT ,
BUT in PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, 'private')
views.py def edit_files(request, file_id): instance = get_object_or_404(DocFile, id=file_id) exact_file = Document(instance.document) .....
# So Here i am editing word document with some processes docx_words_replace(exact_file, regex1, replace) docx_words_replace(exact_file, regex2, replace)
if len(inputs_list) != 0: contract_name = inputs_list[0] fs2 = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) fs2.save(contract_name + "docx", exact_file)
# it says the Error is in this line return render(request, 'edit_files.html', context={'variables': variables, "form": my_form})
settings.py ......
STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, 'private')
urls.py urlpatterns = [ ...... ]
if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
please help me to solve this issue Thank you
submitted by Grigor_1 to django [link] [comments]
D:\Python>python TextGenOut.py File "TextGenOut.py", line 72 predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval() ^ IndentationError: unexpected indent D:\Python>python TextGenOut.py 2018-09-16 21:50:57.008663: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to ... tf.multinomial returns a Tensor object that contains a 2D list with drawn samples of shape [batch_size, num_samples].Calling .eval() on that tensor object is expected to return a numpy ndarray.. Something like this: predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval() You also need to ensure that you have a session active (doesn't make a lot of sense otherwise): 今天遇到一个非常奇怪的问题,百度和谷歌也搜不到,大佬分分钟帮我解决问题。 在做django的定时任务开发时 运行:python manage.py celery worker -l info和python manager.py celery worker -l info报错: AttributeError: ‘CeleryCommand’ object has no attribute ‘preload_options’ 大佬告诉我是源码问题, 错误原因是preload_options ... I am trying to run some code to create an LSTM model but i get an error: AttributeError: module 'tensorflow' has no attribute 'get_default_graph' My code is as follows: from keras.models import Turns out this issue is also happening in a different project here at Relativity, one which does not use importlib and instead just uses a certain arrangement of import statements in a pytest suite. 3. Data model¶ 3.1. Objects, values and types¶. Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.) Les dimanches 25 décembre et 1 er janvier, le Château et le domaine de Trianon sont fermés. Les Jardins et le Parc sont ouverts et gratuits tous les jours. Pendant les fêtes, découvrez la programmation exceptionnelle avec Le Parcours du Roi pour une visite spectacle dans la Galerie des Glaces et le Grand Parcours Louis XV avec une collation chez Ore Ducasse avant ou après la visite. compile (source, filename, mode, flags = 0, dont_inherit = False, optimize =-1) ¶. Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.. The filename argument should give the file from which the ... Just an addition to others looking for an answer for Tensorflow v2. As the others have mentioned, you can use the back-compatability to v1. But Tensorflow v2 does actually come with its own implementation of this. The argument bytes must either be a bytes-like object or an iterable producing bytes.. The byteorder argument determines the byte order used to represent the integer, and defaults to "big".If byteorder is "big", the most significant byte is at the beginning of the byte array.If byteorder is "little", the most significant byte is at the end of the byte array.
[index]
[269] [888] [933] [2] [833] [452] [854] [600] [231] [226]
#