Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pull audio file from django backend in vuejs
I am trying to build an app that would transfer recorder audios from the vuejs front end to my django back end and get them back. However I have troubles with both ways: front -> backend : my audios recordings are 'blobs' format. Should I 'send' in vue to django the entire blob and django would store it or would I juste create an url and vue would store the file on the server ? backend -> front : I try to display an audio by putting in the url of where I stored them, however I keep having 404 errors... Here is my django audio models.py: class Audio(models.Model): id = models.SlugField(max_length = 6, primary_key = True, unique = True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(settings.AUTH_ROOM_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, help_text="timestamp of the audio") audiofile = models.FileField(upload_to='recordings/%Y/%m/%d') def __str__(self): return str(self.audiofile) def __str__(self): return f"{self.id} ({self.user})" Here is my vue, where I want to display audios: onResult() { var div = document.getElementById("audiosContainer"); var link = document.createElement("link"); link.rel = "stylesheet"; link.href = this.audios[0].audiofile; // here http://localhost:8000/files/recordings/2021/05/04/file_example_MP3 div.innerHTML += '<audio controls name="media"><source src="' + link.href + '" type="audio/wav"></audio>'; }, my django python view: class AudioView(APIView): def get(self, request): all_audios = Audio.objects.all().order_by("id") … -
How to use function of order_set if I am using filter instead of get?
When I use get instead of filter in views.py, I get error saying customer object isn't iterable, which I understand. But using filter instead of get doesn't allow me to user 'order_set' function (also in views.py), showing up with an error message: 'QuerySet' object has no attribute 'order_set'. How can I workaround this? views.py def customer(request, pk): customer = Customer.objects.filter(id=pk) order = customer.order_set.all() context = {'customer': customer, 'order':order} return render(request, 'accounts/customer.html', context) customer.html <table> <tr> <th>Email</th> <th>Phone</th> </tr> {% for i in customer %} <tr> <th> {{i.email}}</th> <th> {{i.phone}}</th> </tr> {% endfor %} </table> <table class="table table-sm"> <tr> <th>Product</th> <th>Category</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {%for order in order%} <tr> <td>{{order.product}}</td> <td>{{order.product.category}}</td> <!-- the above is chaining --> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a href="">Update</a></td> <td><a href="">Remove</a></td> </tr> {% endfor %} </table> urls.py urlpatterns = [ path('', views.home), path('products/', views.products), path('customer/<str:pk>', views.customer) ] -
Django pass context to a nested ModelSerializer
I have a Foo serializer inside a Bar serializer. I want to pass the context request to Foo serializer so I can make a valid url of Foo object. class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() def to_internal_value(self, data): # Save depending on name foo = Foo.objects.get(name=data) return {'foo': foo} def to_representation(self, instance): request = self.context.get('request') # Get request from BarSerializer name = instance.foo.name link = request.build_absolute_uri( '/apps/foo/{}'.format(instance.foo.id)) return {'name': name, 'link': link} class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') How do I pass the context request from one serializer to another? -
Mark all duplications in annotations
I have a model: class Order(models.Model): data = models.TextField() sessionid = models.CharField(max_length=40) I need to get queryset where every unique sessionid will be masked as name or something. For example if I have 3 objects { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "bar" } query should annotate each unique session_id to return: { "data": "...", "name": "A" }, { "data": "...", "name": "A" }, { "data": "...", "name": "B" } How could I make this query? Thanks! -
how to join 3 tbales with django?
i need to join 3 tables using django , here is my problem a super user can create a Project and assign users to it a Project contains a Tasks each user have specific tasks under a projects thanks a lot ! class Project(models.Model): name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=50, choices=CATEGORY, null=True) users = models.ManyToManyField(User,db_table='users_to_mission') superuser = models.ForeignKey(User,on_delete=models.CASCADE, related_name='created_by') def __str__(self): return f'{self.name}' class TaskList (models.Model): title =models.CharField(max_length=1000, null=True) def __str__(self): return f'{self.titre}' class Tasks (models.Model): titre = models.ManyToManyField(TaskList) project = models.ForeignKey(Project , on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user') def __str__(self): return f'{self.titre}' -
Test Concurrent Clients in Django's TestCase
I want to test the performance of Django when a number of clients making requests concurrently. I had no luck using Python's multiprocessing package in a TransactionTestCase case but got it to work using threading, like this: class UserRegisterTestCase(TransactionTestCase): NUM_PROCS = 5 @staticmethod def register(): email = '{}@test.com'.format(threading.get_ident()) c = Client() c.post(reverse('my_login'), {'action': 'register', 'email': email, 'password_1': '12345', 'password_2': '12345'}) connection.close() def test_register(self): threads = [] for i in range(self.NUM_PROCS): threads.append(threading.Thread(target=self.register)) for t in threads: t.start() for t in threads: t.join() self.assertEqual(MyClients.objects.count(), self.NUM_PROCS) The test passed, but I wonder with Python's GIL, is it true that 5 concurrent clients are trying to register at the same time, or is it just some syntactic sugar in that under the hood, Django sees and handles one client request at a time? If latter is the case, what's the right way to test for concurrent clients? Thanks. -
django: FOREIGN KEY constraint failed
In my django project when I'm trying to add a faculty it throws a "FOREIGN KEY constraint failed" error. Here I'm trying to save the faculty under the institute and all the roles have a user login which is linked with a one to one field models.py : class CustomUser(AbstractBaseUser): is_admin = models.BooleanField(default=False) is_institute = models.BooleanField(default=False) is_faculty = models.BooleanField(default=False) is_student = models.BooleanField(default=False) user_email = models.EmailField(verbose_name='Email',primary_key=True,unique=True) date_created = models.DateTimeField(verbose_name='date created', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) user_image = models.ImageField(upload_to='profile_images',null=True,blank=True) USERNAME_FIELD = 'user_email' class Institute(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) institute_name = models.CharField(max_length=75,verbose_name="Institute Name",null=True,blank=True) institute_address = models.TextField(max_length=100,verbose_name="Address",null=True,blank=True) institute_number = models.PositiveBigIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute_id = models.IntegerField(unique=True,verbose_name="Institute Id",null=True,blank=True) class Faculty(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) faculty_id = models.CharField(max_length=75,verbose_name="Faculty Id",null=True,blank=True) first_name = models.CharField(max_length=75,verbose_name="First Name",null=True,blank=True) last_name = models.CharField(max_length=75,verbose_name="Last Name",null=True,blank=True) faculty_number = models.PositiveIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute = models.ForeignKey('Institute',on_delete=models.CASCADE) class Meta: unique_together = [['faculty_id','institute']] views.py add faculty function: def addFaculty(request): if request.method == "POST": user = CustomUser.objects.create_user(user_email=request.POST.get('user_email'),role="faculty",password=request.POST.get('password')) user.save() Faculty.objects.create(user=user,faculty_id=request.POST.get('faculty_id'),faculty_number=request.POST.get('faculty_number'),first_name=request.POST.get('first_name'),last_name=request.POST.get('last_name'),institute=Institute(user=request.user)).save() return redirect('dashboard') else: extraFields = [ { 'label':"First Name", 'name':'first_name', 'type':'text' }, { 'label':"Last Name", 'name':'last_name', 'type':'text' }, { 'label':"Faculty Id", 'name':'faculty_id', 'type':'number' }, { 'label':"Faculty Number", 'name':'faculty_number', 'type':'number' } ] return render(request,'learnerApp/addUser.html',context={'extraFields':extraFields}) -
Django Dynamic MySQL Table Creation
How to create Dynamic MySQL Database Table in Django? Suppose I create a table 'surveys'. Enter a survey 'Student Survey' which has id '1' in 'surveys' table. I want to create 'response_1' table for saving the responses. Enter a survey 'Employee Survey' which has id '2' in 'surveys' table. 'response_2' table for saving the responses. Enter a survey 'Job Survey' which has id '3' in 'surveys' table. 'response_3' table for saving the responses. And so on.. Please help.. Thank you. -
Python unittest and coverage missing not working
I have the following function: def edge_delete_check(id: str) -> bool: queryset = NsRequestRegistry.objects.filter( **{ 'nsr_insd__constituent-isd__contains': [ {'id': id} ] } ) if not queryset: return True else: return False And when I run my tests, coverage tells me that i'm missing on return False. So I've been trying to run a test that tests the False condition on my function above. class HelperTests(unittest.TestCase): """Tests helper functions""" def test_edge_delete_check_false(self): result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd') self.assertTrue(result, False) The given id should return a False for result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd'), which it does, which means the given id can not be deleted as queryset in the function above returned a non-empty result. But doing a self.assertFalse(result, False) throws an AssertionError: True is not false : False. If I change my assert to: self.assertTrue(result, False) the test passes but the coverage report still says that my return False on my function is missing. So the two questions I have are: How should I write my test to test the return false statement on my function above? How can I get coverage to report that it has tested the return false statement and is no longer missing? Thanks for any help. -
How to handle patch method in AJAX?
How to handle the patch method from AJAX. My backend is written in Django rest API.Im using model viewsets.Backend view as below: class ProductAPI(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = ProductTbl.objects.all() @action(detail=False, methods=['PATCH']) def get_object(self,*args,**kwargs): return get_object_or_404(**kwargs) def update_product(self,request,pk): try: product_obj = self.get_obj(pk=pk) serializer = self.serializer_class(product_obj,data = request.data, partial = True) if serializer.is_valid(): serializer.save() return Response({},status = 200) return Response(serializer.errors,status = 400) except Exception as e: return Response({},status = 500) urls.py path('product/edit/<int:pk>/', ProductAPI.as_view({'patch': 'update_product'}), name='update_products'), my ajax code as follows: var form = new FormData($("#update_form")[0]) $.ajax({ type:"PATCH", url : "/product/edit/1", data:form, success:function(data){ }, error:function(data){ } }) Still, I'm getting error 405.Method not allowed... -
Django channels create a separate task that sends message to group at intervals
Essentially I am trying to create a real time applications for teams with Django channels. What happens is that there is a physics simulator that runs on the server and then sends the game state to be displayed on the client machines. What I need is a function that runs every 1/20 seconds on the server and then sends an output to each socket in a group. What I am currently thinking of doing is using threading to spin up a task (only needs to run for 60s total) which runs the physics simulation and then waits for the remaining time until the next execution. But I can guess that there is a real way to do this with Django channels which I can't find in the documentation. -
Django: Open a form from admin action
I'm trying to change some things inside this logic, so for now I'm only able to send a push notification to one user at the time and I'm trying to make that I would be able to select multiple users. So I have created an admin action which let's me to select some users and now I'm struggling about creating a form which would fulfill the users that I selected. This is what I have now (Sending push notification to one user at the time). Select users that I want to send the push notification. This is my code: class CustomUserAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('password',)}), (_('Personal info'), {'fields': ('email', 'phone', 'companies', 'active_company', 'avatar', 'completed_registration', 'language')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'work_hours_until', 'work_hours_from')}), (_('Terms and conditions agreement'), {'fields': ('agreement_date', 'agreement_text')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('phone',), }), ) list_display = ['id', 'phone', 'email', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login'] ordering = ('-id',) search_fields = ('email', 'phone') exclude = [] actions = ('send_push_notification', ) def send_push_notification(self, request, queryset): # Create some kind of form and logic..?? queryset.update(is_staff=False) # This is just to test -
Doesn't save form in django python foreignkey
There is a form with input text, which is not saved and throws a ValidationError, because there is no such value in the foreignkey model. The problem is that the check goes against pk, but the name. How to do it? (via select it is impossible, since this is entered and ajax gives him options). models class Orders(models.Model): service = models.ForeignKey('Service', null=True, blank=True, on_delete=models.PROTECT) class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SimpleOrderAddForm(forms.ModelForm): class Meta: model = Orders fields = ['service'] def clean_service(self): name = self.cleaned_data['service'] try: get_service = Service.objects.get(name=name) return get_service.pk except get_service.DoesNotExist: return name picture html form: UPD: a question in a different vein: how to change validation from pk to name field in input forms? UPD2: when entering the correct value into input, it outputs: Choose the correct option. Your option is not among the valid values. the error is that when entering, you must specify the pk field for the Service model and then the model is saved. And how to make the comparison by the name field take into account when writing the form? UPD3: already asked this question in a different vein here: here and here -
How to change the dbsqlite file ownership in gcp?
I have hosted my Django app to gcp. I am able to access the url aswell. But I am not able to login to the django admin panel. It gives me the following message. As per what I read it seems to be a permission issue. How can I fix this problem? NOTE: I dont want to use any cloud database. I want to stay with dbsqlite. Any help is appreciated. -
Django sending email with pdf
How to send an email with pdf or attachment and html using django i received no error but no email send from django.core.mail import EmailMessage send_mail=EmailMessage(email_template, [settings.EMAIL_HOST_USER, Email] , [Email]) send_mail.attach_file('static/pdf/ENROLLMENT-PROCEDURE-2021-.pdf') send_mail.send() print(send_mail) -
How to get count of model objects in django
Would anyone try to explain to me why I can't get a count of what is the query. I'd like to get count for all the books borrowed by every student def view_student(request): issues = Student.objects.all() for issue in issues: borroweds = Issue.objects.filter(borrower_id__student_id = issue.student_id).count() print(borroweds) return render(request, 'view_student.html', {'borroweds':borroweds}) And the tml code is this. {% for student in students %} <tr> <td>{{ forloop.counter }}</td> <td>{{ student.student_id }}</td> <td>{{ student.name }}</td> <td>{{ student.batch }}</td> <td>{{ student.semester }}</td> <td><a href="{% url 'all_borrowed' student.student_id %}"> {{ borroweds }}</a> </td> </tr> {% endfor %} This gives me a list of all students with books borrowed print(borroweds) while in the template {{ borroweds }} gives me 0's Am I calling it the wrong way of the code in the views???? -
centre the contents of a login page
I'm having trouble centring the contents of my login page Can you help me with the styling? I basically want the long input fields to be in the centre and be short like a typical login page. I had another question regarding bootstrap, I found a code snipped for some component for which I used version 3.4 but I am not able to use the other features of the higher versions for my other components..is there a way around that? the code is: {% extends "auctions/layout.html" %} {% block body %} <h2>Login</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <input class="btn btn-primary" type="submit" value="Login"> </form> Don't have an account? <a href="{% url 'register' %}">Register here.</a> {% endblock %} -
Updation of fileds in Django
I am looking to update the profile of my user in Django. However, after clicking the submit button on my webpage, the changes are not reflected into the database and backend. Below, are my models.py, views.py, urls.py, forms.py and html page files containing details of the same. How can I fix this issue. models.py: class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") Address = models.CharField(max_length=150) Skills = models.CharField(max_length=150) Work_Experiences = models.CharField(max_length = 150) Marital_Status = models.CharField(max_length = 150) Interests = models.CharField(max_length = 150) Edcucation = models.CharField(max_length = 150) category = models.ForeignKey("Category.Category",on_delete=models.CASCADE,default="demo") sub_category = models.ForeignKey("Category.SubCategory",on_delete=models.CASCADE,default="demo") phone_number = models.CharField(max_length=11) Aadhar_Card = models.FileField(upload_to="user_aadhar_card/",default="") def __str__(self): return str(self.user) views.py: def myaccount(request): instance1 = User_profile.objects.get(user=request.user) if request.method == "POST": user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance=instance1) if user_form.is_valid(): user_form.save() messages.success(request,('Your profile was successfully updated!')) elif profile_form.is_valid(): profile_form.save() messages.success(request,('Your profile was successfully updated!')) else: messages.error(request,('Unable to complete request')) return redirect('dashboard') user_form = UserForm(instance=request.user) profile_form = UserProfileForm(instance=instance1) return render(request=request, template_name="userprofile.html", context={"user":request.user, "user_form":user_form, "profile_form":profile_form }) forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password","first_name","last_name"] class UserProfileForm(forms.ModelForm): class Meta: model = User_profile fields = '__all__' exclude = ['user'] def _init_(self, *args, **kwargs): super()._init_(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'id':'fname','class': 'form-control'}) self.fields['last_name'].widget.attrs.update({'id':'lname','class': 'form-control'}) self.fields['email'].widget.attrs.update({'id':'email','class': 'form-control'}) self.fields['username'].widget.attrs.update({'id':'uname','class': 'form-control'}) self.fields['password'].widget.attrs.update({'id':'password','class': 'form-control'}) self.fields['Address'].widget.attrs.update({'id':'address','class': 'form-control'}) self.fields['Skills'].widget.attrs.update({'id':'skills','class': 'form-control'}) self.fields['Work_Experiences'].widget.attrs.update({'id':'we','class': … -
how to get data with product id in django
i am working on oms django i stuck at getting data of product with product id in order form how to get data of product in neworderForm with product id i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help* models.py code i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help class new_order(models.Model): Product_Name = models.CharField(max_length=250, null=True) Product_Id = models.CharField(max_length=10, null=True) Free_Size = models.IntegerField(default=0, null=True) S = models.IntegerField(default=0, null=True) M = models.IntegerField(default=0, null=True) X = models.IntegerField(default=0, null=True) XL = models.IntegerField(default=0, null=True) L = models.IntegerField(default=0, null=True) # customer details Name = models.CharField(max_length=250, null=True) Address = models.TextField(null=True) Pincode = models.IntegerField(null=True) Mobile = models.IntegerField(null=True) Alt_Mobile = models.IntegerField(null=True) Date_Of_Order = models.DateField(auto_now=True) Order_Type = ( ("Prepaid", "Prepaid"), ("C.O.D", "C.O.D"), ) Order_Type = models.CharField(max_length=30, null=True, choices=Order_Type) Order_Id = models.CharField( max_length=5, blank=True, null=True, default=random_string ) Total_Amount = models.PositiveIntegerField(null=True, blank=True) Track = models.CharField(max_length=50, null=True) Courier_Partner = models.CharField(max_length=50, null=True) Status = ( ("Pending", "Pending"), ("Dispatched", "Dispatched"), ("Cancelled", "Cancelled"), ) Status = models.CharField(max_length=50, null=True, choices=Status, default="Pending") def __str__(self): views.py code from django.shortcuts import render, redirect, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from … -
How to solve Session matching query does not exist in Django sessions
I added a one user instance functionality to my web app, where a user is logged-out whenever they login in another browser. It worked well, until I updated the logged in user information. whenever I try loggin in- my app throws a DoesNotExist error; stating that Session matching query does not exist. and does not login or even create a new user. How do I get over this error, I will attach codes if need be. -
I want to post a list of JSON values to a model's field in Django
I want to post a movie into the collection's movie field( list of movies). I define the model as class Movie(models.Model): # collection = models.ForeignKey(Collection, on_delete = models.CASCADE) #, related_name='reviews' title = models.CharField(max_length=200) description = models.CharField(max_length=200) genres = models.CharField(max_length=200) uuid = models.CharField(max_length=200) def __str__(self): return self.title class Collection(models.Model): title = models.CharField(max_length=200) uuid = models.CharField(max_length=200, primary_key = True) description = models.CharField(max_length=200) movie = models.ForeignKey(Movie, on_delete = models.CASCADE) def __str__(self): return self.title this is how i am using the viewset class CollectionViewSet(viewsets.ModelViewSet): queryset = models.Collection.objects.all() serializer_class = serializers.CollectionSerializer but i am not able to enter values for the movie field enter image description here -
Django migration problem with long traceback
I have a strange and frustrating problem with migration that I can't figure out. I'm not experienced in debugging. The steps before python3 manage.py makemigrations was OK. This is the log I kept. Could you please help me? ruszakmiklos@Ruszak-MacBook-Pro firm % python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stressz Running migrations: Applying stressz.0050_auto_20210504_0757...Traceback (most recent call last): File "/Library/Python/3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Library/Python/3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Python/3.8/site-packages/django/db/migrations/migration.py", line 124, … -
please solve this DLL load failed
Process Process-1: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "multiprocessing\process.py", line 258, in bootstrap File "multiprocessing\process.py", line 93, in run File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\DeepFaceLab\core\leras\device.py", line 101, in get_tf_devices_proc import tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow_init.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python_init.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors for some common reasons and solutions. Include the entire stack trace above … -
Django: AttributeError: 'int' object has no attribute 'cafe_name'
Hey I am trying to return a set of objects that belong to "friends" the logged in user follows and are within a specific geographic space. But I get this error: AttributeError: 'int' object has no attribute 'cafe_name' views.py def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) friends = UserConnections.objects.filter( follower=request.user ).values_list('followed__pk', flat=True) mapCafes.objects.filter( geolocation__coveredby=geom, uservenue__user_list__user__pk__in=friends ).distinct() return JsonResponse([ [cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in friends ], safe=False) Models class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=1000) image_embed = models.CharField(max_length=10000) class Meta: managed = False db_table = 'a_cafes' def __str__(self): return self.cafe_name [...] class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Traceback: Internal Server Error: /electra/get_friends/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
SSO with roles and permissions
We have projects that interacts with regular users (general app) and company users (companies app). Therefore, in our projects, generally, we have two types of Users: Regular - authenticates with phone_number as identifier. Regular users are any Users that can do common staff in our system. Staff - authenticates with email as identifier. Staff Users belong to some company and they have some roles. So, we built SSO app, that keeps all users, because there are apps that need about any user and having separate app that handles users in one place was for us better choice. However, there are troubles with our idea... The company app has its SUPERUSER that can create some company, company branch and director of that company and etc. We create company-apps superuser in our SSO app and give it COMPANY APP SUPERUSER role. SSO app does not hold the specific roles of company for users, we don't want it. That is the responsibility of company app. So, there is the problem when director of company wants to invite (create) employee, he/she requests company-app, which in the box calls SSO app endpoint to create user. Inside of SSO app we don't know who is requesting …