Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send data to multiple websocket connection in django channels
I am working on a chat app and want to know if there is a way to send data to multiple websocket connections from one websocket connection -
Django forms save override
override save method in a form, I have an image that needs to be saved in a different database, but the rest of the fields should go to the default one, also I should store the image id in the default database class TbUserRegisterForm(CustomUserCreationForm): email = forms.EmailField() image = forms.ImageField() class Meta: model = TbUser fields = ['username', 'image', 'email', 'sex', 'role', 'department', 'password1', 'password2'] -
{% request.user ==" "%} Checking User and rendering html element with if else Django Templatetag
Html code: {% if request.user== "Sangam" %} <li class=""> <a class="text-left " href="landscapes.html" role="button" aria-haspopup="true" aria-expanded="false"><i class="flaticon-bar-chart-1"></i> Landscape </a> </li> {% endif %} {% if request.user == "Sam" %} <li class=""> <a class="text-left " href="characters.html" role="button" aria-haspopup="true" aria-expanded="false"><i class="flaticon-bar-chart-1"></i> Characters </a> </li> {% endif %} I want to do is if the user is Sangam then render a certain html element for him only. But,It doesn't render so. Can I do this?.Also,I wonder how can we render certain html elements to users that we have list him/her to a certain Group in Django-admin panel -
Geojson data shifts when using leaflet Ajax
Am using django and data in my backend seems so accurate when I overlay on Leaflet openstreetmap, when I try to load to my template the geojson data shifts. This is my django admin view. for my template this is what I get. need help to finalize my project -
Custom Error Response on Invalid Credentials [RestFramework_JWT]
I am using restframework_jwt in django. I want to return a custom error response on invalid login credentials. Right now, I am getting this: { "non_field_errors": [ "Unable to log in with provided credentials." ] } I want to return a custom JSON response like this: { "success":false, "message":"Invalid Credentials", "code":401, "data":[] } Kindly help me in this. -
Global search query params based on user role
##I'm getting this error how to solve this one For the global search filter based on user role I have made this function what I have done wrong anyone can suggest me or guide me to get APIs. Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'django.db.models.query.QuerySet'> class SearchView(APIView): def get(self, request): user = self.request.user data = {} q = request.GET.get('q','') customer_obj = Customer.objects.filter(Q(customer__icontains=q) | Q(country__icontains=q) | Q (industry__industry__icontains=q) | Q(location__icontains=q) | Q(outcome__icontains=q) | Q(contact_person__icontains=q)) data['customers'] = CustomerSerializer(customer_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Customer.objects.all() elif user.groups.name == 'Manager': return Customer.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Customer.objects.filter(assigned_to=user) events_obj = Event.objects.filter(Q(status_type__icontains=q) | Q(customer_name__customer__icontains=q) | Q(activity_type__icontains=q) | Q(priority_type__icontains=q) | Q(visibility_type__icontains=q) | Q(organization_type__icontains=q) |Q(contact_name__icontains=q) | Q(location__icontains=q) | Q(subject__icontains=q)) data['events'] = EventSerializer(events_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Event.objects.all() elif user.groups.name == 'Manager': return Event.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Event.objects.filter(assigned_to=user) inquiry_obj = Newinquiry.objects.filter(Q(customername__icontains=q) | Q(types__icontains=q) | Q(region__icontains=q) |Q(owner__icontains=q) | Q(irr_no__icontains=q) | Q(contactperson__icontains=q) | Q(targetdate__icontains=q) | Q(briefinquirydescription__icontains=q)) data['inquirys'] = NewinquirySerializer(inquiry_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Newinquiry.objects.all() elif user.groups.name == 'Manager': return Newinquiry.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Newinquiry.objects.filter(assigned_to=user) customer_po_obj = PoDetail.objects.filter(Q(customer_name__customer__icontains=q) | Q(region__icontains=q) … -
Make sure all list items based on fields exists in table efficiently
I have a model like this: class MyModel(models.Mode): foo = models.CharField(...) bar = models.CharField(...) and I have a list contains foo and bar field values. I want to check all of items in this list, exists in the database. For example: my_list = [{'foo': 'foo_1','bar': 'bar_1'}, {'foo': 'foo_2','bar': 'bar_2'}] I want to check all records exists values corresponding to the list items fields in the database. I can change my list structure. I can do it with for loop but I want to find more efficient way. Is it possible with single query?. Is there any suggestion? -
Django user.save() method
I am working on two legacy databases, the mysql stores all data and mongodb stores just images. I want to implement a method such that when the user saves the form, that has data and an image - the data should be stored in mysql which it does right now, and an image to the mongodb. The mysql stores a reference id to the image that is stored in the mongodb so I need to generate one for mysql. Since storing image in mongodb requires some additional work because it is stored in chunks in my case { "contentType": "png", "md5": "20481950baf03b7f467f824739eb68c4", "chunks": [ { "data": { "$binary": { "base64": "binarydata", "subType": "00" } } }, { "data": { "$binary": { "base64": "binarydata", "subType": "00" } } } ] } ] So I need to convert the image to base64 and so on, therefore I want to have something like a method on save that will create an uuid for mysql image id, and after that to use this uuid to send it with the processed image to the mongodb Here is my user model class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4) username = models.CharField( max_length=40, blank=True, null=True, unique=True, … -
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request"
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request" I am facing this error when trying to use 2 request.session(). In my code my using two request.session() to store variables.After one request successfully completed,its going to another request and throwing this error. request.session['dataset1'] = dataset1.to_json() request.session['total_cols'] = total_cols // getting error here Please help to resolve the same. -
Invalid HTTP_HOST header even if set properly in settings.py
I am getting this error if I access it, DisallowedHost at /accounts/login Invalid HTTP_HOST header: 'galentichrms.tk'. You may need to add 'galentichrms.tk' to ALLOWED_HOSTS. I know what this means & I have properly set the galentichrms.tk in my settings.py like this, ALLOWED_HOSTS = ['galentichrms.tk', '45.93.100.82',] It was working till friday but today getting this error. I have tried to set '*' in the ALLOWED_HOSTS but still getting the same error.I am using nginx+gunicorn for the server. Any help would be appreciated.Please let me know if you need more details. -
How to save polygon data on Elasticsearch through Django GeoShapeField inside NestedField?
The models looks like - class Restaurant(models.Model): zones = JSONField(default=dict) The document looks like- @registry.register_document class RestaurantDocument(Document): zone = fields.NestedField(properties={"slug": fields.KeywordField(), "polygon_zone": fields.GeoShapeField()}) class Index: name = 'restaurant_data' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Restaurant def prepare_zone(self, instance): return instance.zone After indexing the mapping looks like- "zone": { "type": "nested", "properties": { "polygon_zone": { "type": "geo_shape" }, "slug": { "type": "keyword" } } } But when I am saving data on zones field by following structure- [{"slug":"dhaka","ploygon_zone":{"type":"polygon","coordinates":[[[89.84207153320312,24.02827811169503],[89.78233337402344,23.93040645231774],[89.82833862304688,23.78722976367578],[90.02197265625,23.801051951752406],[90.11329650878905,23.872024546162947],[90.11672973632812,24.00883517846163],[89.84207153320312,24.02827811169503]]]}}] Then the elasticsearch mapping has been changed automatically by the following way- "zone": { "type": "nested", "properties": { "ploygon_zone": { "properties": { "coordinates": { "type": "float" }, "type": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } }, "polygon_zone": { "type": "geo_shape" }, "slug": { "type": "keyword" } } } That's why when I try to search on zone__polygon_zone field, it always returns empty because its not polygon type data. So, how can I save polygon data on elasticsearch trough django by nested geoshape field? -
How to get an a value for an particular record only (by ignoring filter condition ) in django ORM
For the the below model, class Comments(models.Model) comment_text= models.CharField(max_length=1000) type = models.CharField(max_length=5) date = models.DateTimeField(default=timezone.now()) In my views, I am getting the latest comments with text>125 . now If the comment type is "System", I have to display those comments by ignoring the filter condition (even though they are less than 125 chars) with regulars comments properly sorted by latest how to achieve it ? In short the filter condition shouldn't apply on comments of type 'System' (but should apply on all other comments)and it should should appear in the results with all other comments in the sorted order. comments=Comments.objects.filter(comment_text__length__gte=125).order_by("-date") -
django inspectdb on mongodb returns empty file
I am runnign django inspectdb on a mongodb database and it returns this # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models In the mongodb I have documents that store image chunks, ask if you need more details -
in django ,how to sum a int field and two float field in jsonb using postgresql
I have a model like this: class Priority(models.Model): base = models.FloatField(default=0) job = models.JSONField() users = models.JSONField() and both job and users are similar. like job = {'a':1,'b':2}, user = {'c':3,'d':4} I want to get the sum ( base + job__a + users__c) how can I write the filter statement, and raw sql is fine too. Thanks -
django connect to mysql and mongodb
I have 2 databases mysql and mongo. On mysql people hold all data and on mongo just images. I have defined them like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '1*****', 'PORT': '1*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, } } } Now I want to run inspectdb on mongodb and I het this error manage.py inspectdb --database mongodb django.db.utils.ConnectionDoesNotExist: The connection mongodb doesn't exist The host password port is ok -
Django and Postgres inserting into many-to-many table not working
I'm using python and psycopg2 to scrape some data and insert them into my database. I've already created the movies and actors tables inside my Django models.py and inside my movies table, there is a many to many relationship between movies and actors table. when I create a movie from Django-admin I select which actors are included in the movie and everything works fine and all the related actors for that movie will show up on my website. But the problem is that when I try to insert scraped data into my database outside of my Django project folder, the related actors won't be shown on my website because obviously, I have not set the many to many relationship between them. I have tried creating a junction table using SQL commands which gets the movie id and the actor's id and links them together but I don't know how I should tell Django to use that table and show the related actors for each movie. I would really appreciate it if someone could help me with this. -
Django image not getting uploaded into my 'media/user_profile_picture' folder
So , my website has a feature where user can upload an image of themselves for their profile picture when they register their account . The model for the same is as follows : class Buyer(models.Model): name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BigIntegerField() email = models.EmailField(max_length=20) address = models.CharField(max_length=100) city = models.CharField(max_length=30) state = models.CharField(max_length=30) pincode = models.IntegerField() dp = models.ImageField(upload_to='user_profile_picture/', blank=True, null=True) created_on = models.DateField(auto_now_add=True, blank=True, null=True) created_by = models.OneToOneField(User, related_name='buyer', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name Now for this model , I have made the following views to extract the relevant data (including images) from the form inside the template when the submit button is pressed @login_required def buyer_profile_details(request): if request.method == 'POST': # creating the buyer object firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') phone = request.POST.get('phone') email = request.POST.get('email') city = request.POST.get('city') state = request.POST.get('state') address = request.POST.get('address') pincode = request.POST.get('pincode') # dp is the user submitted image which I want to get from the form dp = request.POST.get('dp') Buyer.objects.create(name=firstname, last_name=lastname, phone=phone, email=email, address=address, city=city, state=state, pincode=pincode, dp=dp, created_by=request.user) UserType.objects.create(user_type=2, created_by=request.user) return redirect('my_profile') return render(request, 'new_buyer_profile_details.html', {}) And finally this is the template containing the form that I made for getting … -
How to configure the JWT token in django-graphql-jwt to obtain the userId in the token instead of just the username?
TLDR - But by default the JWT token sent from the backend only includes the username. I want the userId as well.This is what it contains currently:- HEADER:ALGORITHM & TOKEN TYPE { "typ": "JWT", "alg": "HS256" } PAYLOAD:DATA { "username": "admin", <---- I have the username already. Need the userId as well! "exp": 1621845856, "origIat": 1621845556 } VERIFY SIGNATURE HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret ) secret base64 encoded I have a Django GraphQL API (using Graphene, django-graphql-auth, django-graphql-jwt) and an Angular frontend. I have authentication setup fully. Now the issue I'm facing is that I'm storing the token in the localstorage and so when the user opens the browser again, I want to verify that token and use just the information in there to obtain the user's id and then use that userId to fetch their user profile information, which is an essential step to complete the login process. I am not sure how to customize the payload to include the userId as well. So that when the user opens the browser after shutting down, I can simply use just the information in the token to fully log them in. I'm very new to both Python and Django. … -
Video Bookmark Using django
How to add video bookmark using django? I am creating a simplle project,in which i want to add a video bookmar it will make better satisfaction for me.Anyone can suggest any tutorial or other sources? -
Django error 'SessionStore' object has no attribute '_session_cache'
the error came out of nowhere, I just woke up with it, i need a quick fix I am using legacy database mysql, yesterday it worked well. Now I want to add one more database and while adding this error popped up. I have deleted all changes but error is still here. This is how I tried to add the new database. I have a table that stores djago session keys all ok DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '1*****', 'PORT': '1*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, } } } AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PersonalProjects\AuthenticationProject\auth\app\views.py", line 14, in home return render(request, 'app/common/home.html', context) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\template\loader.py", line 62, … -
Combine django and react
I am doing this using axios to combine django and react. While running the program in the command prompt I have to use 2 command prompt! One for running (npm start) And the another for backend (python manage.py runserver) My questions: Is there a way to run a single command in a single command prompt then both the commands should managed. How industries merge them both 🤔 Can we use the same program and change as an apk file and use in mobile app? -
'NoneType' object is not iterable in Django rest framework
I am trying to build a post API for creating the products with their variants. But I am getting this error. I am not sure why it's showing. TypeError at /api/addproducts, 'NoneType' object is not iterable My full traceback is as follows: Traceback: File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/generics.py" in post 192. return self.create(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/mixins.py" in create 21. self.perform_create(serializer) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/mixins.py" in perform_create 26. serializer.save() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/serializers.py" in save 214. self.instance = self.create(validated_data) File "/home/aakashlabs/rupseonline/apps/products/api/serializers.py" in create 152. for variants_data in variants_data: My models: class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = … -
Cannot pass JavaScript variable to Django View.py
I have a JavaScript function that will get the user input and store it into an array called tableData. I want the tableData value in javascript to be use in Django view.py. I had tried to use AJAX and post method to send my tableData. But whenever i clicked on submit it show me error. Html template <!DOCTYPE html> <html lang="en"> <html> <head> <link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> .buttonSubmit { background-color: #4caf50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .del_img { background-color: Transparent; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } body { font-family: "Quicksand", sans-serif; } .button { border-radius: 50px; background-color: #ff9633; border: none; color: #ffffff; text-align: center; font-size: 15px; padding: 10px; width: 80px; transition: all 0.5s; cursor: pointer; margin: 5px; margin-left: 500px; } .button span { cursor: pointer; display: inline-block; position: relative; transition: 0.5s; } .button span:after { content: "\00bb"; position: absolute; opacity: 0; top: 0; … -
Django:Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name
I am. trying to. build a search function for my django project base on the enter link description here and the error message popped out "Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name." i have done the searching most of the advise asking me to check if the spelling is error like my "search" in url or my search.html in my render however, i have tried all the solution it still can't work here is some of my code urls.py: from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm,VendorForm def search_product(request): if request.method == "POST": query_name = request.POST.get('title', None) if query_name: results = Product.objects.filter(name__contains=query_name) return render(request, 'products/search.html', {"results":results}) return render(request, 'products/search.html') views.py from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm,VendorForm def search_product(request): if request.method == "POST": query_name = request.POST.get('title', None) if query_name: results = Product.objects.filter(name__contains=query_name) return render(request, 'products/search.html', {"results":results}) return render(request, 'products/search.html') search.html <!DOCTYPE html> <html> <head> <title>Django Search</title> </head> <body> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="name"> <input type="submit" name="submit" value="Search"> </form> {% for result in results %} <p>{{result.name}}</p> {% endfor %} </body> </html> and following is my … -
What is the proper way to start the Bagroundscheduler Apscheduler
I have a django rest framework application, whenever a request comes to this API i have to schedule an action to be performed later by the BackgroundScheduler at a specific time. Here is what i did: in views.py from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore def do_someting(): print("doing someting ...") class HumanAgentManagerView(APIView): def post(self, request): timeout = request.data["timeout"] activation_date = datetime.now() + timedelta(minutes=timeout) try: scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") s = scheduler.add_job(do_someting, 'date', run_date=activation_date, args=[]) try: scheduler.start() except: pass except: pass return Response({"success": "ok"}) So what i did here, at each request that comes to this endpoint by a user, i initialize a new scheduler instance, add the job to it then start it. My question is : Is this the proper way to start and implement the scheduler i saw in this link django - apscheduler how to keep job when uwsgi restart a different implementation of the BackgroundScheduler it instanciate it once and uses that instance for adding all jobs. I appreciate your help and advices in advance.