Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Raspberry JavaScript bottleneck with drawImage canvas
I am trying to send frames to django backend in order to send back some predictions (JSON format). Currently we are using WebRTC getUserMedia, copying video (stream from cam) to a hidden canvas, then sending it through a web socket to the backend as binary file. It works perfectly, however, we can't achieve more than 5 fps on a PI (>30fps on regular laptop). Our bottlenecks seem drawImage (from video to canvas: 150ms on PI vs 4ms on laptop) and toBlob (canvas to binary data: 80ms on PI vs 4ms on laptop). Any idea how to improve it ? Should we definitely switch to WebRTC, or there is alternative to drawImage and toBlob ? (WebAssembly...) -
How to send data from javascript function to Django View
I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided. index.html <script> function makeid(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } console.log(makeid(9)); </script> -
Problem with AJAX calls in Django app while developing google chrome extension
When I am trying to send data to my localhost using the ajax call in popup.js, I am getting an error : Not Found: /sentiment/ "GET /sentiment/?number=219 HTTP/1.1" 404 1714 Even though I checked the url and it is correct and exists. This is the snippet of my ajax call: $.ajax({ url:"http://127.0.0.1:8000/sentiment/", dataType:"json", data:{ number:newTotal }, crossDomain:true, success:function(json) { $('#total').text(json.number) } }) and this is my urls.py file in django app : from django.contrib import admin from django.urls import path,include from DetectHate import views from django.urls import path,re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^sentiment/$', views.sentiment,name="sentiment"), ] and this is my views.py file - import json from django.http import Http404,HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def sentiment(request): if request.is_ajax(): var=request.POST.get('number')+5 data={} data['number']=var+5 return HttpResponse(json.dumps(data),content_type='application/json') else: raise Http404 -
Can't logout in my django project, it doesn't redirect correctly
I'm implementing a log in/ log out script in my django project but the log out is not working. This is my code index.html, {% load static %} <!DOCTYPE html> <html lang="es"> <head> <!--<title> {% block title%}{% endblock%} </title>--> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <header> <h2> Hola {{ user.username }} </h2> <a href="/logout/">Log out</a> </header> </body> </html> As you can see I just declare a link <a href="/logout/">Log out</a> that has to redirect the user to the log out view. I think maybe the error is here. My views.py def logout(request): auth.logout(request) messages.info(request, 'Log out done!') return redirect('login') My urls.py from the app of Usser_App, urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ] My urls.py from the "general" app, urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App/', include('Platform_App.urls')), path('Users_App/', include('Users_App.urls')), ] I know the last one is working because the login is working. The problem is when I click in log out link, that is not redirecting correctly. I tried, <a href="/logout/">Log out</a> <a href="Users_App/logout/">Log out</a> But not work. How I have to do it? I'm sure is esay, but I can't see where is the problem. Thank you very much!!! -
Install python module inside of Django project
I would like to install a python module inside a Django project. That way i can modify the module to my needs. So when i upload the code to the server, it has the same code as locally. Unlike when i install the module via requirements.txt For example: i want to customize the ShopifyApi module. So i download the source code to my project. But where do i have to put the module so that is behaves like a normal module? Because now when i try to import the module with "import shopify" (which works when the module is installed with Pip) Django gives me the error: ModuleNotFoundError: No module named 'shopify' I have put the ShopifyApi modul code inside a custom shopify Django app. -
django: modify database flag from async thread does not have any effect
I have a django 3 project that should be able to spawn a Thread and then stop it when a certain URL is called. My idea was to make a model with the Thread metadata. The thread would have a reference to its metadata object and regularly check a boolean flag. When the flag is set, it would terminate. class Process(models.Model): termination_flag = models.BooleanField(default=False) def check_termination(self): return self.termination_flag def stop(self): print('Stopping process') self.termination_flag = True self.save() print(self.termination_flag) class MyProcess(): process = None def set_tweepy_stream(self,tweepy_stream): self.tweepy_streams.append(tweepy_stream) def set_process(self,process ): self.process = process def on_event(self, status): print('Term flag: ' + str(self.process.check_termination())) But this does not work. When I call the Process.stop() method, the following output is returned: Stopping process True However, at every subsequent call of MyProcess.on_event, the flag is always set to False. At the same time, the MyProcess object calls other methods of the class Process, including a counter function that works correctly. Why does this happen? Any idea on how I can achieve my goal? -
How to test websocket action that contains countdown timer in django-channels?
I am using channels+DRF and one of restrictions in the project is countdown timer like if user is not responding in 15 seconds close his channel. How can I test that in async tests for consumers? -
Query to send post request in django
I'm trying to create a Calorie Info API which saves calorie intake for a user. If it is a new user, then add an entry for the user id and item id. If the user already exists, If the item is new, then just map the item id and the calorie count with that user. If the item id is already mapped with that user, then add the items calorie count with that item for that user. Url: /api/calorie-info/save/ Method: POST, Input: { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } Output: - Response Code: 201 My model: class CalorieInfo(models.Model): user_id = models.IntegerField(unique=True) itemId = models.IntegerField(unique=True) calorie_count = models.IntegerField() I tried: class Calorie(APIView): def post(self, request): data = json.loads(request.body.decode("utf-8")) user_id = data['user_id'] for i in data['calorie_info']: entry = CalorieInfo(user_id=user_id, item_id=i['itemId'], calorie=i['calorie_count']) entry.save() res = {"status": "success"} return Response(res, status=status.HTTP_201_CREATED) The above code works fine but how can I check the above conditions in my code ? -
Django - should I start a new app for login pages?
I'm wondering, should I start a new app for autentication or use this mechanism in existing app in my project? -
'Relation does not exist' error when trying to run docker-compose in docker-machine cookiecutter-django
I have completed my Django Project using cookiecutter-django. If I just locally run: $ docker-compose -f local.yml build $ docker-compose -f local.yml up My project launches just fine in http://0.0.0.0:8000 Nonetheless, now I am trying to deploy it following this guide: https://realpython.com/development-and-deployment-of-cookiecutter-django-via-docker/ I have been able to create the local docker-machine with docker-machine create --driver virtualbox dev, activate it eval $(docker-machine env dev) and build the image, but if I run docker-compose -f local.yml up then I get the following error: Attaching to innovacion_innsai_postgres_1, innovacion_innsai_django_1, innovacion_innsai_node_1 postgres_1 | 2020-03-12 09:14:42.686 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2020-03-12 09:14:42.686 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2020-03-12 09:14:42.688 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-03-12 09:14:42.702 UTC [21] LOG: database system was shut down at 2020-03-11 10:05:23 UTC postgres_1 | 2020-03-12 09:14:42.732 UTC [1] LOG: database system is ready to accept connections django_1 | PostgreSQL is available django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute django_1 | return self.cursor.execute(sql, params) django_1 | psycopg2.errors.UndefinedTable: relation "innovation_sector" does not exist django_1 | LINE 1: ...n_sector"."id", "innovation_sector"."sector" FROM "innovatio... django_1 | ^ … -
Django: From List of ForeignKey-Parents: get the on with the newest Child
is there a way to get, from a list of ForeignKey-Parents, the one which got the newest Child? For example: class parent(models.Model): name = models.CharField(*) class child(models.Model): parent = models.ForeignKey(parent, *) Now, given a list of parents, i want to get the parent, which had a child added last. Is there an easy way to do that in Django? Thanks for the Answers! -
How to retrieve dynamic value from Django settings.py in a Celery Task?
My Django rely on Celery and Celerybeat to spawn tasks. I have 3 systemd services/units: myapp.service (gunicorn daemon) celery-myapp.service (celery worker(s)) celerybeat-myapp.service (celerybeat daemon) I have an environment variable MY_SECRET defined in my main "myapp.service" service (systemd unit). I can't get this value from settings.py or directly environment variable in my tasks (tasks.py), but I can retrieve this value smoothly from my view (views.py) using settings.py or environment variable directly. Do I need to replicate environment variable MY_SECRET defined in myapp.service to celery-myapp.service and celerybeat-myapp.service so that I could grab this value from my Celery tasks? myapp.service [Unit] Description=My App After=network.target Wants=celery-myapp.service Wants=celerybeat-myapp.service [Service] User=myapp Group=nginx Environment=MY_SECRET=1234 WorkingDirectory=/opt/myproject/ ExecStart=/opt/myproject/env/bin/gunicorn --workers 3 --log-level debug --bind unix://opt/myproject/myapp.sock myaproject.wsgi:application [Install] WantedBy=multi-user.target Environment variable is referenced in my Django project 'settings.py' along with other settings I intended to use within the application: settings.py # Populated with environment variable defined by systemd unit MY_SECRET = os.environ.get('MY_SECRET') # Static value MY_URL= 'http://127.0.0.1' From my view I can get value defined as environment variable MY_SECRET from settings.py and directly from environment: views.py def my_view(request): from django.conf import settings as project_settings my_secret_env = os.environ.get('MY_SECRET') my_secret_setting = project_settings.MY_SECRET my_url_setting = project_settings.MY_URL return render(request,'mypage.html',{ 'my_secret_env': my_secret_env, 'my_secret_setting': my_secret_setting, 'my_url_setting': my_url_setting, … -
Perform calculations on data in backend in anticipation of API request
First up, I'm not looking for any code, but only guidance related to the workflow and technologies which can be used to address our specific problem. We have a system where we provide a visual query builder kind of interface. We have loads of data on which the user can apply this query. So the query can be something like all rows where x > 5 and y <2.5. While this is fairly easy to achieve, the problem we are facing is that the fields x and y are not pre-calculated fields and these relations can be defined by the user. For instance, the user can define a relationship like x = (a+b)-c^2 and then apply a filter on x. Since the value of x needs to be dynamically calculated, the query builder then takes significant amount of time to return the results. So I was wondering if we can implement some kind of prefetching and preprocessing such that the moment the user selects the field x, we calculate all the values for x in the backend. Since the user can take a few seconds to define the entire query, we'd have at least part of the calculation done by … -
Deploy application developed using Django + Angularjs on apache http server [closed]
I am working on a POC using Django as backend and angular js as front end . I want to deploy the application on Apache http server. How to set up apache http server and what configuration changes should be done on backend and front end to run the application using apache http server. -
Access basket/shipping address in django oscar pricing strategy
What would be the best practice to get the shipping address in a pricing strategy? Based on the country selected, I would like to apply tax, or not. I have an instance of CheckoutSessionData in my Selector, and the Selector inherits from CheckoutSessionMixin. But, CheckoutSessionMixin needs a basket for many operations, especially for getting a shipping address. And, the BasketMiddleware gets it's strategy first, and only then sets the basket on the current request. So, how to get the shipping address, before? Any best practices? -
Django distinct method
I just want to select what i want to distinct field, in my case the Grading_Behavior__GroupName should not coincide with being distinct of Grading_Behavior__Name this is my current result this is I want result This is my views.py behaviorperlevel = EducationLevelGradingBehavior.objects.filter(GradeLevel__in = coregradelevel).filter(Grading_Period__in = coreperiod)\ .order_by().values('Grading_Behavior__GroupName','Grading_Behavior__Name','Display_Sequence','id').distinct('Grading_Behavior__Name') my models class EducationLevelGradingBehavior(models.Model): Display_Sequence = models.IntegerField(null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Behavior = models.ForeignKey(GradingBehavior, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) this is my admin site -
django-allauth: override a user already existing
In my movies app, I allow anonymous users creating their own movie lists. This is done by means of retrieving the session_key parameter and saving it into the User model. So, I actually register anonymous users as users on the background, and their username is their id in this case. Now, when an authenticated anonymous user registers via Facebook or Google (registration is implemented by means of django-allauth), I want not to create a new User instance, but to update the existing user, so as to keep their movies_list intact, with their username changing from their id in the database to the actual username retrieved from Facebook. I have tried to play with the user_signed_up signal and to override DefaultAccountAdapter, but this yielded no results. Obviously, I just don't understand how this should work and need some conceptual advice on how to implement the desired scheme: update the existing User instance instead of creating a new one from Facebook or Google with django-allauth. -
What is the best way to handle different but similar models hierarchy in Django?
What is the deal: I'm crating a site where different types of objects will be evaluated, like restaurants, beautysalons, car services (and much more). At the beginning I start with one app with with Polymorfic Model: models.py: from django.db import models from users.models import ProfileUser from django.utils import timezone from polymorphic.models import PolymorphicModel class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) sea_food = models.BooleanField(default=False) is_cash = models.BooleanField(default=False) is_bank_card = models.BooleanField(default=False) is_wi_fi = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='restaurants') category_bg_name = models.CharField(max_length=100, default='Ресторанти') bg_name = models.CharField(max_length=100, default='Ресторант') is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class SportFitness(Object): is_fitness_trainer = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='sportfitness') category_bg_name = models.CharField(max_length=100, default='Спорт и фитнес') bg_name = models.CharField(max_length=100, default='Спорт и фитнес') class CarService(Object): is_parts_clients = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='carservice') category_bg_name = models.CharField(max_length=100, default='Автосервизи') bg_name = models.CharField(max_length=100, default='Автосервиз') class Comment(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments') author … -
How to check that uuid field is generated when creating a custom user in Django?
I have added an uuid field to the cusom user model. How can I check that every user I'm creating will have the uuid value? I have tried to print the uuid but it doesn't work. The field I added is: uuid = models.UUIDField(default=uuid.uuid4) -
Django ORM: Select with TO_CHAR
I have DB with fields: task_description, type, hours, date, status, user_id, created_at, updated_at, project_id, I need create list with dicts like this: [{"month":"2020 Mar","Accepted":0,"Declined":0,"Open":40}] I generated SQL query: select "t"."status", sum("t"."hours") as "total_hours", TO_CHAR("t"."date" :: DATE, 'YYYY-MM') as "ddate" FROM "tracks_track" as "t" WHERE "t"."user_id" = 1 GROUP BY "ddate", "t"."status" Format of date is YYYY-MM-DD, but i need to group this fields by YYYY-MM Can I do it using Django ORM? -
How do I make a signal run only if the user created is on a specific group in Django?
I have a model Client which uses a @receiver signal to update its fields whenever a User is created, so it creates a Client profile. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() Is there a way to only run this if the user created belongs to the Clients group? Because if a user is created in the Employees group, I don't want to create a profile. This is the view that creates the Client in the Clients group: @login_required(login_url='./accounts/login/') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() # this creates the user with first_name, email and last_name as well! group = Group.objects.get(name='Clients') user.groups.add(group) user.refresh_from_db() # load the profile instance created by the signal user.clients.address = form.cleaned_data.get('address') user.clients.city = form.cleaned_data.get('city') user.clients.postal = form.cleaned_data.get('postal') user.clients.nif = form.cleaned_data.get('nif') user.clients.mobile = form.cleaned_data.get('mobile') return redirect('clients') else: form = SignUpForm() return render(request, 'backend/new_client.html', {'form': form}) -
Django : defining method inside the models
serialize() method included in the django Tools_booked class but while trying to access that method it shows error. 'QuerySet' object has no attribute 'serialize' models.py from django.core.serializers import serialize class UpdateQuerySet(models.QuerySet): def serialize(self): print("*****Entered the serizlize inside the UpdateQuerySet models **********") qs = self return serialize('json', qs, fields=('auto_increment_id','user','component','booked')) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Tools_booked(models.Model): auto_increment_id = models.AutoField(primary_key=True) user=models.ForeignKey(Profile, on_delete=models.CASCADE) component = models.CharField(max_length=30, blank=True) booked = models.DateTimeField(auto_now_add=True,blank=True) objects = UpdateManager() def __str__(self): return self.component def serialize(self): json_data = serialize("json", [self], fields=['auto_increment_id','user','component','booked']) stuct = json.loads(json_data) print(struct) data = json.dump(stuct[0]['fields']) return data views.py class SerializedDetialView(View): def get(self, request, *args, **kwargs): print("*****Entered the SerializedDetialView **********") obj_list= Tools_booked.objects.filter(auto_increment_id=1) json_data = obj_list.serialize() return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): json_data = Tools_booked.objects.all().serialize() return HttpResponse(json_data, content_type='application/json') The error traceback json_data = Tools_booked.objects.all().serialize() AttributeError: 'QuerySet' object has no attribute 'serialize' But this works. class SerializedDetialView(View): def get(self, request, *args, **kwargs): obj_list= Tools_booked.objects.filter(auto_increment_id=1) json_data = serializers.serialize("json", obj_list ) return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): qs = Tools_booked.objects.all() json_data = serializers.serialize("json", qs ) return HttpResponse(json_data, content_type='application/json') How to use the serialize() method inside the models.py ,Tools_booked class. -
What am I missing in this Django model relationship
I have a custom user model, and a blog model. Here is the user model: class CustomUser(AbstractUser): pass email = models.EmailField(unique=True) first_name = models.CharField(max_length=20, default="", blank=True) and the blog model: class Blog(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, verbose_name=_('user'), related_name="%(class)s_blogs", on_delete=models.SET_NULL) blog_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) blog_title = models.CharField(max_length=150, null=False) My understanding is that I could use the related_name to get all blogs by a user. >>> from users.models import CustomerUser >>> user = CustomUser.objects.get(pk=1) >>> user.blog_blogs.all() <BlogQuerySet []> As you must have seen, this turns to always return but an empty queryset, even though there are blog entries by that user. So is it am not understanding here? Thank you. -
how to make custom user login using SQL query in DjangoRestFulAPI?
i have user data set in my database that contains user_id,username and password. i want to fetch data from databases using raw query. user_raw_query = ''' SELECT * from users ''' now i want to make custom user login as per above details. any help would be appreciated. -
JS files of django-smart-select not working. net::ERR_ABORTED 404
I want to use django-smart-select I have installed it via pip and used this command as mentioned in django-smart-select problems: sudo pip3 install git+https://github.com/digi604/django-smart-selects.git@js-unlinting-fixes I have added 'smart_selects' to settings.py and added these lines to URLs: url(r'^chaining/', include('smart_selects.urls')), also used this line in settings.py JQUERY_URL = True and as mentions again in problems added this lines to HTML: {% load staticfiles %} <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> but when I load the page it raises these errors. it leads to not working the second option in django smart select: GET https://example.com/static/smart-selects/admin/js/chainedfk.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/chainedm2m.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/bindfields.js net::ERR_ABORTED 404 models.py: class CustomerAddressProvince(LoggableModel): title = models.CharField(verbose_name='province', max_length=60) class CustomerAddressCity(LoggableModel): title = models.CharField(verbose_name='city', max_length=60) province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.CASCADE, related_name='cities') class CustomerAddress(LoggableModel): province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.SET_NULL, related_name='address_province', null=True, blank=True) city = ChainedForeignKey( CustomerAddressCity, verbose_name='city', chained_field="province", chained_model_field="province", show_all=False, auto_choose=True, sort=True, null=True, blank=True)