Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a Register/Login system in Django?
I have my Django project setup, with an app called "accountManager" that manages user registeration, login and the profile page, the templates are all setup and the URLs are ready. I have already designed a form for the registeration page and the login page, so I just want to use the fields that I have in my form. I did a Google search and most of the results used the UserCreationForm which in itself is a form. Would someone tell me how do I get the information from the page and register the user? Thanks in advance -
Cross join in Django
I have a QuerySet and I need to cross join it with values list, like this SELECT table_name.*, v.flag FROM table_name CROSS JOIN (VALUES (FALSE), (TRUE)) AS v(flag) QuerySet is already initialized at this moment, so I cannot use raw method, and it is being processed further, so I need QuerySet instance in result. Is there some kind of solution to do this by using only Django ORM tools? -
Django M2M admin views
I have a problem when doing the view of a model with relation m2m in django admin. this is my model: class PagoEmpleado(models.Model): cod_pago = models.AutoField(unique=True, primary_key=True) cantidad = models.IntegerField(blank=True, null=True, default='1') monto = models.DecimalField(decimal_places=2, max_digits=20, default='0',blank=True, null=True) formula = models.CharField(max_length=250 ,blank=True, null=True) class Prenomina(models.Model): PG = ( ('obreros', 'Obreros'), ('trabajadores', 'Trabajadores'), ('ejecutivo', 'Ejecutivo'), ) cod_prenomina = models.AutoField(unique=True, primary_key=True) tipo = models.CharField(choices=PG, max_length=30, default='trabajadores') descripcion = models.CharField(max_length=20, blank=True, null=True) pagos_empleados = models.ManyToManyField(PagoEmpleado) fecha_inicio = models.DateField(blank=True, null=True) fecha_final = models.DateField(blank=True, null=True) I do not know how to represent each data in the relationship ordered in the administrator. I have read the documentation of django but I have not been able to make the view, is there a complete example to guide me? -
Error when trying to upload to AWS S3 after resizing
I am having an issue with trying to resize images before uploading to Amazon S3. I got it to work somehow on a different project that uses sqlite3 database, but i doesn't work with my latest project that uses mysql instead. Can anyone please help me out here? class UserImage(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE, null=True, default=True) myimage = models.ImageField(default='profile_pics/default-profile-picture.jpg', upload_to=profile_upload) def __str__(self): return f'{self.author.username} image' def save(self, *args, **kwargs): super().save(*args, **kwargs) img_read = storage.open(self.myimage.name, 'r') img = Image.open(img_read) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) in_mem_file = io.BytesIO() img.save(in_mem_file, format='JPEG') img_write = storage.open(self.myimage.name, 'w+') img_write.write(in_mem_file.getvalue()) img_write.close() img_read.close() -
django - not saving in other database with using()
I am doing this: user = User.objects.create( username=username, email=email, is_active=False ) user.set_password(raw_password=password) user.save() for db in settings.DATABASES: if 'default' in db: print('this is default db, so skip it: ', db) continue new_user = User( username=user.username, email=user.email, password=user.password, is_active=False ) new_user.save(using=db, force_insert=True) I am trying to "sync" one user instance into other databases. I am getting: duplicate key value violates unique constraint "auth_user_username_key" I know, it is reading from default, to check for duplicates, but even if I have "force_insert=True", it is still checking default database, therefore the error. what am I missing here? -
givin three table how to populate one by one table
enter image description here Given three table how to populate a one by one table -
Unexpected end of JSON input and 404 (Not Found)
I'm working on a chat bot system. Every time I write a message and expect a message back, I get two error messages. Uncaught (in promise) SyntaxError: Unexpected end of JSON input The error is specifically pointing on .then(response => response.json()).then((json) => { I also get error: POST http://localhost/get-response/ 404 (Not Found) which is poiting to fetch("/get-response/", { I commented it in the code below: script.js window.onload = function () { var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { messages: [], input: '', send_blank: false, placeholder: 'Send a message to the chatbot...', }, created: function() { }, methods: { add_message: function() { if (this.input.length > 0) { var message = { 'text': this.input, 'user': true, 'chat_bot': false, }; this.messages.push(message); this.input = ''; //just incase this.send_blank = false; this.placeholder = "Send a message to the chatbot..."; fetch("/get-response/", { //<---- The 404 error points to this body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) .then(response => response.json()).then((json) => { //<--- The SyntaxError points to this this.messages.push(json['message']) }) } else { this.send_blank = true; this.placeholder = "Please put in some text"; } … -
Only the first form in Django forloop submitting data. The other forms submit empty fields
I am facing a situation whereby only the first form in the forloop in the code below can submit data. The rest of the forms after the first forloop posts empty data. What could be the problem. I believe my views is good since it's able to process the data from the first form. I believe the problem should be in the code below only that i cannot figure where the issue is When i hit submit button on the subsequent form i get the following in the shell [12/Mar/2020 12:07:17] "POST /hotels/conference/cart/twiga-boardroom-3/ HTTP/1.1" 302 0 [12/Mar/2020 12:07:18] "GET /hotels/conference/panari-hotel HTTP/1.1" 200 34389 HTML CODE <div class="room-item"> <div class="row gap-20"> <div class="col-12 col-sm-12 col-md-6"> <div class="row gap-20"> <div class="col-12 col-sm-4 col-md-4"> <div class="image"> <img src="{{ item.room_photo.url }}" alt="{{ item.object.name }}" /> </div> <p></p> {% if user.is_authenticated and item.user == user %} <a href="#" class="btn btn-primary btn-xs">Edit</a> <a href="#" class="btn btn-danger btn-xs">Delete</a> {% endif %} </div> <div class="col-12 col-sm-12 col-md-8"> <div class="content"> <h5><a href="#">{{ item.room_Name }}</a></h5> <p>{% for list in item.features_as_list %} <span class="icon-font"><i class="fas fa-check-circle text-primary"></i> {{ list }} </br></span> {% endfor %}</p> <p class="max-man">Max. Guests : <span class="badge badge-primary">{{ item.room_Capacity }}</span> <p class="price"><span class="number text-secondary"><small>Ksh</small>{{ item.room_Price|intcomma }}</span> per guest</p> … -
why django not found module psycopg2 in django2.2 and python 3.8
I install django 2.2.10 and python 3.8 and psycopg2 2.8.4 but when i try migration with command (python manage.py migrate) confront this error: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' psycopg2 in 32-bit. i try any solution that available in stackoverflow but this error don't dissolve -
Django Query filtering when all rows meet a criteria
Using django 1.11.7 and postgres we have four tables Job Table which contains job details job id test id Requirements table which contains Resource Requirements(Each Job can have multiple Requirements) Job = ForeignKey('Job') requirement_tpe = CharField() Resource: Resource ID resource status PotentialResourceRequirement Table which have a ForeignKey referring to Requirements table. Each requirement can be met by multiple resources.so there are multiple entries in PotentialResourceRequirement for each requirement with the identified resource. p_resource = models.ForeignKey('Resource') p_reequirement = models.ForeignKey('Requirement') I am looking for for a way to query the ORM providing a list of resources and identifying the job which can be run using those resources -
how to paginate django mptt queryset?
I start with an example Here is end of the first page: And here is start of the second page: Notice that "stand up" is without parent. I want to move it to the first page. Naїve solution would be: query page_size number of level 1 nodes extend queryset with descendant nodes The problem is that search will be broken. Here is example of search result (I extend result queryset with ancestors and descendants): "Alternative" has 20 more children, I don't want to show them all while searching for "indie". So naive solution will not work. Do you have any other suggestions? -
problem retrieving file from request.FILES
I have this at django @csrf_exempt @require_http_methods(['POST']) @api_token def foo(request): upload_file = request.FILES['file'] random_function(upload_file) return HttpResponse('done') and this at another python file import requests url = "http://127.0.0.1:8000/api/external/path" payload = {} files = {'file': open('csv_file.csv', 'rb')} headers = { 'x-api-key': 'api-key-token', 'Content-Type': 'application/form-data' } response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text.encode('utf8')) the problem is that when I executed the python file I got this error django.utils.datastructures.MultiValueDictKeyError: 'file' it was like request.FILES can't find file name but when I execute it from postman it works fine -
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 …