Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels working with ws:// but fails to handshake with wss://
nginx setting server { listen 80 default_server; listen [::]:80 default_server; server_name www.sample.co; return 301 https://$host$request_uri; } server { ssl on; listen 443 ssl; listen [::]:443 ssl; server_name www.sample.co; rewrite ^(.*) https://beta.sample.co$1 permanent; ssl_certificate /home/ubuntu/certificate/certificate.crt; ssl_certificate_key /home/ubuntu/certificate/private.key; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } } Running on daphne CMD ["daphne","-b","0.0.0.0","-p","8001","config.asgi:application"] Working fine on ws://xyz.amazonaws.com/ws/sample// Fails to work on wss://xyz.amazonaws.com/ws/sample// Error: WebSocket connection to 'wss://xyz.amazonaws.com/ws/sample//' failed: Error in connection establishment: net::ERR_CERT_COMMON_NAME_INVALID The applications are running on AWS. The websocket is getting called from https. I tried to call the websocket with ws:// from a dummy react app in local it is working fine. -
Upload csv files with unknown columns in a database in django
I'm working on an app which has the following steps: 1. Select a csv file from local machine (user's input) 2. read the file and store it in a sqlite database with the table name "data". If a database already exists, overwrite it with this new data I've seen a couple of tutorials but none seem to answer how to do the second part. Anyone who has done it before or may have an idea as to how to do it? -
Datetime comparison with a timedelta from an F() object
Context : I'm trying to do a condition for a queryset filtering. It implies 2 fields of my model and datetime.datetime.now() (aka. now), one field representing a time delta (a number of minutes) and one field representing a datetime (start_datetime). I'd like to check if start_datetime - now <= time_delta`. General case : I've seen the example (from the doc) in which we're able to compare two date(time)s and a constant timedelta. >>> from datetime import timedelta >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3)) But what if it's a value contained in an other field of my entry? The way I try to instanciate this timedelta is obviously not possible. >>> from datetime import timedelta >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=F('n_timedelta'))) Could there be a solution to achieve this using the ORM features (and not a raw SQL query)? -
Page is opening but search is not working when i am using {% for i in kitty_list %} but in case of {% for i in kitty %} then NoReverseMatch error
// In Below scenario page is opening but search functionality not working when i am using {% for i in kitty_list %} in the template but when i am using {% for i in kitty %} then NoReverseMatch error is coming Url: path('kitty_view',views.kitty_view,name='kitty_view') View: kitty_list = kitty_list.filter(status = status1) kittys = kitty.objects.all() ctx = {'kitty': kitty_list,'kitty_code':kittys} return render(request, 'kitty/kitty_view.html', ctx) //Html page which is giving NoReverseMatch error when {% for i in kitty %} is used. When i am using {% for i in kitty_list %} then page is rendering but serach button is not working template: {% extends 'base.html' %} {% load static %} {% block content %} <form class="form-signin" action="{% url 'kitty_view' %}" method="get"> {% csrf_token %} <div class="form-row"> <div class="mb-3"> <select class="custom-select center-block" name="code1" id="code1"> <option value="">Choose Kitty...</option> {% for j in kitty_code %} <option value="{{ j.code }}"> {{ j.code|add:' - '|add:j.name }} </option> {% endfor %} </select> </div> <div class="mb-3"> <input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus> </div> <div class="mb-3"> <select class="custom-select center-block" name="stat" id="stat" placeholder="Status"> <option value="">Choose Status...</option> <option>A</option> <option>I</option> </select> </div> <div class="mb-3"> <button type="submit" class=" btn btn-info " role="button">Search</button> </div> </div> </form> <table class="table table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">Kitty Code</th> … -
Find file in templates directory
In versions up to 2.2.5 of Django I put my html files that were passed in views as follows: myapp templates myapp index.html But in django 2.2.6 and 2.2.7 when I do this gives the following error: TemplateDoesNotExist at / But when I do: myapp templates index.html The template is found. How in these newer versions does Django handle to identify 2 templates with the same name without needing subdirectory to differentiate? -
Creating DetailApiViewset by using classed based api view
I am trying to create detail api viewset but for now I am getting page not found whenever I go to my "matches/api/matches/1/". ListCreateAPIView works fine. Here are my viewsets: class MatchViewset(viewsets.ViewSetMixin, generics.ListCreateAPIView): serializer_class = MatchSerializer def get_queryset(self): header_token = self.request.META.get('HTTP_AUTHORIZATION', None) print(header_token) if header_token is not None: try: token = sub('Token ', '', self.request.META.get('HTTP_AUTHORIZATION', None)) token_obj = Token.objects.get(key=token) self.request.user = token_obj.user except Token.DoesNotExist: pass print(self.request.user) return Match.objects.filter(creator=self.request.user) class MatchDetailViewset(generics.RetrieveUpdateDestroyAPIView): queryset = Match.objects.all() serializer_class = MatchSerializer and routers: router = routers.DefaultRouter() router.register(r'matches', matches_views.MatchViewset, base_name="matches") Thanks for all answers :) -
dajngo-admin-sortable2 doesn't sort order of SortableAdminMixin
I created an app with django and python3 containing several tutorials, which in turn contain multiple content entrys that are saved in another table. Each tutorial is represented by an entry in the exercises tutorial model. I want to be able to sort the tutorials and the contents in the django admin panel. It works fine for the inline tutorial contents with SortableInlineAdminMixin class. It also works fine if I create new tutorials from scratch without having any objects saved before (it works local on my pc if I clone this project and set it up from scratch) My problem now is, that I have the app setup like you see in the code and pictures below on a ubuntu server with apache, but I can't sort the tutorials (the inline contents still work fine). If i drag and drop them to a new position and reload, they don't save at their new position and fall back to their old position. Tutorial and TutorialContent model: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField # Page for tutorials class Tutorial(models.Model): title = models.CharField(max_length=60) order = models.PositiveIntegerField(default=0, null=False, unique=True) # Timestamp created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['order'] … -
How can I fix django Reverse function to work with the current application?
I have little experience with django and APIs and recently started developing this application. My code structure goes like this: config/ env/ .env files requirements/ __init__.py ... settings/ __init__.py base.py local.py __init__.py urls.py views.py wsgi.py projects/ api/ town/ apps.py urls.py views.py ... core/ models/ town.py serializers/ town_serializer.py ... tests/ test_town.py manage.py this is the file project/api/town.urls.py from django.urls import path from . import views app_name = 'town' urlpatterns = [ path('town/', views.CreateTownView.as_view(), name='town-list'), path('town/<int:pk>/', views.TownViewSet.as_view(), name='town-detail') ] And the file for config/settings/urls.py: from django.contrib import admin from django.urls import path, include # from .views import views urlpatterns = [ path('admin/', admin.site.urls), # path('', views.index) path('api/', include('project.api.city.urls', namespace='city')), path('api/', include('project.api.town.urls', namespace='town')) ] I have used routes like localhost:8000/api/town and I had no problem working with API and they're working just fine. The only problem happans when I am trying to run the test module. This is the part of test that error pops up:-{ from django.db import IntegrityError from django.test import TestCase from project.core.models.town import Town from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status import unittest CREATE_TOWN_URL = reverse('town:town-list') DETAIL_TOWN_URL = reverse('town:town-detail') this is the error: raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'town-detail' with no arguments not found. … -
Accessing server cookies from localhost
I have a dev server at http://dev.example.com. My react app is hosted locally and I need to use the dev server. The problem is that the server cookies have the domain 'dev.example.com' which is not accessible from localhost. I can use a proxy server and set Nginx to proxy_pass to the dev server but I want a simpler solution without a proxy server. What can I do? -
Get Redis client_list from Django console
I have error max number of clients reached. And I want to see who are these all clients (not web app only). I found that Redis have command for that named client_list(). But I was unable to use it from Django shell. from django.core.cache import cache cache.get_list() # Raises: # TypeError: 'list' object is not callable cache.client_list # Returns: # [StrictRedis<ConnectionPool<Connection<host=somehost.amazonaws.com,port=12345,db=1>>>] What is correct way to retrieve the list? -
Django Bulk upload of Large Files
I want to upload a xlsx file to my database.I tried upload a file using Openpyxl package and bulk_create option in the django as given below, model.py, class cardata(models.Model): Name= models.CharField(max_length = 60, db_column = 'Name') Model_Type= models.CharField(max_length = 60, db_column = 'Model_Type') ...... objects = models.Manager() pdobjects = DataFrameManager() def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) views.py, def upload(request): if request.method == "POST": excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file, data_only=True) worksheet = wb.worksheets[0] excel_data = list() for row in worksheet.iter_rows(): row_data = list() for cell in row: if cell.value=='': cell.value='None' row_data.append(str(cell.value).strip()) excel_data.append(row_data) df = pd.DataFrame(columns=excel_data[0], data=excel_data[1:]) df_records = df.to_dict('records') model_instances = [cardata( Name =record['Name'], Model_type =record['Model_type'], Year =record['Year'], Make =record['Make'], ....... ) for record in df_records] cardata.objects.bulk_create(model_instances) return render('success.html') else: return render('upload_form.html') Above code works fine for the upload file having lesser data.When I try to upload a file having more than 5 lacks rows,it throw me the, MemoryError at /upload/ I have to deal with the large datasets. Suggest me a easier and fastest way to upload the data into database model or some codes. Thanks in advance. -
python_socketio with django cause db connection unclosed problem
Backgroud: django + Postgres + socketio Description: python_socketio: I create sync socketio to process some functions, and it will create a persistent thread to process the sockerio events django: in a django handle function ,I call socketio method, such as: class MyDangoHandler(object): def myfunction(self): socket_io_client.emit( event=ClientEvents.MyEvent, data={ "id": 1 } ) and in the sockerio event handler, I will call postgres database to get some data. We know that in a request, django will close the old db connections first,we suppose the main thread is Thread-1, then in the Thread-1, we call the socketio function, it is Thread-2, because of the db connection is threadlocal, so the closed_old_connections methods is unusable for db connections in sockertio(Thread-2), so after the connection created for a long time(> CONN_MAX_AGE), the connections in Thread-2 may still open, but the connection is unusable, it will cause the problem OperationError: server_closed_the_connection_unexpectedly This_probably_means_the_server_terminated_abnormally before_or_while_processing_the_request. Now I solve the problem by closing the old DB connections in socketio handler functions manually, but I don't think it's good enough because we need to close the connections in each handler which will call the database function. And I didn't find the root cause why the connections will be unusable if … -
Django - Insert youtube video in HTMLField
I'm trying to insert a youtube video on a Django HTMLField to look like an iframe, but i can't find the clue for it. Is there any way to insert it or a special field for youtube videos? Thanks! I tried to insert raw html and the link for the video -
How to make google, facebook authentication and token generation in django with flutter
I am using Flutter Google, Facebook login for authentication, i want to know which is best way to authenticate users in django with flutter login. also i want to generate auth token, so that django dont need to authenticate google, facebook login on every request from same user. -
Django: Filter against a value of another row
I'm having a model Foo with with a value field. # models.py class Foo(models.Model): value = models.IntegerField() Now I want to filter all Foo instances that have a greater value than the Foo object with a specific knwon id. pk = 10 obj = Foo.objects.get(pk=pk) qs = Foo.objects.filter(value__gte=obj.value) The question is can I somehow combine the two db queries above into one? -
How to allow google cloud storage to save duplicate files and not overwrite
I am using google cloud storage bucket to save file uploads from my Django web application. However if a file with same name is uploaded, then it overwrites the existing file and i do not want this to happen. I want to allow duplicate file saving at same location. Before moving to google cloud storage when i used my computer's hard disk to save files, Django used to smartly update filename in database as well as hard disk. -
How to authorize swagger ui using JWT Bearer Authorization in Django?
I am using JWT Authorization. Faceing Issue on authorize using Jwt Bearer Authorization. -
ModuleNotFound while running the web app locally
I'm trying to run the project available on GitHub locally as mentioned in the instructions but getting ModuleNotFound error even though I've cloned the whole project and following the instruction in a correct way as mentioned. I'm unable to understand this. Please find the repository here. https://github.com/aasis21/4th_umpire -
Pass Image Read From OpenCV From Django To Reactjs and Show it on Website in Real Time
I have python snippet which gets live feed camera video from IP camera: Load each frame using opencv's read function and pass the loaded frame to face detector. Processed frame with bounding boxes received from a function(in a variable). It show the resultant frame using cv2.imshow function. Now my goal is, instead of using opencv's imshow function I want to show it on website in real time as it's working cv2. So now i am using django-react simple application to show it on website. BUT my question is that how we can show the processed image( in variable array) and pass it from django views.py to react and show it on website page. I have googled so many times but couldn't find anything related to this. Thank You. -
How to create an attribute of model which is consists parts of other attributes
Let's I have a model. class Trips(models.Model): from_point = models.CharField(max_length=50) to_point = models.CharField(max_length=50) trip_desc = models.TextField(max_length=250) seats = models.CharField(max_length=20, blank=True, null=True) price = models.PositiveIntegerField() created_time = models.DateTimeField(auto_now_add=True) new_attribure= ? How to create an attribute so when we're creating an instance of Trips it will take part of attributes from_point, to_point + some unique string? For example: obj1 = Trips('Moscow', 'Dushanbe', 'Some_description', '4', '100', 'date_time', 'MosDushUniquestring') In this case it's taking three first characters of from_point, to_point attributes + some unique string. The idea is to have a unique attribute which has some meaning. -
Sort Dictionary of Dictionaries in Django
I have a dataset {6317637: {'name': 'Le Petit Souffle', 'Votes': 314, 'Cuisines': 'French, Japanese, Desserts', 'AverageCostfortwo': 1100, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6304287: {'name': 'Izakaya Kikufuji', 'Votes': 591, 'Cuisines': 'Japanese', 'AverageCostfortwo': 1200, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.5', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6300002: {'name': 'Heat - Edsa Shangri-La', 'Votes': 270, 'Cuisines': 'Seafood, Asian, Filipino, Indian', 'AverageCostfortwo': 4000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6318506: {'name': 'Ooma', 'Votes': 365, 'Cuisines': 'Japanese, Sushi', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.9', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6314302: {'name': 'Sambo Kojin', 'Votes': 229, 'Cuisines': 'Japanese, Korean', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 18189371: {'name': 'Din Tai Fung', 'Votes': 336, 'Cuisines': 'Chinese', 'AverageCostfortwo': 1000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6300781: {'name': 'Buffet 101', 'Votes': 520, 'Cuisines': 'Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6301290: {'name': 'Vikings', 'Votes': 677, 'Cuisines': 'Seafood, Filipino, Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.2', … -
How to save a value for the Get Request Using Views-Models
I am trying to create a chatbot, I want to create a variable(list/dictionary) the one which is one to save my GET Request, I want to access the value of the variable and manipulate it. After some logical operations, I will use a new variable to save a result and print that result on the same page. -
How to add tag field in django?
Here I have some model and this model should have some tags for making it SEO friendly.For this how can i design my model? Any suggestions or help would be appreciated. my model class TourPackage(models.Model): name = models.CharField(max_length=255) package_detail = models.TextField() image = models.ImageField() booking_start = models.DateTimeField() booking_end= = models.DateTimeField() package_start = models.DateTimeField() #how can i save this tag field for seo purpose #tag = models.CharField() -
Converting csv for fixtures
I am unable to convert test data in CSV format using csv2json.py so that I can use the same in fixtures which should have the format pk, model, and then the fields. [ { "pk": 1, "model": "wkw2.Lawyer", "fields": { "school": "The George Washington University Law School", "last": "Babbas", "firm_url": "http://www.graychase.com/babbas", "year_graduated": "2005", "firm_name": "Gray & Chase", "first": "Amr A" } } ] -
I can import matplotlib.pyplot in one file.py but I cannot import it in view.py in django app
I have plot_file.py which has: import matplotlib.pyplot as plt def plot_graph(): squares = [1, 4, 9, 16, 25] plt.plot(squares) plt.savefig('static/img/sqaure_plot.png', bbox_inches='tight') When I run this, it works and saves the file correctly. I am trying to import this function in the views.py within the same app folder in Django. When I put the import statement in the views.py from plot_file.py import plot_graph as pg And save it and try to initiate runserver I get: ModuleNotFoundError: No module named 'matplotlib' Both the files are in the same folder myapp/plot_file.py myapp/views.py I have installed matplotlib using pip3 install matplotlib. I am using MacOS with python3 installed later. I am using Sublime Text which is compiling on Python3. I do not understand how I can import matplotlib in plot_file.py and not in the views.py file? Beginner here. Thank you in advance.