Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't import Bootstrap scss files in Django project
I'm trying to integrate bootstrap into my Django project and want to overwrite some BS classes as per the documentation. Now in my custom base.scss I got # base.scss @import "bootstrap/scss/bootstrap.scss"; and it doesn't find the dir, why? Do I have to work with npm? (never worked with scss before) # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ['static'] -
How to delete all the values of one particular column Django
I want to delete of all values of one particular column. I tried this way , now i can not do runserver application = models.CharField(null=True, editable=False ) -
my token sends user_id How I can get it by localStorage in Angular?
I need help trying to figure it out, i am using django as backend and Angular as frontend. My django backend pass a token so it can be acessed in frontend by login. login.ts onLogin() { this.service.loginUser(this.input).subscribe( response => { console.log(response) this.jwttoken.setToken(response['token']); this.jwttoken.getItem(response); this.router.navigate(['dashboard']); }, error => { console.log('error', error); } i save it in a localstorage that can be acessed on my service jwttoken service jwtToken : string decodedToken: {[key: string]: string} public storage: Storage; constructor() { this.storage = window.localStorage; } setToken(token: string){ if (token) { this.jwtToken = token; } } getItem(key: string) { if(this.storage){ localStorage.setItem('token',(key)); } return null; } i need to have my user id that i can see on my web browser console. {"token":"[object Object]","d34330659cba7cf64e8414f83aa6522f55b0f978":"d34330659cba7cf64e8414f83aa6522f55b0f978","[object Object]":"{"token":"d34330659cba7cf64e8414f83aa6522f55b0f978","user_id":1,"email":"admin@admin.com"}"} this is where i need to access my user id, so i can send it to my html file export class RegularComponent implements OnInit { patient_code: any; number_tumor: any; tumor_size: any; tumor_volume: any; biopsy_date: any; hp_lote_number: any; closeResult: string; userlists: any; user_id: any; constructor(private service: SharedService, private modalService: NgbModal, private jwtstorage: JWTTokenServiceService) { } localstorage = JSON.stringify(this.jwtstorage.storage).replace(/\\/g, ""); ngOnInit() { // this.getUserlist(); console.log(this.localstorage); } // getUserlist() { // let observable = this.service.getUsersList(); // observable.subscribe((data) => { this.userlists = data; console.log(data); … -
Filtering duplicates in queryset based on UUIDField
I'm running into some problems when pulling a specific list of objects from my db. I'm picking up python/django after quite a bit of time off and feeling pretty rusty. As an exercise I am building an app that allows a group of friends to 'draft' season tickets, eg. take turns selecting which games you want to attend until all the tickets are distributed. The way I've chosen to go about this is to have one db model that contains a dump of all games for an entire season (SportSeason) and a db that contains draft information (TicketDraft). As there will be many rows (to track ticket/game selection) for each draft session, I've created a UUID field for logically grouping the rows that belong to the same draft. models.py class SportSeason(models.Model): year = models.IntegerField(default=None) sport = models.CharField(max_length=10, default=None) home = models.CharField(max_length=10) visitor = models.CharField(max_length=10) date = models.DateTimeField(auto_now=False) class Meta: app_label = 'ticket_draft' class TicketDraft(models.Model): tt_group = models.IntegerField() tt_status = models.CharField(max_length=10) # available, selected tt_owner = models.CharField(max_length=30) gm_date = models.DateTimeField(auto_now=False, null=True) team_home = models.CharField(max_length=10) team_visitor = models.CharField(max_length=10) draft_year = models.IntegerField() ssn_create = models.DateTimeField(auto_now=True) ssn_owner = models.CharField(max_length=30) ssn_status = models.CharField(max_length=10) # active, cancelled, complete ssn_ident = models.UUIDField(default=uuid.uuid4, editable=False) On the home page … -
argument after ** must be a mapping, not str error, using celery but not without using it
I have a simple send_email_task() function. @shared_task def send_email_task(subject, message, email_from, recipient_list): print("Email Sent", f"{subject, message, email_from, recipient_list}") send_mail(subject, message, email_from, recipient_list) return None I'm calling it in the views like : send_email_task.apply_async( subject, message, email_from, recipient_list) But I'm facing this error, I don;t understand what it is, I tried reading other answers on stack overflow but not able to find how to handle this problem. -
Dynamically updating models in Django (Javascript, HTML and Python)
am trying to dynamically update a file for a django model but am having difficulty figuring it out: here is the code I have so far: Detail.html <table class="cert-table"> <tr> <th>Dpt:</th> <th>Licence:</th> <th>Exp. Date:</th> <th>Upload Date:</th> <th>File:</th> <th></th> <th></th> <th></th> </tr> <tr> {% for cert in list_of_certs %} <td>{{ cert.department }}</td> <td>{{ cert.licence }}</td> <td>{{ cert.exp }}</td> <td>{{ cert.ul_date }}</td> <td>{{ cert.file }}</td> <div class="upload-tds"> <td> <button class="btn sitebtn{{cert.id}}" id="sitebtn{{cert.id}}" onclick="openUpdateCert()">Update File</button> </td> <td> <div class="upload-tds-hidden" id="form-update-cert-js"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ cert.file }} <button type="submit">Create</button> </form> </div> </td> </div> </div> </tr> {% endfor %} </table> main.js: function openUpdateCert() { var x = document.getElementById("form-update-cert-js"); var z = document.getElementById("sitebtn{{cert.id}}"); if (x.style.display === "block") { x.style.display = "none"; z.style.display = "block"; } else { x.style.display = "block"; z.style.display = "none"; } } models.py from django.db import models from django_resized import ResizedImageField class Site(models.Model): name = models.CharField(max_length=25) picture = ResizedImageField(size=[319, 305], upload_to='images/', blank=True, null=True) location = models.CharField(max_length=20) def __str__(self): return self.name class Certificate(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE, blank=True, null=True, editable=False) department = models.CharField(max_length=4) licence = models.CharField(max_length=50) exp = models.DateField() ul_date = models.DateField(auto_now_add=True) file = models.FileField(blank=True, null=True) def __str__(self): return self.licence forms.py from django.contrib.auth.forms import AuthenticationForm, UsernameField from .models import Site, Certificate … -
How to add string var inside php code in python
I saw a php code to decrypt an encrypted AES-256-CBC string in PHP. But I'm using python, so I looked for a way to add a PHP script inside python. This is how I did it as I saw from this link: def decrypt(encrypted_data, password): code = """<?php function decryptionM($data, $key) { $secretkey = str_pad($key, 32, '*'); echo('secretkey: '); echo($secretkey); echo("\n"); $iv_with_ciphertext = base64_decode(str_replace('plusencr', '+', $data)); echo('iv_with_ciphertext: '); echo($iv_with_ciphertext); echo("\n"); $iv_length = openssl_cipher_iv_length('AES-256-CBC'); echo('iv_length: '); echo($iv_length); echo("\n"); $iv = substr($iv_with_ciphertext, 0, $iv_length); echo('iv: '); echo($iv); echo("\n"); $ciphertext = substr($iv_with_ciphertext, $iv_length); echo('ciphertext: '); echo($ciphertext); echo("\n"); $text = openssl_decrypt($ciphertext, 'aes-256-cbc', $secretkey, OPENSSL_RAW_DATA, $iv); echo('text: '); echo($text); echo("\n"); $asArr = explode(',', $text); echo('asArr: '); echo($asArr); echo("\n"); foreach ($asArr as $val) { $tmp = explode('=', $val); echo('tmp: '); echo($tmp[0]); echo("\n"); $finalArray[trim($tmp[0])] = str_replace('+', '', $tmp[1 ]); } echo('finalArray: '); echo($finalArray); echo("\n"); return $finalArray; } echo decryptionM(""" + encrypted_data + """, """ + password + """); ?> """ res = php(code.encode()) return res But the line echo decryptionM(""" + encrypted_data + """, """ + password + """); is outputting an error: [2022-03-24 02:06:50,202: WARNING/MainProcess] b"PHP Parse error: syntax error, unexpected '=', expecting ')' in Standard input code on line 55\n\nParse error: syntax error, unexpected '=', … -
Django Rest Framework - TypeError: reverse() got an unexpected keyword argument 'request'
I have a number of tests written for a django application, and all tests must pass in order for automated deployment to take place. Unexpectedly, a number of tests began failing, none of which had been touched with the latest commit. The error comes from a serializer that uses django rest frameworks 'reverse' function. # serializers.py from rest_framework.reverse import reverse from rest_framework.serializers import ModelSerializer, SerializerMethodField from my_app.models import ConfigVersion class ConfigVersionMetadataSerializer(ModelSerializer): class Meta: model = ConfigVersion fields = ('id', 'config', 'config_name', 'hyperlink', 'version') hyperlink = SerializerMethodField() def get_hyperlink(self, obj): return reverse( 'versions-list', kwargs={ 'configurations_pk': obj.config.id, 'version_pk': obj.id }, request=self.context['request'] ) All tests that call this serializer now fail with error TypeError: reverse() got an unexpected keyword argument 'request' Django rest frameworks documentation states that 'request' is an included and recommended argument https://www.django-rest-framework.org/api-guide/reverse/. After reviewing the documentation, I have searched for dependency version changes in the build logs to see if there were code changes, but the only dependency update is presumably unrelated (pytz). I'm pretty confused by the source of this issue, since tests were working properly a couple days ago and there don't appear to be any changes to the tests, serializers, views, or required libraries. -
Only able to run tests from dir containing manage.py while using docker shell
I have been trying to run a Django test suite in a running docker container, but using docker exec or even entering the docker shell and running the tests from outside their dir results in the test runner failing to find anything. docker exec -it \<container_name\> <project>/manage.py test doesn't find any tests. However, if I docker exec -it \<container_name\> /bin/bash and then navigate to <project> and run python manage.py test this runs the tests. If I try to do the same (enter shell) but from outside the <project> dir (e.g. python <project>/manage.py test) the test runner finds 0 tests again. I am very confused by these results to say the least, as it seems like these commands should all evoke the same behavior -
How to handle multi-level permissions in Django REST Framework?
I'm attempting to create a DRF API that can handle multi-level permissions. I have Users, Clients, and Brands. Clients can contain one or many Brands. The way I'm trying to get User Permissions to work is a User can have access to one or many Clients. If given access to that Client they will also be given limited access to one or many Brands within that Client. I can't wrap my head around how to manage the permissions on this. Does this need to object instance level permissions? or is there another way to organize it? I'm trying to avoid 3rd party packages, but I have seen several people mention django-guardian. I understand this is a very general question. So I appreciate any type of response on this. Thank you. -
How to enable CORS in Python Dash
I've seen that you can enable CORS for Flask (How to enable CORS in flask), but I have a Dash app and I want to enable something like headers = { 'Access-Control-Allow-Origin':'*' } Does anyone know how to do it? -
Muti-array result in models django
I have a second instance of database called slave_db this database have tables like this, the profile and the details of lands I created a model.py for these from django.db import models class Fields(models.Model): field_id = models.IntegerField() field_name = models.CharField(max_length=50) class Meta: managed = False db_table = 'tbl_fields' class Profile(models.Model): profile_id = models.IntegerField() name = models.CharField(max_length=20) fields = models.OneToOneField(Fields) class Meta: managed = False db_table = 'tbl_profile' I also have my serialize.py from rest_framework import serializer from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['profile_id','control_no','name','fields'] then in my views.py from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.generics import get_object_or_404 from .models import Profile from .serializers import Profile Serializer @api_view(['GET']) def ProfileDetails(request): control_no = request.GET.get("control_no") details = Profiles.objects.using("slave_db").select_related("fields").filter(control_no = control_no) detailSerializer = ProfileSerializer(details, many=True) print(detailSerializer) now the result is [ { "profile_id": 1, "control_no": "8-001", "name": "Foo", "fields": "8-001" }, { "profile_id": 1, "control_no": "8-002", "name": "Bar", "fields": "8-002" }, ] how can i get the data properly and have a result like this?. [ { "profile_id": 1, "control_no": "8-001", "name": "Foo", "fields": [ { "field_id": 1 "field_name": "Charlie Land" }, { "field_id": 2 "field_name": "Alpha Land" } ] … -
Field 'id' expected a number but got 'None'
I have a little problem. I try to add some values on my table from Mongodb, using django and the admin page. I wrote in models.py (the code is basic, because I am learning and this was the first step from a tutorial that I saw): from datetime import date from django.db import models class activity_stage(models.Model): date = models.TextField() start = models.TextField() stop = models.TextField() distance = models.TextField() calories = models.TextField() steps = models.TextField() In admin.py from django.contrib import admin from .models import activity_stage admin.site.register(activity_stage) But on my admin page, it doesn't attribute to me the index number (list of objects from admin page). I tried to delete the objects, but I receive this error: Field 'id' expected a number but got 'None'. My table from my database it's look like this: Mongodb_collection. I named the class from the models with the same name as the collection from mongo. At the end, I want to import on my page an excel file and I found something that probably can help me. But I don't know how to solve my error. I think that i solve the problem I can after add the objects from admin page in my db. -
Django async model update not being enacted
The SQL update does not seem to be being enacted upon, and no errors are being thrown either. Below is a simplified version of my code. For context, the "choice" field in the model is a Boolean Field with a default of False, and a user may (ideally) change this by sending a JSON package with the "CHOICE" event and "Yes" message. consumers.py import json from channels.generic.websocket import AsyncJsonWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] #Websockets connection code async def disconnect(self): #Websockets disconnect code async def receive(self, text_data): response = json.loads(text_data) event = response.get("event", None) message = response.get("message", None) if event == "CHOICE": room_set = await sync_to_async(Room.objects.filter)(room_code=self.room_code) room = await sync_to_async(room_set.first)() if (not room.choice) and message["choice"] == 'Yes': sync_to_async(room_set.update)(choice=True) #line seems to not be working elif room.choice and message["choice"] == 'No': sync_to_async(room_set.update)(choice=False) #code to send message to group over Websockets #code regarding other events async def send_message(self, res): #Websockets send message code I've tried to only include the relevant code here, but if more is needed please let me know. Thanks in advance! -
How to deal with lots of duplicated data in DB?
I'm currently building a database for a photography project and I'm having troube to decide this: There are about 3 million photographs and I'd like this to keep working even with 15 million. They are stored on disk and with paths in the DB. All of those need a caption, but captions are highly duplicated. On Average about 10 photos have exactly the same caption (same creator, same title, same date). Is it better to create one model? class Photo(models.Model): file = models.FileField() headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() Or should I make 2 models even if it means having to create copies manually when one photo out of a group gets a different caption afterwards? class Photo(models.Model): file = models.FileField() metadata = models.ForeignKey('Metadata') def set_metadata(self, metadata): self.metadata = Metadata.models.get_or_create(metadata) class Metadata(models.Model): headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() The most common task will be to search for pictures based on their metadata. Is creating an extra model and reducing the db table by factor 10 worth it? Or does it just introduce unnessesary complications with no benefits in performance? Thank you for your help! -
How to change datatables language on click of a button in django?
I already have the language change of my page when clicking a button, the problem is that how do I do it with dataTables? It's rare to change the entire language page and dataTables doesn't sync with the language change button. Does anyone have an idea how to do that? index.html <form action="{% url 'set_language' %}" method="POST" class="form-inline"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <div> <select name="language" id="" class="form-control"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} {{language.code}} </option> {% endfor %} </select> </div> <input type="submit" value="{% trans 'Go' %}" class="btn btn-danger"> </form> js <script> $(document).ready( function () { $('#datatable').DataTable({ ); } ); </script> -
Django - How to create and migrate two tables for development and production on same database? (prefix in front when running as dev)
I am trying to have two tables in one database like below based on development and production environment. development dev_my_comments production my_comments I tried using environment variable while declaring table like below class Data_Comments(models.Model): class Status(models.IntegerChoices): GENERAL = 0 YELLOW = 1 RED = 2 ord_no = models.ForeignKey(Data_Import, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=500, null=True) strike_comment_type = models.IntegerField(choices=Status.choices, default=0) strike_date = models.DateTimeField(auto_now=True, blank=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='comments_user') class Meta: db_table = 'my_comments' if settings.ENV_TYPE == 'PRO' else 'dev_my_comments' app_label = "my_app" by using this option, make migrations just renames existing tables instead of creating new... (wanted to have both the tables and want to migrate changes on both tables) is there something I am missing to make it work? -
django forms.DateInput not responding to dd/mm/yyyy format
currently I'm having issues with getting input validation working as expected with Django DateInput As per my understanding, the default format for DateInput is "%Y-%m-%d" if left untouched, however explicitly setting the format to "%d/%m/%Y" still causes validation errors. Here are some examples Input: 25/03/1981 Expected: Valid date (We expect this value to not trigger a validation error) Actual: Enter a valid date. Input: 1/07/1981 Expected: Date parsed as 1st July Actual: Date parsed as 7th January (i.e date and month are parsed in place of each other) forms.py class PatientForm(ModelForm): class Meta: # Make form look nice from here model = Patient fields = ('PAS_number', 'first_name', 'middle_name', 'surname', 'DOB', 'priority_code', 'patient_information', 'patient_status') widgets = { 'PAS_number': forms.NumberInput( attrs={'class': 'form-control'}), 'first_name': forms.TextInput( attrs={'class': 'form-control'}), 'middle_name': forms.TextInput( attrs={'class': 'form-control'}), 'surname': forms.TextInput( attrs={'class': 'form-control'}), 'DOB': forms.DateInput( format=('%d/%m/%Y'), attrs={'class': 'form-control'}), 'priority_code': forms.Select( attrs={'class': 'form-control'}), 'patient_information': forms.Textarea( attrs={'class': 'form-control'}), 'patient_status': forms.Select( attrs={'class': 'form-control'}), } -
Which better operating system (windows or linux) to use for python app on azure app service
I'am confused which opertaing system to use for my django app to deploy it on azure cloud I can't find enough information to take the best decision -
Django RestFramework nested serializer field many=false
how can I create a nested serializer field without using (many=True)? The following code works fine: from music.models import Track, Album from rest_framework import serializers class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album However the I cannot change the json payload as it comes from a 3rd part app, and the field "tracks" in the example should be "track" and POST just one object. This json works fine: { "album_name": "Black Album", "artist": "Metallica", "tracks": [ { "order": 1, "title": "Enter Sandman", "duration": 245 }, { "order": 2, "title": "Sad but True", "duration": 264 }, { "order": 3, "title": "The Unforgiven", "duration": 159 } ] } but I need to get this json working, one object, without the square brackets []: { "album_name": "Black Album", "artist": "Metallica", "tracks": { "order": 1, "title": "Enter Sandman", "duration": 245 } } I've tried to remove the (many=True) but I receive either the following errors: Got AttributeError when attempting to get a value for field `order` on serializer … -
Redirect a user from www.abcd.in to www.abcd.com with nginx and django app automatically
I have a unique query: There is a website is hosted on Digitalocean Droplet with a certain IP. There is a abcd.com domain and a abcd.in domain. Currently the nginx vhost is containing the abcd.com domain ServerName with the IP of the droplet. Also both abcd.com and abcd.in have the same IP addresses configured by the previous server admin. I want a way such that when I open up abcd.in domain, it should redirect to abcd.com automatically. What is the change required to be done in the Nginx server block for the same ? Or can I change directly on digitalocean itself in it's Domain Configuration. The base stack is Django App with Python Stack. -
How can I link styles.scss file with django templates?
I just facing a silly problem. I can't link styles.scss file with django template from the static folder. This method not working here {% static '/css/style.scss' %}. Now, what will have to do for linking .scss file? -
Saving Django data from forms to sqlite database
What I have here is basically recipes which have to be saved in a database with many to one relationship between hops, fermentables etc. and main recipe which includes the name type and so on. What we have is the user fills in the forms and then with this information we are calling this in the view.py file: def saveRecipe(request): try: data=json.loads(request.read()) recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Now this leads us to the models.py file: class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe @classmethod … -
django unit test admin StackedInline with post function using reverse function
I'm working on unit test and want to test the admin dashboard where I have a user information with inline models. I don't want how to fill data to those models. this is test for the admin: def test_user_admin__create(superuser, client): client.force_login(superuser) phone_number = factory.Faker._get_faker().phone_number() password = factory.Faker._get_faker().password() response = client.post( reverse("admin:users_user_add"), { "phone_number": phone_number, "password1": password, "password2": password, "is_superuser": True, "is_staff": True, }, follow=True, ) the models: class User(AbstractUser, PermissionsMixin): phone_number = PhoneNumberField(unique=True) email = models.EmailField("Email address", unique=True, null=True, blank=True) password = models.CharField(_("password"), max_length=128) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) class Address(models.Model): label = models.CharField(max_length=200) user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="addresses") is_default = models.BooleanField(default=False) street = models.CharField(_("Street"), max_length=200) and the registration is done like that: class UserAddressInline(admin.StackedInline): model = Address extra = 0 class UserAdmin(admin.ModelAdmin): add_form = CustomUserCreationForm form = UserChangeForm inlines = [ UserAddressInline, ] admin.site.register(User, UserAdmin) admin.site.register(Address, AddressAdmin) I want to test the admin dashboard and fill data to the model User and the Addresses using the function test_user_admin__create -
how do i solve tuble object has no attribute after i run my django prject
I have created django project and starting the development. there were no issue as i test it but after i visit the developement server I get the error of tuple object has no attribute even though there is no tuble variable whatsoever