Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
a live stream site using reactjs and drf
hello guys i'm working on a livestream site using reactjs and drf for server side. and apparaently i want to acheieve three things. when a particular song(div) is clicked on and currently playing, i add a "play" to the class list. now when the user clicked on another song i want to remove that play from the initial div(song) that was clicked on and add it to the current div that was click ASAP. secondly, when the song is been played i'm having a delay in response(like i'd have to click twice first click will fetch the song then the second click will then play it. how can i rectify it so when i click once everything fetches and plays asap. i have used the fetch function and applied a call back yet still having same issues. when i play a song it appears on all audio tags in all divs(music) i think that due to my usesstate setup and the way i am rendering it please how can i sought it so that each music(div) handles there own audio tag when played? Thanks const Home=()=>{ const audio=document.querySelector('#audio') const music_container=document.querySelector('#music_container') const [image, setImage]=useState('') const [posts, setPosts]=useState([]) const [icon,setIcon]=useState(faPlay) const[playing,setPlaying]=useState(false) const[music,setMusic]=useState('') … -
How change the url of an image within an html page in a django project?
I'm new to Django. I have 2 images, one for NP environment and one for Production environment. I have to make each image stay in its given environment. This is to be done in an html page within Django. This html page is the body of an email. can you help me? The image looks like below. And I want to control her link according to the environment she is in <td bgcolor="#fff" align="right" style="padding: 21px 19px 18px"> <img alt="Teste" src="https://.../mail/logo.png" width="210px" /> </td> -
Django Viewset method accepts get request while it's actually a post
I defined my urlpattern as follows: urlpatterns = [ ... path('api/cluster/<int:cluster_id>/topic/save', TopicView.as_view({'post': 'save_topic'}), name='save_topic'), ... and here's my view: class TopicView(viewsets.ViewSet): permission_classes = (IsAuthenticated, IsAdminUser, ) authentication_classes = (JWTAuthentication, ) def save_topic(self, request, cluster_id): # saves specific data I can access this method via GET, but POST is not allowed. My CORS settings is as follows: CORS_ORIGIN_ALLOW_ALL=True I tried: @action(methods=['post'], detail=False) def save_topic(self, request, cluster_id): Nothing changed. What am I missing? -
Can I install Python, Django and other packages on a USB device and and run a server from this USB?
I would like to have a Django server on a Windows machine which is not connected to Internet. For that, would it be possible to install, from another Windows machine connected to Internet, Python, PyCharm, Django and other packages to a USB device that I will then connect to the other Windows machine in order to start the application ? Would it work without problems ? Thanks ! - -
django translation doesn't work although dgango_language cookie is set
It's been 3 days and I'm getting tired of this. Here's my setting file: from pathlib import Path from django.utils.translation import gettext_lazy as _ # 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/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-z$__b9aa(_3!czi7ssop9cr2lae^9)f^!_kq+y_n=+6u=ul!%q" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "mainapp", ] 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.locale.LocaleMiddleware', "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "soroushprojects.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ['templates'], "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", 'django.template.context_processors.i18n', ], }, }, ] WSGI_APPLICATION = "soroushprojects.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # 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",}, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True LAGUAGES = ( ('en', _('English')), ('fa', _('Persian')), ) LOCALE_PTHS = [ BASE_DIR / … -
Why this DeleteView doesn't actually delete the entry in Django?
In my Django app the delete view doesn't work. When I click on an entry the page just refreshes and nothing happens. The entry is not deleted from the database. Creating and updating entries works fine. Is there something wrong with any of the files? microtarjetas/views.py: class DeleteCardView(DeleteView): model = Card template_name = 'microtarjetas/delete_card.html' form_class = CardForm success_url = '/cards/' templates/microtarjetas/delete_card.html: {% extends 'base.html' %} {% load static %} {% block content %} <h2>Delete card</h2> <p>Are you sure you want to delete "{{ object }}"?</p> <form method="post">{% csrf_token %} <input type="submit" value="Confirm" /> </form> {% endblock %} a snippet from templates/microtarjetas/cards.html: <tbody> {% for card in cards %} <tr> <td>{{ card.word_en }}</td> <td>{{ card.word_es }}</td> <td><a href="{% url 'update_card' card.pk %}">update</a></td> <td><a href="{% url 'delete_card' card.pk %}">X</a></td> </tr> {% endfor %} </tbody> forms.py: from django import forms from .models import Card class CardForm(forms.ModelForm): class Meta: model = Card fields = "__all__" models.py: class Card(models.Model): word_en = models.CharField(max_length = 30) word_es = models.CharField(max_length = 30) def get_absolute_url(self): return "/cards" def __str__(self): return f"{self.word_en} --- {self.word_es}" urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('cards/', views.CardsView.as_view(), name='cards'), path('cards/new', views.CreateCardView.as_view(), name='create_card'), path('cards/<pk>/delete/', views.DeleteCardView.as_view(), name='delete_card'), path('cards/<pk>/update/', views.UpdateCardView.as_view(), … -
nginx 502 bad gateway error with Django webapp hosted on AWS EC2
Ever since rebooting my Ubuntu EC2 instance, I have an issue with nginx giving a 502 error for my site. I didn't change any settings before the reboot and the site was working fine before then. Error from /var/log/nginx/error.log: 2022/12/06 21:10:54 [error] 1503#1503: *4 connect() failed (111: Unknown error) while connecting to upstream, client: ###.##.##.###, server: ##.#.###.###, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "##.#.###.###", referrer: "http://##.#.###.###/" Here is my config in /etc/nginx/sites-available/: server_tokens off; access_log /var/log/nginx/esms.access.log; error_log /var/log/nginx/esms.error.log; # This configuration will be changed to redirect to HTTPS later server { server_name .##.#.###.###; listen 80; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; } location /static { autoindex on; alias /home/ubuntu/ESMS/esms/static/; } } And the output of netstat -plnt: sudo netstat -plnt Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 664/sshd: /usr/sbin tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1567/nginx: master tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 420/systemd-resolve tcp6 0 0 :::22 :::* LISTEN 664/sshd: /usr/sbin tcp6 0 0 :::80 :::* LISTEN 1567/nginx: master -
Nginx 400 Error - client sent plain HTTP request to HTTPS port while reading client request headers
I recently added a SSL certificate to my website using Let's Encrypt and have noticed that when I try to access my website using either HTTP or HTTPS, the site will load correctly most of the time, but sometimes it will return a 400: Bad Request error. Refreshing the page after that will usually return me to the working HTTPS site, but I am having trouble understanding why this error only occurs sometimes. The current site is using Django, Gunicorn, Nginx, and AWS EC2 with a load balancer and the SSL certificate is for the EC2 instance, if this makes a difference. nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log info; ## # Gzip Settings ## gzip on; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } sites-enabled .conf file server { listen 80; server_name … -
How to retrieve attributes from a foreign key related model to another foreign key related model?
I'm using django 4.1.2 with python 3.10.8. I have three models one for user management, one for questions and another for answers. They are described below: class User(AbstractUser): phone_number = models.CharField(max_length=14, unique=True) first_name = models.CharField(max_length=40) father_name = models.CharField(max_length=40) email = models.EmailField(unique=True, required=True) age = models.CharField(max_length=3) username = models.CharField(max_length=8, required=True) class Question(models.Model): question = models.CharField( max_length=500, null=False, unique=True ) creating_staff = models.ForeignKey( User, null=False, on_delete=models.PROTECT, to_field="phone_number", ) options = models.JSONField(null=False) correct_option = models.CharField(max_length=250, null=False) question_ts = models.DateTimeField(auto_now_add=True, null=False) class Meta: verbose_name = "Question" def __str__(self) -> str: return f"{self.question}" class Answer(models.Model): answer = models.CharField(max_length=500, null=False) question_answered = models.ForeignKey( Question, null=False, on_delete=models.PROTECT, related_name="question_answered" ) answering_user = models.ForeignKey( User, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="answerer" ) status = models.BooleanField(null=False) answer_ts = models.DateTimeField(auto_now_add=True, null=False) class Meta: verbose_name = "Answer" def __str__(self) -> str: return f"{self.answer} -- {self.answering_user}" This is the urls.py file: from django.urls import path from commons.views import (AnswerView) app_name = "commons" urlpatterns = [ path("play/", AnswerView.as_view(), name="play"), ] What I'm trying to do is whenever a user has logged in a wants to answer a set of questions by going to /commons/play/, on the GET request I want to parse out all the previous questions that user has answered and always display new questions. … -
Convert a query to geojson
I need help with this error that I am being presented with and it is the following. I have a database that when I perform the query has a list of points throughout the city, these points are in latitude and longitude format separately, now I need to pass them to geodjango and I need to serialize the data to convert it into geojson but I can't find the way to find the solution, I have the data like this from the database: {'type': 'Feature', 'properties': {'name': 'Centro Puerto Lopez', 'direction': 'Calle 5 # 7-28', 'latitude': '4.08467', 'longitude': '-72.9558', 'city': 'Puerto Lopez', 'department': 'Meta', 'pk': '97'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Bachue Acacias', 'direction': 'Carrera 35 # 14-23', 'latitude': '3.98454', 'longitude': '-73.777', 'city': 'Acacias', 'department': 'Meta', 'pk': '98'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Ciudad Porfia', 'direction': 'Carrera 43 # 67-04 Sur', 'latitude': '4.07094', 'longitude': '-73.6695', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '99'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Ciudad Milenio', 'direction': 'Calle 53 S # 33 - 02', 'latitude': '4.08341', 'longitude': '-73.6645', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '100'}, 'geometry': None}]} The data is displayed, I am trying to serialize it like this: from django.http import JsonResponse from django.contrib.auth.decorators import … -
Django tutorial problem: The current path, polls/, didn’t match any of these
I'm just getting started with Django, and I'm a touch rusty with web development, so this may be an easy one. I'm stepping through the Django Polls Tutorial from the official documentation and I encounter a problem nearly right away. I'm not having success accessing http://localhost:8000/polls/ . I receive the error... Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn’t match any of these. Here is my relevant code... \mysite\polls\views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") \mysite\polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] \mysite\urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] \mysite\mysite\setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'mysite.urls' Development server reads... Not Found: /polls/ [06/Dec/2022 15:02:01] "GET /polls/ HTTP/1.1" 404 2095 I have tried a hodgepodge of fixes that I've seen from other similar tutorial fixes, but nothing has worked and I feel like I'm taking stabs in the dark at this point. -
Django UpdateView set read only field by user permission
I have seen some posts like Making form fields - read only or disabled in DJANGO updateView use custom form on an UpdateView to make some fields as read only fields. However, the form object is not accessible for request.user object. If I want to make some fields read-only only for some user group, is there way to do it under UpdateView? -
Method "POST" not allowed for an api endpoint
I save topic data in a specific method of my viewset. I get following error: {detail: "Method "POST" not allowed."} end here's my view definition: class TopicView(viewsets.ViewSet): def save(self, request, cluster_id): # saves specific data ...and my urlpatterns: urlpatterns = [ ... path('api/cluster/<int:cluster_id>/topic/save', TopicView.as_view({'post': 'save'}), name='save_topic'), ... ] I don't understand, it's defined as post. What am I missing? Thanks. -
Redirecting to next url with additional parameters using LoginView
I have a detail page /spaces/<int:pk>/ where an unauthenticated user can enter form data. Upon submitting the form, this data is appended to the url like: /spaces/<int:pk>/?product_id=1&start_date=2022-12-23&duration=1 The user is then prompted to login or register to continue. Upon clicking login, the detail page url is appended as a next parameter to the login url. /login/?next=/spaces/1/?product_id=14&start_date=2022-12-23&duration=1 However, after logging in and redirecting back to the detail page, the url looks like: /spaces/1/?product_id=14 This is because the url is split with & when parsed, so the start_date and duration are considered as separate parameters. The only solution i can think of is to override LoginView.get_redirect_url and append each parameter from self.request.GET separately, but I'm not sure that is the best approach here. My goal is to preserve the initial input data so that the user does not have to input it again after logging in and landing back on the space detail page. For conversion reasons, I do not want to force the user to login before entering the initial form data. -
How to restrict media files of django project via nginx without dedicated server
I am running a Django project in a docker container. Uwsgi is my chosen protocol. Nginx is acting as a reverse proxy. I am able to restrict django sites for users based user.is_authenticated(). I am not able to restrict media and static files for not authenticated users as they get served directly from the filesystem. I do not have a second, dedicated server which only purpose is to identify and authenticate users. As I already have the functionality within my django project, I want to use this. My nginx configuration: events{} daemon off; http { access_log /dev/stdout; error_log /var/log/nginx/error.log; upstream django { server unix:///tmp/nginx/diplab.sock; } server { listen 8080; location = /accounts/check-authenticated { internal; uwsgi_pass django; proxy_pass_request_body off; proxy_set_header Content-Length ""; } location /static { alias /vol/web/static; include /etc/nginx/mime.types; } location /media { alias /vol/web/media; include /etc/nginx/mime.types; auth_request /accounts/check-authenticated; auth_request_set $auth_status $upstream_status; } location / { uwsgi_pass django; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; include /etc/nginx/uwsgi_params; } } } My Django Setup of the view which has the purpose to authenticate a user (200) or not (401). # urls.py app_name = 'accounts' urlpatterns = [ path('check-authenticated/', views.is_authenticated_view, name="check-authenticated"), path('login/', views.UserLoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), … -
unable to deploy django project on railway
keep receiving 'stream did not contain valid UTF-8' at the building stage tried using the pipreq command to generate requirements.txt in place of pip freeze>, yet it made no difference -
Add subquery on annotate with the model field value from the same model in Django
I have a model as follows: class Job(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=255) parent_job = models.UUIDField(default=uuid.uuid4) Now I need to get the name of the parent model in an annotate. I have tried the following but to no success: ( Job.objects.filter() .annotate( par_job_name=Subquery( Job.objects.filter(id=OuterRef("parent_job")).first().name ) ) .values("id", "par_job_name") ) ( Job.objects.filter() .annotate( par_job_name=Subquery( Job.objects.filter(id=F("parent_job")).first().name ) ) .values("id", "par_job_name") ) How can I get the par_job_name here? Note: I know that using a foreignkey to self might be a good way to model here but this is existing code and I have to work with this for now. So I have to implement the solution in th -
Can I remove existing fields or add some more fields in the default User DB in Django?, Also can i login using email instead of username?
I want to create a databasee for my project using default django database 'user' and i found that django have primary key username and some fields are not required, if i can add more fields to existing DB 'user' that would be great... i want to login using email instead of username and want to change some fields into required. Also can i add a field 'address'and 'mobile' ? Iam using Django 3.5.2 I have tried adding new fields using the following but still couldnt find a way to change primary key and required fields forms.py -> class CustomerUserForm(forms.ModelForm): class Meta: model=User #django default model fields=['first_name','last_name','password','email','username'] widgets = { 'password': forms.PasswordInput() } class CustomerForm(forms.ModelForm): class Meta: model= models.CRegistration fields=['address','mobile','profile_pic'] models.py -> class CRegistration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) profile_pic = models.ImageField(upload_to='profile_pic/CustomerProfilePic/', null=True, blank=True) address = models.CharField(max_length=100) mobile = models.CharField(max_length=20) #null=True status = models.BooleanField(default=False) -
showcasing Data to Chartjs using django
I'm trying to display data of patient count per month in bar chart with chartjs The data is being sent from the backend alright, but the issue Is that I don't know how to spread them in the chart with X axis being 12 months of the current year. this is the code: views.py class DataChart(APIView): def get(self, request, format=None): now = datetime.datetime.now() year = now.year month = now.month label = [datetime.datetime.today() + datetime.timedelta(days=i) for i in range(1, 10)] patien = Patient.objects.filter(date_joined__year__gte=year, date_joined__month__gte=month, date_joined__year__lte=year, date_joined__month__lte=month ).count() default_items = [patien] data = { "labels":label , "default":default_items } return Response(data) chartjs script $(document).ready(function() { var endpoint = '/api/chart/' var defaultData = [] var monthls = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setData() }, error: function(err_data){ console.log("error") console.log(err_data) } }) function setData(){ const ctx = document.getElementById('myChart'); new Chart(ctx, { type: 'bar', data: { labels:labels, datasets: [{ label: 'Patients', data:defaultData , borderWidth: 1 }] }, options: { scales: { x: { type: 'time', time: { unit: 'day' } }, y: { beginAtZero: true } } } }); } }); The labels that being sent from the views is just showing dates in a day format, and … -
Djnago relations nesting "related_name"
I'm trying to create single loop that will iterate through all sizes for each product from category. My models: class Category(models.Model): ... class Product(models.Model): category = models.ForeignKey(Category, db_column="id", on_delete=models.CASCADE, related_name="products") ... class Size(models.Model): product = models.ForeignKey(Product, db_column="id", on_delete=models.CASCADE, related_name="sizes") ... And my code in service def adjust_sizes(self, category: Category) -> None: for size in category.products.sizes.all(): # rest of my function But when I was trying to run this function I got error: *** AttributeError: 'RelatedManager' object has no attribute 'sizes' I wanted this to run in single loop, can someone help me how to do that? -
AttributeError: type object 'AdminSignUpForm' has no attribute 'as_view' why is this not working?
Creating a simple multiple users app. The as_view method is working with all the other views but not on this particular one. I have no clue why. Here are my models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Admin(models.Model): admin = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() def __str__(self): return f'{self.user.username} Admin' class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') def get_unanswered_questions(self, quiz): answered_questions = self.quiz_answers \ .filter(answer__question__quiz=quiz) \ .values_list('answer__question__pk', flat=True) questions = quiz.questions.exclude(pk__in=answered_questions).order_by('text') return questions def __str__(self): return self.user.username Here are my forms.py class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('students:quiz_list') class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'admin' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('home') Here is the traceback Traceback (most recent call last): File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\management\base.py", line 487, in check … -
Export to excel in django not working quite as i hoped it would
I am a django beginner, Trying to export an excel writer to excel in a django front end app using the results of function1 in function2 which contains the code to export/download the file but i can't seem to get it to work. It works when i include the export to excel code in function1 in my views.py (its a project with quite some sensitive data hence why i wont be sharing the actual code here). Each function has a button that run it to provide the required output but This doesnt work, i appreciate any help on this def function1(request): #post method request with filters from the frontend #use filters to read in the data df = read_sql("query with filters") #created a writer output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') #called functions that send output to writer sheets, see example below check_for_duplicates(df,writer) #create context to render some sample output on the frontend return render(request, 'home.html', context) def function2(request): function1(request) # gets me the results i want to export to excel writer.save() output.seek(0) response = StreamingHttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=customers_{lebook}.xlsx' return response I tried to put the code that appears in function2 in function1 and it worked but in … -
Websocket does not receive a message from django channels server even though they are connected
I am currently building an application with django channels. I have a websocket connected to a server. Looking at my terminal, it seems like the websocket is successfully connected to the server. HTTP GET / 200 [0.01, 127.0.0.1:62087] HTTP GET /static/video/js/websocket.js 200 [0.00, 127.0.0.1:62087] WebSocket HANDSHAKING /ws/video [127.0.0.1:62089] WebSocket CONNECT /ws/video [127.0.0.1:62089] However, the websocket does not receive the message sent from the server. Here are my codes: consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class VideoConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'you are connected!'})) websocket.js const address = 'ws://' + window.location.host + '/ws/video' const websocket = new WebSocket(address) const btn = document.getElementById('myButton') websocket.onopen = (event) => { console.log('websocket connected!!!') } websocket.onmessage = (event) => { console.log(event.data) } I would like to receive the message "you are connected!" on my browser's console. I looked into the official django channels document and google searched for a solution but I failed to solve my issue. What am I missing here? -
Include and Static statements are not being recognized with GitPages
I am new to GitPages and have successfully built and ran my page. However, the {% include %} and {% static %} methods in my index.html aren't being registered. As you can see here. Additionally, my two static files referenced in this file (circleselfie.png and home.css) have weird characters in their static paths when inspecting the page. Here is my project: https://github.com/jishli113/JSite/tree/master. What is causing this? -
nginx: Django X-frame options "DENY"
I am working with Django, Nginx, Gunicorn creating a printing file. For printing I am using templated docs. I have successful test cases for everything except loading a signature using jsignature. Loading the jsignature can be done many ways, however each time I add a {% load 'tag' %} in my document, nginx returns a X-Frame Options DENY/ 404. Removing the tag causes everything to work as normal. Nginx config: server { listen 80; server_name 3.142.15.65; index index.html index.htm; root /home/ubuntu/chippedoutauto; #path_to_your_directory # Forbidden files or directories location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md) { return 404; } # Directory verification related settings for one-click application for SSL certificate location ~ \.well-known{ allow all; } location /static/ { autoindex on; alias /home/ubuntu/chippedoutauto/chippedOutERP/static/ ; } location /static/js/ { alias /home/ubuntu/chippedoutauto/chippedOutERP/static/js/; } location /templatetag/jsignature/{ alias /home/ubuntu/venv/lib/python3.8/site-packages/jsignature/templatetags/; } location /static/admin/ { alias /home/ubuntu/chippedoutauto/chippedOutERP/static/admin/; } location /static/bootstrap_datepicker_plus/{ alias /home/ubuntu/chippedoutauto/chippedOutERP/static/bootstrap_datepicker_plus/; } location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; #Persistent connection related configuration add_header X-Cache $upstream_cache_status; #Set Nginx Cache add_header Cache-Control no-cache; expires 12h; } access_log /home/ubuntu/chippedoutauto/bin/logs/chippedOutEPR.log; error_log /home/ubuntu/chippedoutauto/bin/logs/chippedOutERP.error.log; } I have attempted to use both the built in image tag from templated docs while using "draw_signature" from jsignature, as …