Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement multiple filters with django_filters
So I'm currently working on an app and I'm having some problems with using multiple filters in the same function. I have a SortFilter which works. This is a dropdown menu from which you can sort on price for instance. Now I'm also trying to implement a checkbox filter where you can filter on all the brands found in the 'brand' attribute of the model. But if a user has selected a filter from the dropdown menu I still want this filter selected when using the checkbox filter. How can I do this? My code looks like this: filter.py: class SortFilter(django_filters.FilterSet): ORDER_BY_CHOICES = ( ('-discount_sort', 'Hoogste korting'), ('-new_price', 'Hoogste prijs'), ('new_price', 'Laagste prijs'), ) order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order') class Meta: model = Product fields = [] def filter_by_order(self, queryset, name, value): return queryset.order_by(value) class CheckboxFilter(django_filters.FilterSet): brand = django_filters.ChoiceFilter(choices=[]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['brand'].extra['choices'] = [ (brand, brand) for brand in Product.objects.values_list('brand', flat=True) ] class Meta: model = Product fields = ['brand'] .html (dropdown part): <form method="get" class="form-inline"> <select class="single-select" name="order_by" id="order_by" onchange="this.form.submit()"> <option>Sorteer op:</option> <option value="-discount_sort">Hoogste korting</option> <option value="new_price">Laagste prijs</option> <option value="-new_price">Hoogste prijs</option> </select> </form> desired .html for checkbox: <form method="get" class="form-inline" id="checkboxes"> <ul> <li><a href="#">Applied … -
Django problem with DeleteView deleting parent content
I have two models: a Project model and ProjectNotes. ProjectNotes are notes that are related to Projects. The ProjectNotes model has a project field that is a foreign key of the related Project. The problem I have is that when I delete a note on a project, the entire project is deleted. Only the note should be deleted. I think I have on_delete=models.cascade set up correctly on the ProjectNotes model. So I think the issue is with the view. The models: class ProjectManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = ( Q(title__icontains=query) | Q(description__icontains=query) # Q(slug__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs def get_with_counted_notes_documents_todos(self): queryset = self.get_queryset().annotate( num_notes=Count('notes'), num_documents=Count('project_documents'), num_todos=Count('todo_group') ) return queryset class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) tags = tagulous.models.TagField(to=SiteWideTags, blank=True, related_name='projects_tags') objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) class ProjectNotesManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = ( Q(title__icontains=query) | Q(body__icontains=query) # Q(slug__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with … -
I am trying to convert a canvas element to a dataURL but the image is cut short
I'm trying to send an image of a hand taken with a live feed from a webcam to my backend to predict the hand gesture. HTML: <form method="POST" enctype="multipart/form-data"> <div id="videos"> <video class="video-player" id="user-1" autoplay playsinline></video> <canvas class="output_canvas" width="1280px" height="720px"></canvas> <canvas class="video-player" id="computer" autoplay playsinline></canvas> </div> </form> The js method I'm trying to use when pressed it should use mediapipe to draw lines on the hand, and as soon as it has recognized a hand send that image to the backend let playGame = async () => { const videoElement = document.getElementsByClassName('video-player')[0]; const canvasElement = document.getElementsByClassName('output_canvas')[0]; const canvasCtx = canvasElement.getContext('2d'); let screenshotSent = false; function onResults(results) { canvasCtx.save(); canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height); canvasCtx.drawImage( results.image, 0, 0, canvasElement.width, canvasElement.height); if (results.multiHandLandmarks) { for (const landmarks of results.multiHandLandmarks) { drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, {color: '#00FF00', lineWidth: 5}); drawLandmarks(canvasCtx, landmarks, {color: '#FF0000', lineWidth: 2}); } if (!screenshotSent) { //Take a screenshot of the canvas and send it to the server to be processed let screenshot = canvasElement.toDataURL('image/png'); console.log(screenshot); let response = fetch('/play_game/' + game_id + '/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ screenshot: screenshot, }) }); screenshotSent = true; } } } const hands = new Hands({locateFile: (file) … -
MultiValueDictKeyError at /signin/
I am tryin to add an remember me option to my login page. Whenever i try logining and i click on the remember me option, everything works fine. When i do not click on it, it raises this error. Here is my forms.py class Signin(forms.Form): username = forms.CharField( max_length=9, widget=forms.TextInput( attrs={ "id": "input_64", "name": "q64_typeA", "data-type": "input-textbox", "class": "form-textbox validate[required]", "data-defaultvalue": "", "size": "20", "placeholder": "180591001", "data-component": "textbox", "aria-labelledby": "label_64", "required": "", } ), ) password = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={ "id": "first_66", "name": "q66_name66[first]", "class": "form-textbox validate[required]", "data-defaultvalue": "", "autoComplete": "section-input_66 given-name", "size": "10", "data-component": "first", "aria-labelledby": "label_66 sublabel_66_first", "required": "", "placeholder": "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022", } ), ) remember = forms.BooleanField(required=False, initial=False) views.py def signin(request): if request.user.is_authenticated: return redirect(index) if request.method == "POST": form = Signin(request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] remember = request.POST["remember"] user = User.objects.filter(username=username).exists() if user: get_user = User.objects.filter(username=username) check_pass = check_password(password, get_user[0].password) if not check_pass: messages.error(request, "incorrect password") return redirect(signin) else: login(request, get_user[0]) if not remember: request.session.set_expiry(0) return redirect(index) else: messages.error(request, "Invalid User") return redirect(signin) else: form = Signin() return render(request, "accounts/login.html", {"form": form}) What i want to achieve is to make the remember me option not required. -
How to pass a tuple as a variable to render function in python/django? [closed]
I want to pass a tuple I decleared globally in views.py to a render function. But the categories.html does not see the tuple. views.py: `categories = ( ("0", ""), ("1", "electronics"), ("2", "books"), ("3", "clothes"), ("4", "instruments"), ("5", "other") )` def categories(request): return render(request, 'auctions/categories.html', { "categories":categories }) and categories.html looks like this: <ul> {% for category in categories %} <li>{{category.1}}</li> {% empty %} <li>No Items</li> {% endfor %} </ul> it just print No Items. How can I fix it? I wanted to print all categories -
Double GROUP BY in Django rest framework
I'm trying to do this query: SELECT * FROM series WHERE series.co_uni = 'SOME STRING' AND series.language = 'SOME STRING' AND series.visualization = 1 GROUP BY co_ind, no_ind; In DJANGO with filter result = Series.objects.filter(language = language, co_uni = co_uni, visualization = 1).values('co_ind', 'no_ind').annotate(ci=Count('co_ind'), ni=Count('no_ind')).order_by('co_ind', 'no_ind') Is it possible? I'm getting KeyError: "Got KeyError when attempting to get a value for field `year` on serializer `SeriesSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'year'." -
How to Filter value of model Field based on other model field value in django?
I have a model: class Employee(models.Model): name = models.CharField(max_length=128) nic = models.CharField(max_length=25, unique=True) def __str__(self) -> str: return self.name class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") def __str__(self) -> str: return self.name class Standup(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.DateTimeField(auto_now=True) This is the ViewSet: class StandupViewSet(ModelViewSet): serializer_class = serializers.StandupSerializer queryset = Standup.objects.all() Now when I hit the API to post the data of standup, Standup.employee should display only those employees which are in a particular meeting, it should not display all the employees. Information about a particular team will be retrieved from Standup.team, and Standup.employee should display these employees: Standup.team.members. We will select one employee from the subset of employee list, instead of selecting employee from all the employees. It can be changed dynamically based on the value of Standup.team. Please guide. -
Got an error creating the test database: duplicate key value violates unique constraint "pg_database_datname_index"
Complete Error: Creating test database for alias 'default'... Got an error creating the test database: duplicate key value violates unique constraint "pg_database_datname_index" DETAIL: Key (datname)=(test_chat_app) already exists. I added the pre commit hook in Python-Django to run testcases before commit. It is working fine on my side, but when my collegues trying to commit, the above error occurs. Test cases run successfully but this error doesn't let the commit to complete. I have tried dropping and then recreating database, but in vain. Can anyone help me with this, I am attaching screenshot for setting up pre commit hook. just setup this hook. Working fine on my side, but not on my collegues side I have tried dropping and then recreating database, but in vain. -
I am not getting capture in variables of a form made with django, to put them in a python script
The full stack it's already done, django is running in a server, the views are done,all done, that from is linked in a db, i just uploaded the script.py that will use the variables from that form.I have tried the similar solutions that I found here and nothing worked. the project repository: https://github.com/Mayri1/djangoPrimerProyecto.git My failed attempt: from django import usuarios import paramiko import time HOST = '' PORT ='22' USER = 'xxxxx' PASS= '' datos =dict(hostname=HOST, port=PORT, username=USER)"""if __name__ == '__main__':*# try:*client = paramiko.SSHClient() client.connect(HOST, PORT, USER, PASS, banner_timeout=200) stdin, stdout, stderr = client.exec_command("ppp secret add name=\"" + {{ usuarios.nombre }} +"\" password=\"" + {{ usuarios.contraseña }} +"\" profile=OVPN service=ovpn") time.sleep(1) result = stdout.read().decode()# except paramiko.ssh_exception.AuthenticationException as e:# print('Autenticacion fallida')#export file=flash/prueba_export.backup to=C:\rmikrotikprint(result) Another failed attempt: #views def testing(request): mydata1 = Usuario.objects.filter(nombre='usuario.nombre').values() mydata2 = Usuario.objects.filter(contraseña='usuario.contraseña').values() template = loader.get_template('paginas/usuarios.html') context = { 'usuario': mydata1, 'contraseña': mydata2 } return HttpResponse(template.render(context, request)) In urls: path('testing',views.testing, name='testing'), Another:in views "create" if formulario.is_valid(): formulario.save() mk.recibir(formulario) return redirect('usuarios') in mk.py: def recibir(request): formulario = UsuarioForm(request.POST or None, request.FILES or None) for x, y in formulario.items(): user = x passw = y print(user, passw) return (recibir) -
File upload using Django Post method
I'm trying to post a file from remote server to client server. This can be a large file sometime upto 20k lines. And then store it in the client server for further processing using pandas. Example file.txt: A*B*C* D*E*F* G*H*I* I was able to do the file transfer using the below snippet in my views.py class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format=None): up_file = request.FILES['file'] destination = open('/home/xxx/' + up_file.name, 'wb+') for row in up_file.chunks(): destination.write(row) destination.close() return Response(up_file.name, status.HTTP_201_CREATED) But then again, the file seems to be in binary format for the obvious reasons that the file open mode was binary.. and at the same time when i open the file all the line from the file seem to be in a single line instead of being separated by a new line. output.txt A*B*C*D*E*F*G*H*I* Any pointer on how this can be avoided and is there a way i can do the pandas processing for each line efficiently without impacting performance within the post block itslef? -
Problem with sso-login in Django, Error GET /authorize/?token= HTTP/1.1"404 250
I am trying to run simple Django application. I have already installed simple-sso module in my local app. I tried but not solved. Following images tell us that error is occured when i run localserver. enter image description here enter image description here Following code is some of "settings.py": INSTALLED_APPS = [ 'ssoLogin.apps.ssoLoginConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'simple_sso.sso_server', ] ROOT_URLCONF = 'ssoLogin.urls' # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] SSO_PRIVATE_KEY='ttVCo7bewsATjEPS7CNHd4tIk1ayyBKb1qbPk5DxWZiK4pvyLZQtnpinjPh6fWr3' SSO_PUBLIC_KEY='hGtAakAg7Sh3SffSs2obwAAflMuzbbLBUJUHpk6WrFnxhA9b78EHNoTOr0DsDho3' SSO_SERVER='http://127.0.0.1:8000/server' I used "simple-sso" module correctly according to documentation. I think everything of config(settings.py) is ok but i don't know urls and views are correct. Anyway this is my configuration in urls.py. Following code: from django.contrib import admin from django.urls import path, include, re_path from simple_sso.sso_server.server import Server from simple_sso.sso_client.client import Client from django.conf import settings test_client = Client(settings.SSO_SERVER, settings.SSO_PUBLIC_KEY, settings.SSO_PRIVATE_KEY) test_server = Server() urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), re_path(r'^server/', include(test_server.get_urls())), re_path(r'^client/', include(test_client.get_urls())), ] Server and Client object imported correctly. I think client is working good but I dont know Server works. Maybe Server doesn't work correctly. Need to solve this. -
how to install pipfile packages with pipenv?
I use mac m1. i install the latest version of python(3.11) also i install pipenv with this command: brew install pipenv. also i install rosetta. but when i enter this commands: pipenv shell pipenv install I got this error meesage: Installing dependencies from Pipfile.lock (1fd85c)... An error occurred while installing asgiref==3.5.2 ; python_version >= '3.7' --hash=sha256:4a29362a6acebe09bf1d6640db38c1dc3d9217c68e6f9f6204d72667fc19a424 --hash=sha256:1d2880b792ae8757289136f1db2b7b99100ce959b2aa57fd69dab783d05afac4! Will try again. An error occurred while installing asttokens==2.0.8 --hash=sha256:e3305297c744ae53ffa032c45dc347286165e4ffce6875dc662b205db0623d86 --hash=sha256:c61e16246ecfb2cde2958406b4c8ebc043c9e6d73aaa83c941673b35e5d3a76b! Will try again. An error occurred while installing crispy-tailwind==0.5.0 --hash=sha256:65cfcdf8dce96be37c99578e2688ed2d0067e6ff633baaf657358b3b3be052c7 --hash=sha256:0041c85b73b0a197e312ab969bd505aa1f96752a6a50324377287c2b6be3c0cb! Will try again. An error occurred while installing decorator==5.1.1 ; python_version >= '3.5' --hash=sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330 --hash=sha256:b8c3f85900b9dc423225913c5aace94729fe1fa9763b38939a95226f02d37186! Will try again. An error occurred while installing dj-database-url==1.0.0 --hash=sha256:cd354a3b7a9136d78d64c17b2aec369e2ae5616fbca6bfbe435ef15bb372ce39 --hash=sha256:ccf3e8718f75ddd147a1e212fca88eecdaa721759ee48e38b485481c77bca3dc! Will try again. An error occurred while installing django==4.1 --hash=sha256:032f8a6fc7cf05ccd1214e4a2e21dfcd6a23b9d575c6573cacc8c67828dbe642 --hash=sha256:031ccb717782f6af83a0063a1957686e87cb4581ea61b47b3e9addf60687989a! Will try again. An error occurred while installing django-appconf==1.0.5 ; python_version >= '3.1' --hash=sha256:be3db0be6c81fa84742000b89a81c016d70ae66a7ccb620cdef592b1f1a6aaa4 --hash=sha256:ae9f864ee1958c815a965ed63b3fba4874eec13de10236ba063a788f9a17389d! Will try again. An error occurred while installing django-crispy-forms==1.14.0 --hash=sha256:35887b8851a931374dd697207a8f56c57a9c5cb9dbf0b9fa54314da5666cea5b --hash=sha256:bc4d2037f6de602d39c0bc452ac3029d1f5d65e88458872cc4dbc01c3a400604! Will try again. An error occurred while installing django-extensions==3.2.0 --hash=sha256:4c234a7236e9e41c17d9036f6dae7a3a9b212527105b8a0d24b2459b267825f0 --hash=sha256:7dc7cd1da50d83b76447a58f5d7e5c8e6cd83f21e9b7e5f97e6b644f4d4e21a6! Will try again. An error occurred while installing django-jalali-date==1.0.1 --hash=sha256:bb872f58c2b956fb49e26abec5d13753179bc30a7304424adb102672473c1f74! Will try again. An error occurred while installing django-quill-editor==0.1.40 --hash=sha256:276bf3e344531c923b82012f04cec8373c3239d9f7124d4f2bce5f8c5f2b5749 --hash=sha256:26b42aef27168517898c25207d22202402e2816d4a1fa9e3fcc083ae1da0a70c! Will try again. An error occurred while installing django-widget-tweaks==1.4.12 --hash=sha256:fe6b17d5d595c63331f300917980db2afcf71f240ab9341b954aea8f45d25b9a --hash=sha256:9bfc5c705684754a83cc81da328b39ad1b80f32bd0f4340e2a810cbab4b0c00e! Will try again. An error occurred while installing djangorestframework==3.13.1 ; python_version >= '3.6' --hash=sha256:24c4bf58ed7e85d1fe4ba250ab2da926d263cd57d64b03e8dcef0ac683f8b1aa --hash=sha256:0c33407ce23acc68eca2a6e46424b008c9c02eceb8cf18581921d0092bc1f2ee! … -
Django api giving Invalid Padding error for multi api
In my project, multiple apis have started giving Invalid padding errors at the same time I don't know if this error is coming can anyone help or guide me through this problem -
How to get the last record with a condition in Django
I am trying to get the last record of the table in Django with a condition. Model: Rooms id room staff_id 1 103 1000 2 105 1000 3 107 1555 the staff (number 1000) has two records, but I want to get just the last record of him. getStaffRecords = Rooms.objects.get(staff_id=1000) staffRoom = getStaffRecords.room and here I get an error, because I have more than one record. Error: get() returned more than one Rooms-- it returned 2! Anybody has a solution? I tried to use the methode like this: getStaffRecords = Rooms.objects.get(staff_id=1000).last() staffRoom = getStaffRecords.room but it didn't work, bcause in this case, "get" isn't recognized by Django. -
How to insert a value from a dict in a django annotation using each id from queryset
I have a simple dict containing ids with values associated like: {1:True, 2:False} I also have a queryset that have the same ids listed above in an atribute named user_id, but I need to add a new field to my objects on queryset with the values from my dict. Lets suppose the field I want to add is called is_admin, so I need to create a field on the object with id 1 on my queryset with the value True. What I tried to do is: my_dict= {1:True, 2:False} queryset = queryset.annotate( is_admin=Value(my_dict.get(F("user_id")), output_field=BooleanField()) ) But what happen is that I'm receiving null on is_admin. I tried to do the code below and it works: queryset = queryset.annotate( is_admin=Value(my_dict.get(1), output_field=BooleanField()) ) So I think is something wrong with my use of F expression. I will appreciate any help. -
how to have a TimeField with auto increment of 5 minutes (django)
I have a model in django that consists of these fields: device = models.CharField(max_length=150, null=True) time_received = models.TimeField(auto_now_add=True, null=True) display_time = [ i want it to have same hour as time_received , minute to be started at 00 and then have interval of 5 and finally second to be 00 ] the reason i want to do this , is to display time in an orderly manner. for example: device A is received at 8:01:20 ---> device A is shown as 8:00:00 device A is received at 8:07:22 ---> device A is shown as 8:05:00 one final note: I need to store both display time and received time in postgresql thanks for helping -
Centralised Django Web application ideas
I have a djnago web server for webservices (Djnago+Gunocrn+Nginx) which connects to one client URL and provide servers. My requirement is, I have multiple clients on different environment. So we are planning to setup a centralised Django server with (Djnago+Supervisor+Gunocrn+Nginx) setup. Please share some idea on what shoule be considred and best practices. Ideas and Suggestions -
My access to Google Sheets API is being blocked to a URI Redirect Mismatch
I am unable to access my Google sheet, here is the error I get: Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Request details: redirect_uri=http://localhost:57592/ Below I'll share my code, relevant parts of the credentails file as well as my Google Cloud console configurations I have in place. Just to note, From my inexperienced eyes (as far as python and google console is concerned), it seems as if I've checked the right boxes based on what I've found on StackOverflow. PYTHON: from __future__ import print_function from datetime import datetime import pickle import os.path import pyodbc from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # connecting to the database connection_string = 'DRIVER={driver};PORT=1433;SERVER={server};DATABASE={database};UID={username};PWD={password}; MARS_Connection={con}'.format(driver= 'ODBC Driver 17 for SQL Server', server= server, database= database, username=username, password=password, con='Yes') conn = pyodbc.connect(connection_string) print("Connected to the database successfully") # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. # https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=0 SPREADSHEET_ID = spreadSheetID RANGE_NAME = 'CAPS!A2:K' #def dataUpload(): def dataUpload(): creds = None # The … -
Wagtail: Limit choice dynamically based on current object
How can I limit the choices for the districtobject field in wagtail admin? class DistrictPage(Page): districtobject = models.ForeignKey(DistrictTranslated, on_delete=models.SET_NULL, null=True, blank=True) I know that I can use "limit_choices_to" for basic limitations with Q. But I want to use a more dynamic approach which allows me to use the "content" of the current object. (Like self.attribute ... etc) For example: def my_limit_function(self): 1. get parent page 2. read date from parent page and extract this information for a filter query -
Sorting QuerySet by a key of a JSONField is super slow
Let's say my model is: class MyModel(models.Model): code = CharField(...) dynamic_columns = JSONField(null=False, default=dict, encoder=DjangoJSONEncoder) This : MyModel.objects.all().order_by("dynamic_columns__some_key") goes a loooot slower than MyModel.objects.all().order_by("code") I know it's not a surprising result, however are there tricks to optimize the first operation ? Like would defining the schema of dynamic_columns somehow help ? Thanks in advance ! -
Django app with pandas processing not loading specific page on railway.app but runs fine locally, How to troubleshoot?
I am facing an issue where my Django application, that uses pandas processing code, is not loading a specific page when deployed on https://railway.app service and keeps giving an application server error, whereas it runs fine on a local server but takes more than 10-11 seconds for loading the specific page. I would like to know the possible causes of this issue and how can I troubleshoot it. Note: I am using an API build with Django Rest framework. View that renders the pandas processed data: def nsebse(request): if request.user.is_authenticated: endpoint1 = rq.get('https://stockindex.up.railway.app/api/bse/').json() endpoint2 = rq.get('https://stockindex.up.railway.app/api/nse/').json() bseData = helperForBSENSE(endpoint1) nseData = helperForBSENSE(endpoint2) return render(request,'nsebse.html',{'bseData':bseData,'nseData':nseData}) else: return render(request,'notauth.html') Helper function used in above segment: def helperForBSENSE(data): df = pd.DataFrame(columns = ['id','date','open','high','low','close','adj_close','volume']) for i in range(len(data)): item = data[i] df.loc[i] = [item['id'],item['date'],item['open'],item['high'],item['low'],item['close'],item['adj_close'],item['volume']] df['date']= pd.to_datetime(df['date']) today, req_day = datetime(2023,1,12), datetime(2022,1,12) one_year_df = df[(df['date'] <= today) & (df['date'] > req_day)] fifty_two_week_high = max(one_year_df['high']) fifty_two_week_low = min(one_year_df['low']) day_high = df[df['date']==today]['high'] day_low = df[df['date']==today]['low'] previous_day = today - pd.Timedelta(days=1) today_close = float(df[df['date']==today]['close']) prev_close = float(df[df['date']==previous_day]['close']) today_open = float(df[df['date']==today]['open']) today_gain_or_loss = float(today_close - prev_close) data = { 'today_open':today_open, 'today_close':today_close, 'prev_close': prev_close, 'today_gain_or_loss' : today_gain_or_loss, 'day_high':float(day_high), 'day_low':float(day_low), 'fifty_two_week_high':fifty_two_week_high, 'fifty_two_week_low':fifty_two_week_low, 'xAxis':list(df['date']), 'yAxis':list(df['close']), } return data here is a live … -
Response Data isn't even showing in console. I have tried everything. But not getting a proper solution for that
I am sending request from react to django to know if we've this user or not. django is sending response back but it's not even showing in console in react. here is my React Code: const BASE_URL = 'http://127.0.0.1:8000/writter-login/' function TeacherLogin() { const[writterLoginData, setWritterLoginData] = useState({ 'writter_email' : '', 'writter_password': '' }); const handleChange = (event) => { setWritterLoginData({ ...writterLoginData, [event.target.name]:event.target.value }) } const submitForm = () => { const writterLoginFormData = new FormData(); writterLoginFormData.append('writter_email',writterLoginData.writter_email) writterLoginFormData.append('writter_password',writterLoginData.writter_password) try { axios.post(BASE_URL,writterLoginFormData).then((res) => { console.log('Found') console.log(res.data) if(res.data === true) { localStorage.setItem('writterLoginStatus',true) window.Location.href="/writter-dashboard"; } }) } catch (error) { console.log(error) } } const writterLoginStatus = localStorage.getItem('writterLoginStatus') if(writterLoginStatus === 'true'){ window.Location.href="/writter-dashboard"; } return ( <div className='App'> <Form.Label>Email address</Form.Label> <Form.Control value={writterLoginData.writter_name} onChange={handleChange} name ="writter_email" type="email" placeholder="Enter email" /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Form.Label>Password</Form.Label> <Form.Control value={writterLoginData.writter_password} onChange={handleChange} name ="writter_password" type="password" placeholder="Password" /> <Button onClick={submitForm} variant="success me-5" type="submit">Login </Button> ); } export default TeacherLogin; here is my django code: @csrf_exempt def WritterLoginDetails(request): writter_email = request.POST['writter_email'] writter_password = request.POST['writter_password'] writterData = models.Writter.objects.get(writter_email = writter_email, writter_password = writter_password) if writterData: print('data found') return JsonResponse({'bool':True}) else: print('no data found') return JsonResponse({'bool':False}) i have tried to console it in browser and even in network … -
Django equivalent of rails schema annotation
I moved from Rails to Django and was trying to find a library similar to https://github.com/ctran/annotate_models that annotates models using comments in Rails. Does such a library exist? It's a little hard to find due to the inbuilt annotate method in django if it does -
Django Static doesn't work on production even after collectstatic
I'm facing a problem and cannot resolve it. Looking for some advices ! Ok so locally everything works fine, i already run collect static and i collected statics files under a folder named 'static' on my django app folder : app | |- app |- app n°2 |- static So running locally, not a single error and admin have css While i push on production, my app run , proxy (nginx) run ... However, while connectinf to example.com/admin/, css not running my logs from proxy give me this ... "GET /app/static/admin/css/responsive.css HTTP/1.1" 404 179 "https://example.com/admin/login/?next=/admin/" An error 404 occur ? Here is what's my setting.py looks like STATIC_URL = '/app/static/' STATIC_ROOT = '/app/static' Any help will be welcome, i would like to understand the error ! Thank a lot Cheers -
DjangoModelPermissions not working with DRF
I am trying to use Django Rest Framework and face a problem. The problem is when i try to use DjangoModelPermissions it doesn't follow the permission from Django admin panel. What I excepted, is that when I set permission Projects|projects|can view projects then user can see the output. Here are my codes: Views.py from rest_framework import viewsets from rest_framework.permissions import IsAdminUser, IsAuthenticated, DjangoModelPermissions from django.shortcuts import get_object_or_404 from rest_framework.response import Response from .models import Projects from .serializers import ProjectSerializer class ProjectsViewSet(viewsets.ViewSet): permission_classes_by_action = {'list': [DjangoModelPermissions]} queryset = Projects.objects.none() serializer_class = ProjectSerializer def list(self, request): queryset = Projects.objects.all() serializer = ProjectSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Projects.objects.all() project = get_object_or_404(queryset, pk=pk) serializer = ProjectSerializer(project) return Response(serializer.data) def get_permissions(self): try: return [permission() for permission in self.permission_classes_by_action[self]] except KeyError: return [permission() for permission in self.permission_classes] serializers.py from rest_framework import serializers from .models import Projects class ProjectSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Projects fields = ('id','name') Django admin site permission for the user: [] Output HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "proj 1" }, { "id": 2, "name": "proj 222" } ] …