Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to turn a Django Rest Framework API View into an async one?
I am trying to build a REST API that will manage some machine learning classification tasks. I have written an API view, which when hit, will trigger the start of a classification task (such as: training an SVM classifier with the data the user provided previously). However, this is a long running task, so I would ideally not have the user wait once they have made a request to this view. Instead, I would like to start this task in the background and give them a response immediately. They can later view the results of the classification in a separate view (haven't implemented that yet.) I am using ASGI_APPLICATION = 'mlxplorebackend.asgi.application' in settings.py. Here's my API view in views.py import asyncio from concurrent.futures import ProcessPoolExecutor from django import setup as SetupDjango # ... other imports loop = asyncio.get_event_loop() def DummyClassification(): result = sum(i * i for i in range(10 ** 7)) print(result) return result # ... other API views class TaskExecuteView(APIView): """ Once an API call is made to this view, the classification algorithm will start being processed. Depends on: 1. Parser for the classification algorithm type and parameters 2. Classification algorithm implementation """ def get(self, request, taskId, *args, **kwargs): … -
Best way of using Django queryset where JSONField != {}
class JobAnalysis(Base, XYZ): env_vars = JSONField( default=dict ) job = models.ForeignKey( Job, related_name='jobanalyses' ) seller = models.ForeignKey( ABC, null=True ) class Usage(Base): job = models.ForeignKey( Job, null=True, blank=True ) I want all usages where env_vars has some key pair. usages_qs = Usage.objects.filter( job__jobanalyses__seller__isnull=True ).exclude( job__jobanalyses__env_vars__exact={} ) I am using above queryset to fetch all usage information where seller is null and env_vars is not equals {} usages_qs.query SELECT "Usage"."job", FROM "Usage" LEFT OUTER JOIN "Job" ON ("Usage"."job_id" = "Job"."id") LEFT OUTER JOIN "JobAnalysis" ON ("Job"."id" = "JobAnalysis"."job_id") WHERE ("JobAnalysis"."seller_id" IS NULL AND NOT ("Usage"."job_id" IN (SELECT U2."job_id" FROM "JobAnalysis" U2 WHERE U2."env_vars" = '{}') AND "Usage"."job_id" IS NOT NULL)) But I am seeing performance issue here because .exclude(job__jobanalyses__env_vars__exact={}) create inner query and because of that this select statement is timing out. Is there any better way of writing Django queryset for getting all usage record where seller is null and env_vars != {}? -
django each user needs to create and view data Issue
I have build a simple application for Creating User data, starting from user registration till the CRUD operation. now I want to extend the application to multiple users. i.e. A user can login and does CRUD likewise B user can login and does CRUD operation so on...C,D,E,F,G etc... Each individual user should able to see its own data .... for that i have used decorators/groups ...etc.. My problem is how to pass particular user data into view to see the particular user data like tasks = request.user.Task.objects.all() for this, I am getting error Internal Server Error: /query/ Traceback (most recent call last): File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\decorators.py", line 21, in wrapper_function return view_func(request,*args,**kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\views.py", line 107, in query tasks = request.user.Task.objects.all() File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'Task' [15/Oct/2020 23:07:22] "GET /query/ HTTP/1.1" 500 83300 - Model from django.contrib.auth.models import User from django.db import models # Create your models here. from … -
Jumbotron and background images disappear when the window size changes from full screen to small
Have an issue with my homepage, the jumbotron/background images disappear when the window size changes from full screen to small screen, when it's resized the background/jumbotron images re-appear,how can the images be made responsive ? Below is the styling: <style type = "text/css"> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; position:center; background-size:cover; background-attachment:fixed; } .jumbotron{ margin-top:20px; background-image:url("{% static '9.jpg'%}" ); background-repeat:no-repeat; background-size:cover; position:center; color:white; } body{ background-image:url("{% static '8.jpg' %}"); background-repeat:no-repeat; background-size:cover; background-position:center center; background-attachment:fixed; overflow:visible; } -
ValueError at / empty range for randrange() (0, 0, 0) Django Hosting
File "/root/payyannuronline/webapp/views.py", line 61, in indexrandom_ads=ads.objects.all()[randint(0,count - 1)]File "/usr/lib/python3.8/random.py", line 248, in randintreturn self.randrange(a, b+1)File "/usr/lib/python3.8/random.py", line 226, in randrangeraise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))ValueError: empty range for randrange() (0, 0, 0) Views.py def index(request): count=ads.objects.count() random_ads=ads.objects.all()[randint(0,count - 1)] return render(request,'index.html',{'nbar': 'index','random_ads':random_ads}) Tenmplate <div class="container"> {% load static %} <img class="mySlides" src="/media/{{ random_ads.cover }}" alt="{{ random_ads.title }}" style="width:100%"> Models.py class ads(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=260) owner = models.CharField(max_length=260) contact = models.IntegerField(null=False) email = models.EmailField(null=True) subject = models.CharField(max_length=360,null=False) description = models.TextField(max_length=2600) cover = models.ImageField(upload_to='images/ads/', default=None) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True,) validity = models.DateField(null =False) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Python code execute through django shell but not through file
I recently installed the python library riskchanges. Now I created the test_lib.py file and try to use the library function as below, from RiskChanges.load_SHP import loadshp loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') And I tried to run this code from the terminal, (python test_lib.py), it shows the following error, Traceback (most recent call last): File "test_lib.py", line 2, in <module> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', File "F:\SDSS\1. code\django\venv\lib\site-packages\RiskChanges\load_SHP.py", line 39, in loadshp geodataframe = geopandas.read_file(shpInput) File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\io\file.py", line 139, in _read_file return GeoDataFrame.from_features( File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\geodataframe.py", line 427, in from_features "geometry": shape(feature["geometry"]) if feature["geometry"] else None File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\geo.py", line 105, in shape return Polygon(ob["coordinates"][0], ob["coordinates"][1:]) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 243, in __init__ ret = geos_polygon_from_py(shell, holes) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 509, in geos_polygon_from_py ret = geos_linearring_from_py(shell) File "shapely\speedups\_speedups.pyx", line 408, in shapely.speedups._speedups.geos_linearring_from_py ValueError: GEOSGeom_createLinearRing_r returned a NULL pointer If I tried to run the same thing through django shell, it worked fine without any error message, >>> python manage.py shell >>> from RiskChanges.load_SHP import loadshp >>> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') Please help me to find out the actual error. -
Adding an `if` statement to send an Email when the count of Likes reaches a certain No
I am trying to add an IF statement so that when the Like Count reaches 2 an email is sent. I have written the codes but it is not working, I am trying with the below but it is not working. My question is how to add an if statement so that when any item with likes more the 2 an email is sent a specific email. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField( User, related_name='liked', blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() Here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def LikeView(request): # … -
Django variable creation issue
I have an custom template tag with something like this: @register.simple_tag def getLikesByUser(likedFilter, loggedInUserID): likedPeople = likedFilter personLoggedIn = loggedInUserID for personLiked in likedPeople: if personLoggedIn == personLiked.id: return True return False this will return true or false in my template, is there an option to set this return to an variable in my template? this is how a call this: {% getLikesByUser Post.likes.filter request.user.id %} I would like to have this in a variable so I can further check if is true show button if false don't. I tried this, from suggestion from my previews post: {% with likes_by_user=Post.likes.filter|getLikesByUser:request.user.id %}{% endwith %} and no luck. thanks -
Html Form does not make post request on submit
My html form won't make post request unless I comment out div with id="empty_form". This div is used to create new empty form when add more is clicked. I found that solution here. It seems like that div is marked as required field when I submit form, because when I click add more after trying to submit, new form is highlighted as red indicating required field. I am not sure why this div (id="empty_form") is required when I have not even clicked add more button. Here is my html code: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {% for form in recipeform %} <div class="row spacer"> <div class="col-2"> <label>{{form.label}}</label> </div> <div class="col-4"> <div class="input-group"> {{ form }} </div> </div> </div> {% endfor %} {{ formset.management_form }} <div> <fieldset id="form_set"> {{ formset.management_form }} <div> <a href="#" class="remove_form">Remove</a> <fieldset> {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </fieldset> </div> <div id="empty_form" style="display:none"> <div> <a href="#" class="remove_form">Remove</a> <fieldset> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </fieldset> </div> </div> <input type="button" value="Add More" id="add_more"> </fieldset> </div> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> $('#add_more').click(function() { … -
django models improve query
I want get query in model def Currently, 5 queries occur when entering into the template. {{ comment.get_all_children }} Currently I want to have fewer than 5 queries. plz... My model class Comment(models.Model): post = models.ForeignKey( Post, related_name='comment_set', related_query_name='comment', on_delete=models.CASCADE ) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.ForeignKey('self', related_name='reply', on_delete=models.SET_NULL, null=True) content = models.TextField() def get_children_filters(self, include_self=True): filters = Q(pk=0) if include_self: filters |= Q(pk=self.pk) for c in Comment.objects.filter(comment=self): _r = c.get_children_filters(include_self=True) if _r: filters |= _r def get_all_children(self, include_self=True): table_name = Comment.objects.model._meta.db_table query = ( "WITH RECURSIVE reply (id) AS (" f" SELECT {table_name}.id FROM {table_name} WHERE id = {self.pk}" " UNION ALL" f" SELECT {table_name}.id FROM reply, {table_name}" f" WHERE {table_name}.comment_id = reply.id" ")" f" SELECT {table_name}.id" f" FROM {table_name}, reply WHERE reply.id = {table_name}.id" ) if not include_self: query += f" AND {table_name}.id != {self.pk}" return Comment.objects.filter( pk__in=[comment.id for comment in Comment.objects.raw(query)] ).select_related('author', 'comment', 'post').prefetch_related('author') class Meta: ordering = ['-id'] -
ImportError while running a unit test in Django
I am inheriting an existing project and since I want to implement unit testing for the future modules, I have tried to run a very simple test like: class CalcTests(TestCase): def test_add_numbers(self): """ Test that two numbers are added together """ self.assertEqual(add(3, 8), 11) However, it shows the Import Error ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) so I looked at the init.py in the serializers file and it looked like this: from .default import * from .backup import * from what I understood, it's a not-so-good practice to use asterisks so instead, I imported all the serializer classes manually by naming every single one of them. However, I still get the same error. If you want a better reference, below is the whole error message: ====================================================================== ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * … -
"<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used
I am trying to fix an error related to my e-commerce project to show the context in Admin through PDF.html so I am trying to fix it but I got this error and I don't know how to solve it. "<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used. here is the views.py @staff_member_required def admin_order_pdf(request, order_id): html = render_to_string('pdf.html', {'order': Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) here is the url path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') -
my images are appearing as a broken file in django
im trying to build a webdite that allows the users to post product image and description for products they want to sell. but i am getting a broken image thumpnail. this is my settings.py file """ Django settings for mum project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tbe4^5o02%t@$e4n551llb@_5d_!l+8j2+je_a5gl6610zmfu)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'products.apps.ProductsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mum.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mum.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Azure Active Directory Authentication from Django-REST-Framework and ReactJS App
Seems like something pretty basic to implement, but I've been struggling for several days with it now. Trust me, I've asked enough questions here and on GitHub developer repos regarding it. Essentially: User navigates to domain.com/admin This URI is for internal company users only Thus, the user needs to be verified against the organizations Azure AD If they are a user, it takes them to the dashboard; If not, they are rejected from entering Simple, right? I'm finding not so much. I've been trying to do it server-side with DRF. Mind you, my Django backend, does not serve any static assets. It is strictly and API that consumes and provides data. It at no point uses Django Templates. I'm finding most of the libraries are out dated, have poorly written documentation, or just don't work for my use case (DRF). I've tried a handful and can't get any of them working. The ones I've tried: python-social-auth python-social-auth-django drf-social-oauth2 django-rest-framework-social-oauth2 I understand that this can also be done client-side with ReactJS libraries and supposedly it is secure. I haven't tried yet. I have no preference for either server-side or client-side just as long as user's information can be put in the … -
Django Annotate - Can I used the fields created in annotate for another field created in annotate?
I am calculating the sum of scores by dept and the number of users in each department in annotate like this: queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True)).order_by('-total_pts') I also want to send back as part of the return data avg_score = total_pts / total_users. Is there a way to add this into the annotate, or chain them together, or otherwise add this to the return queryset? Thank you. -
Postgres db FATAL: password authentication failed for user
I need help. So I am hitting a wall and have been looking around for solutions but nothing seems to be working for me. I am trying to get the backend to connect to the DB but it keeps returning the error below: django.db.utils.OperationalError: FATAL: password authentication failed for user "app". If I try changing the db_host to localhost or 127.0.0.1 it just throws back an error saying it can't find anything on port 5432. but unless I'm missing something the user and password match and have been added in the correct locations. I would appreciate any help that can be offered. I've tried wiping the containers and images and restarting and nothing seems to be working. does anyone have ideas as to what the issue may be? error Traceback (most recent call last): api_1 | File "manage.py", line 10, in <module> api_1 | execute_from_command_line(sys.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line api_1 | utility.execute() api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute api_1 | self.fetch_command(subcommand).run_from_argv(self.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv api_1 | self.execute(*args, **cmd_options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute api_1 | output = self.handle(*args, **options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 83, in … -
Django+Axios: Multiple Files upload (foreignkeys) [READ FIRST]
Greeting! (feel free to edit this post, i am exhausted ...) I have a form in ReactJs that allows multiple files upload for a single post. ISSUE i can't save these files(images) when they hit Django ( django setup is good, the issue is coming from axios). Code Sample updatePost = (data) => { let formData; const hasFile = Boolean(data.images.length); if (hasFile) { formData = new FormData(document.getElementById('postForm')) // for (let dataKey in data) { // if (dataKey === 'details') { // formData.append("details", [...data["details"]]); // } // else if (dataKey === 'images') { // formData.append("images", [...data["images"]]); // } // else { // formData.append(dataKey, data[dataKey]); // } // } for (let val of formData.entries()) { console.log(val[0] + ', ' + val[1]); } } else { formData = data; } if (!Boolean(data.id)) { return this.createPost(formData, this.axiosConfig({ 'hasFile': hasFile })) }; return axios.put( `${data.path}`, formData, this.axiosConfig({ 'hasFile': hasFile }) ); } axiosConfig = (param = {}) => ({ headers: { 'Authorization': `Token ${this.fetchToken()}`, 'content-type': param.hasFile ? 'multipart/form-data' : 'application/json' } }) return of console.log(...) name, sfdfsd Service.js:57 description, Et animi inventore et. Placeat sit laudantium voluptas et nihil architecto nemo aperiam. Adipisci voluptatem accusamus atque molestias qui. Service.js:57 category, 7 Service.js:57 subcategory, 39 Service.js:57 … -
How to set a table to UTF-8 in Django?
I am trying to update 2 tables with the SQL command like so: ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8; ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8; However, I need to do this in Django. Is there a way to set these table columns to utf8 through Django and then apply to the database via migration? -
I am trying to consume a method that I have in django but it generates an error of is not JSON serializable
@action(detail=False, methods=['post']) ## etiqueta que define el metodo def generateGuia(self, request): contrasenaEncriptada = 'contra' client = Client('url/soap') header_value = header arrayGuias = [ '' ] envios2 = [{ 'box':{ 'objEnvios': [{ 'EnviosExterno': { 'idePaisDestino': 1 . . . 'objEnviosUnidadEmpaqueCargue': { 'EnviosUnidadEmpaqueCargue':{ . . . } } } }] } }] data3 = client.service.CargueMasivoExterno(envios = envios2, arrayGuias = arrayGuias, _soapheaders=[header_value]) print(data3) ## respuesta sin necesidad de serializer return response.Response({ 'token': data3 }) response : Object of type boxResponse is not JSON serializable -
Physical printing with printer
Is there a framework that Django has (or is compatible with) that can print stuff from its web-based app to physical printers that are connected to the client side. Let's assume one printer per client, and the more simple case: the printing is triggered by human user doing something in the app (though if possible, automatic printing would be cool) . I found an old post with a suggestion here but I don't quite understand it (particularly the manual settings of the browser (Notes, Firefox, Chrome, how and where is this done, what programming language are those code lines written in?). The post also mentioned "connect the printer to the server"? If the app is hosted on a server such as Heroku, or Amazon, etc., how is this possible? -
changing cart items quantity in shopping cart using vanilla javascript
I am building an eCommerce website with Django and I am trying to change the quantity items in my shopping cart using pure javascript. I have been able to select and click on the increase and decrease buttons using a query selector but when I click on any of those buttons only the first item in the cart updates the remaining buttons do not increase the quantity of the items associated with it what should I do? This is the javascript code var minusButton = document.getElementsByClassName("btn minus1") for (var i = 0; i < minusButton.length; i++) { minusButton[i].addEventListener("click", function(event){ var quantity = document.getElementsByClassName("cart-quantity-input") for (var i = 0; i < quantity.length; i++) { var quantity = quantity[i].value-- //console.log(quantity) } })} this is the HTML code <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cart</title> <link rel="stylesheet" type="text/css" href="{% static 'css/cart.css' %}"> </head> <body> <!-- navigation menu --> {% include "topnav.html" %} <div class="maincontent"> <h1 class="hhh1" style="font-size:50px; margin:0px; margin-bottom:30px">Your Cart</h1> <div class="centerblock"> <!-- DYNAMIC CONTENT GOES HERE --> <div class="cart-row"> <span class="cart-item cart-header cart-column">ITEM</span> <span class="cart-price cart-header cart-column">PRICE</span> <span class="cart-quantity cart-header cart-column">QUANTITY</span> </div> <div class="cart-items"> {% for item in items %} <div> <div class="cart-item cart-column"> <img class="cart-item-image" src="{{item.product.imageURL}}" width="100" … -
How to solve 403 forbidden error in django?
Well I am trying delete comment. only the author of comment can delete the comment or remove the comment but on every comment it showing me 403 forbidden. and not removing the comment. views.py def comment_remove(self,request,pk): comment = self.get_object() if self.request.user == comment.author.user: comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('posts:post_detail',pk=post_pk) urls.py app_name = 'posts' urlpatterns = [ path('<int:pk>/remove/',views.comment_remove,name='comment_remove'), ] If more detail is require than tell me. I will update my question with that information. -
websocket failed with 'Invalid frame header'
I created a simple chat app and deployed it to AWS EC2. I built the frontend with Vue.js and use javascript's WebSocket. In the backend, I used Django, channels, and Postgres. It works fine on local but WebSocket is disconnected after some time on the server. I used Nginx for deployment. I also set proxy_read_timeout to 600s for the Nginx WebSocket configuration. this.chatSocket = new WebSocket(GlobalConstants.WEBSOCKET_URL + '/ws/chat/' + id + '/') this.chatSocket.onmessage = (m) => { let data = JSON.parse(m.data) let messageData = {} messageData[data.type] = data.message let message = { author: data.sender == this.currentUser ? 'me' : data.sender, type: data.type, data: messageData } this.receiveMessage(message) if (data.sender != this.currentUser) { this.addParticipant(data.sender) } } This is nginx configuration. server { listen 80; server_name x.x.x.x; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_pass "http://127.0.0.1:8000"; } location /ws/ { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_read_timeout 600s; } } Please help me. -
Django login using social account with custom adapter
I am trying to implementing logging in with Google on my django app. However, if a user with the same email as my google account exists it prompts me to a signup page, I would like to create an adapter that if user exists with the social account email, it will show a message that user exists, and if it does exists but it is inactive, it will remove it and login the new user instead. So far I have implemented this: class SocialAccountAdapter(DefaultSocialAccountAdapter): def clean_email(self, email): if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") return email def clean_username(self, username): if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") return username My intention is that if a user for instance with a gmail is logged in and tries to login but an inactive user with their gmail already exists it will remove the inactive user and login the new user instead. -
Django Sum in Annotate
Good afternoon, I am really struggling with getting a sum using Annotate in DJango. I am using User object and the following models: class Depts(models.Model): dept_name = models.CharField(max_length=55) dept_description = models.CharField(max_length=255) isBranch = models.BooleanField(default=False) def __str__(self): return "{}".format(self.dept_name) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=75) dept = models.ForeignKey(Depts, on_delete=models.CASCADE, related_name="dept", null=True) class ActivityLog(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user') activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat') activity_description = models.CharField(max_length=100, default="Misc Activity") class ActivityCategory(models.Model): activity_name = models.CharField(max_length=40) activity_description = models.CharField(max_length=150) pts = models.IntegerField() def __str__(self): return '%s' % (self.activity_name) What I need to do is get a group of departments with aggregating the sum of the pts earned by all the users activitylogs. So a user is part of department, they do activities, each activity is of a type activity_category and has associated points. How can I query using the ORM to get a sum of points for everyone in each department? Thank you, I cannot seem to wrap my mind around it.