Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I created a form to let me edit my user and email(using Python, Django, and Vue.js). When I press submit changes, nothing happens
So I am working on this time tracking app for myself, to learn Django and Vue.js, I found a tutorial from Code with Stein. I got stuck at editing the profile part from the tutorial. I get no errors, yet there are no changes made to my username or email(the changes don't even apply to my admin dashboard or database). The thing is that I get no error, which leaves me completely in the dust. Here is the code in edit_profile.html: {% extends 'core/base.html' %} {% block title %}Edit Profile | {% endblock %} {% block content %} <nav class="breadcrumb" aria-label="breadcrumbs"> <ul> <li><a href="#">Dashboard</a></li> <li><a href="{% url 'myaccount' %}">My Account</a></li> <li class="is-active"><a href="{% url 'edit_profile' %}" aria-current="page"></a>Edit Profile</li> </ul> </nav> <div class="columns"> <div class="column is-4"> <h1 class="title">Edit Profile</h1> <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="field"> <label>Username</label> <div class="control"> <input type="text" name="username" id="username" class="input"{% if request.user.username %} value="{{ request.user.username }}" {% endif %}> </div> </div> <div class="field"> <label>Email</label> <div class="control"> <input type="text" name="email" id="email" class="input"{% if request.user.email %} value="{{ request.user.email }}" {% endif %}> </div> </div> <div class="field"> <label>Password(You can change it if you want it.)</label> <div class="control"> <input type="password" name="password" id="password" class="input"{% if request.user.password %} value="{{ request.user.password }}" … -
How to integrate Django oAuth in flutter App
We are currently working on an app that uses Django auth-users and oauth2 as authorization. Now I was looking at the documentation and examples of the flutter-package oauth2, and the tutorial looks quite easy. But it doesn't really work. Does anybody already have a simple solution for oauth2 with django that he could share, or maybe a link to a github project that could help me? -
Django server side cursor is not working in test
with psycopg2.connect(conn_url) as conn: with conn.cursor(name=f"{uuid4()}") as cursor: cursor.itersize = batch_size cursor.execute(raw_sql, params) this is returning empty row in django test. But running correctly in shell_plus. Also I have set @override_settings(DISABLE_SERVER_SIDE_CURSORS=False) . But still getting the same result -
ClientError at /securelogin/products/product/add/ An error occurred (InvalidArgument) when calling the PutObject operation: None
I am trying to add products in django admin.why this error showing. i am uploading in aws s3 bucket.Is there any problem in boto3 or storages Is there anyone for solution.is there anyone who have ever faced this issue.Kindly Responde -
My Django form won't save now that I have styled it using Tailwindcss?
Since I have started using Tailwind CSS to style my form, it won't save. I was previously passing the form like this {{ form.as_p }} but wanted to style it. Now that I have styled the form, it does not correctly submit the data. I have been stuck on this for ages, and any help would be greatly appreciated. Here is all the relevant code. html template: {% load static %} <head> <link href="{% static 'src/output.css' %}" rel="stylesheet" /> <title>Surfer Creation Form</title> </head> <body class="bg-gradient-to-tr from-pink-500 via-purple-500 to-blue-500"> {% include 'include/messages.html' %} <form method="post" action="{% url 'roxy:UserCreate_Surfer' %}"> {% csrf_token %} <!-- User Creation Form --> <div class="flex justify-center items-center"> <div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 my-2"> <h2 class="mb-4">Start your surfing journey now!</h2> <!--Name fields --> <div class="-mx-3 md:flex mb-6"> <div class="md:w-1/2 px-3 mb-6 md:mb-0"> <label for="{{ user_form.first_name.id_for_label }}" class="block text-sm font-normal mb-2" >{{ user_form.first_name.label }}: </label> <input type="text" name="{{ user_form.first_name.html_name }}" id="{{ user_form.first_name.auto_id }}" class="border border-gray-300 rounded px-4 py-2 mb-4 input-field" required /> </div> <!-- Last name field --> <div class="md:w-1/2 px-3 mb-6 md:mb-0"> <label for="{{ user_form.last_name.id_for_label }}" class="block text-sm font-normal mb-2" >{{ user_form.last_name.label }}: </label> <input type="text" name="{{ user_form.last_name.html_name }}" id="{{ user_form.last_name.auto_id }}" class="border border-gray-300 rounded … -
Error while deploying my Django App in Vercel
So My Django app runs perfectly fine on the local server, i've been trying to upload it on vercel but it keeps giving me this error. ***Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-xx4e_y5y/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in setup.cfg*** I've tried locating the setup.cfg file, but i couldn't find any. This is my first deployment, and i don't know how to deploy it yet properly. Any help regarding what the error is and how to solve it, is greatly appreciated. Thanks -
Redirect database call to different db url based on type of query(Read, write, update) with Django
In an existing project how can i implement a method using which i can redirect it different database(Write, Update & read) without modifying existing django queries. If i have 2 queries: MyModel.objects.get(name = "abc") And MyModel.objects.create(name = "xyz") With database config as: DATABASES = { 'read_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'read_db', 'USER': 'read_db', 'PASSWORD': 'read_db', 'HOST': '', 'PORT': '', }, 'write_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'write_db', 'USER': 'write_db', 'PASSWORD': 'write_db', 'HOST': '', 'PORT': '', }, 'update_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'update_db', 'USER': 'update_db', 'PASSWORD': 'update_db', 'HOST': '', 'PORT': '', } } Want read_db to be called for query 1 & write_db for query 2 -
ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'
I want to get listings under a particular category. But when I select the category, I get this error: ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'. VIEWS.PY def index(request): listings = Listing.objects.filter(is_active=True) product_ca = Category.objects.all() return render(request, "auctions/index.html", { "data": listings, "categ": product_ca }) def categories_view(request): if request.method == "POST": c = request.POST["categorys"] cg = Listing.objects.filter(category=c) cg.category_id return render(request, "auctions/Categories_view.html", { "category": cg, }) MODELS.PY class Category(models.Model): type = models.CharField(max_length=100, null=True) def __str__(self): return self.type class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) price_bid = models.DecimalField(decimal_places=2, max_digits=6, default=False) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") Seems I'll have id get the id of c = request.POST["categorys"] in Listing but I don't really know how to go about it. Or maybe am still wrong. -
Jinja does not update properly
I have this code in python: @overviewBlueprint.route('/dashboard/words-cloud', methods=['GET', 'POST']) @login_required def textCloud(): filterParams = buildFilterParams() productScopeStr = request.args.get('product') if request.args.get('product') else 'myproducts' multiWord = request.args.get('multiword') reviewsQuerySet = filterQuerySet(customer_id=session["customer_id"]) wordsType = 'trending' if request.method == 'POST': wordsType = request.form['words-type'] if wordsType and wordsType == 'topics': popularWords = [] topics = topic.getSavedTopicsByQuerySet(reviewsQuerySet) topics = sorted(topics, key=lambda item: item['count'], reverse=True) for element in topics: item = { 'topic': element['topic'], 'driver': { 'totals': { 'reviewCount': element['count'] } } } popularWords.append(item) return render_template("text-cloud.html", filterParams=filterParams, wordsType=wordsType, currentProduct=productScopeStr, multiWord=multiWord, topics=topics, popularwords=popularWords) elif wordsType == 'trending': popularWords = topic.popularTopics(reviewsQuerySet=reviewsQuerySet) return render_template("text-cloud.html", filterParams=filterParams, wordsType=wordsType, currentProduct=productScopeStr, multiWord=multiWord, topics=[], popularwords=popularWords) In the jinja template, I have a select box that has 2 options: trending and topics. I added an onChange event for select elements which makes a post request with the updated value. But every time I change the select value it displays only the first table. As you can see in my template I have two tables : <i class="fa fa-info-circle" aria-hidden="true"></i> Talk About shows how many reviews talk about this subject {% if wordsType == 'trending' %} <table id="popular-words" class="table table-bordered tablesorter"> <thead> <tr> <th>Topic</th> <th>Talk About</th> <th>Sentiment</th> </tr> </thead> <tbody> {% for item in popularwords %} <tr> <td> … -
I have hosted a django application render on free server. It is working fine local machine but not working in render ,i have pushed all the code
I have fetched NSE data from nse api and displayed using chart js in django templates , everything fine in local machine , once i pushed the all code in render server it is showing like this . This page isn’t workingsuperlogo-final.onrender.com is currently unable to handle this request. HTTP ERROR 502. I have uploaded the images please check and help me figure out the problem -
How to send selected option with Django and Ajax?
i have a problem about send or save my selected option to database. I have tried all the ways I know to run this program, but always the selected option is not saved. I have removed the line of code I was trying to solve this problem so that you guys can come up with a solution in your own way. if you guys need more detailed code just let me know. hope you can understand what I'm saying my models.py: class Category(models.Model): category = models.CharField(max_length=200) slug = models.SlugField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(Category,blank=True) thumbnail = models.ImageField(upload_to='thumbnails') slug = models.SlugField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) my forms.py: class GalleryForm(forms.ModelForm): category = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.SelectMultiple, required=False ) class Meta: model = Gallery fields = ['title', 'description', 'category','thumbnail'] my views.py: def gallery_list_and_create(request): form = GalleryForm(request.POST or None, request.FILES or None) if(request.user.is_authenticated): user = User.objects.get(username=request.user.username) gallery_user = user.gallery_set.all() if(is_ajax(request=request)): if(form.is_valid()): instance = form.save(commit=False) instance.author = user instance.save() return JsonResponse({ 'id': instance.id, 'title': instance.title, 'description': instance.description, # 'category': [category.category for category in instance.category.all()], 'thumbnail': instance.thumbnail.url, 'slug': instance.slug, 'author': instance.author.username, 'since': … -
how can i bookmark songs in my django project
I've been trying to put the favorites feature for days with django rest framework and javascript api fetch in my lyrics project but without success all the methods I'm trying don't work please help me I'm a beginner in javascript, even in api with django too. here is what I tried, where did I mow apiviews.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,permissions from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework import generics from rest_framework.response import Response from rest_framework import viewsets, status from rest_framework.decorators import action from .serializers import SongSerializer from .models import Song, User from .models import Song, Favorite class FavoritesongView(APIView): serializer_class = SongSerializer queryset = Song.objects.all() @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def favorite(self, request, id): song = self.get_object() user = request.user if user not in song.favorited_by.all(): song.favorited_by.add(user) song.save() return Response({'status': 'favorited'}) @favorite.mapping.delete def unfavorite(self, request, id=None): song = self.get_object() user = request.user if user in song.favorited_by.all(): song.favorited_by.remove(user) song.save() return Response({'status': 'unfavorited'}) apiurls from django.contrib import admin from django.urls import path from favorites.apiViews import FavoritesongView urlpatterns = [ path('songs/<int:id>/favorite/', FavoritesongView.as_view()) ] js file function addToFavorites(songId) { fetch(`/api/songs/${songId}/favorite/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) .then(response … -
CSRF Failed: CSRF token missing. in Django Rest
I am really confused because I can't avoid this error. My previous projects were not engaged with this error. So anyways I hope you can find solution. here is my settings.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "accounts", "contents", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication" ] } WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } 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', }, ] LANGUAGE_CODE = 'en-us' STATIC_ROOT = os.path.join("static") TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' and here is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path("contents/", include("contents.urls")), ] here is accounts.views: from rest_framework.response import Response from rest_framework.generics import CreateAPIView from rest_framework … -
How to configuring Apache as a Reverse Proxy for a Django App in a Docker Container: Serving Static Files
I have Django app that runs in docker container. I have a problem with serving static files with my Apache configuration. My django app works inside docker container and Apache correctly routes requests to it I made sure to set STATIC_URL = "/static/" and DEBUG = False settings properties I made sure to collect static to /var/www/my_app/static/ directory I made sure that directory /var/www/my_app has correct acccess rights for apache: drwxr-xr-x 3 www-data www-data 4,0K June 11 16:25 my_app This is my apache config: <VirtualHost 000.00.0.000:443> ServerName my_app.com SSLEngine on SSLProxyEngine on SSLCertificateFile /etc/apache2/certs/cert.pem SSLCertificateKeyFile /etc/apache2/certs/cert.key SSLCACertificateFile /etc/apache2/certs/DigiCertCA.crt CustomLog /var/log/apache2/my_app.log combined ErrorLog /var/log/apache2/my_app.log ProxyPass /static ! Alias /static/ /var/www/my_app/static/ <Directory /var/www/my_app/static/> Require all granted </Directory> <Location /> ProxyPass http://localhost:6000/ ProxyPassReverse http://localhost:6000/ ProxyPreserveHost on </Location> </VirtualHost> Could you help me please to resolve the issue? -
how to create a django form with names from the database
I have a sidebar with a drop-down menu that has categories and dishes. I want to create a checkbox for selection dishes models.py class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Dish(models.Model): category = models.ForeignKey(to=Category, related_name="children", on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=500) weight = models.IntegerField() cost = models.IntegerField() def __str__(self): return self.name in html format it looks like this: <div class="filter-content collapse show" id="collapse_1" style=""> <ul class="list-unstyled ps-0"> {% if category %} {% for cat in category %} <li class="mb-1"> <button class="btn btn-toggle d-inline-flex align-items-center rounded border-0 collapsed" data-bs-toggle="collapse" data-bs-target="#{{ cat.id }}" aria-expanded="false"> {{ cat.name }} </button> {% for dish in cat.children.all %} <div class="collapse" id="{{ cat.id }}" style=""> <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small"> <li> <div class="list-group list-group-checkable d-grid gap-2 border-0"> <input class="list-group-item-check pe-none" type="checkbox" name="listGroupCheckableRadios" id="{{dish.name}}" value=""> <label class="list-group-item rounded-3 py-3" for="{{dish.name}}"> {{dish.name}} </label> </div> </li> </ul> </div> {% endfor %} </li> {% endfor %} {% else %} <p>no values</p> {% endif %} </ul> </div> to handle clicking on the checkbox, I create a form: class DishForm(ModelForm): class Meta: model = Basket fields = ['dish'] widgets = {"dish": CheckboxInput(attrs={ 'class': 'list-group-item-check pe-none', 'type': 'checkbox', }) } and added this form to html <div class="filter-content collapse show" id="collapse_1" … -
How to host 2 server in one Azure App Service?
I'm having a web app which is based on ReactJS (Frontend) + Django (Backend), I've integrated ReactJS with Django and make it as single server based application. I have 1 more server which is based on Express JS separately. I'm trying to host my web application in Azure app service and publisher is Docker Container. So, I am hosting React + Django based web app in 1 app services it is successfully getting hosted along with the SSL certificates. Now, I am trying to host Express JS in same web app in which I hosted React + Django based web app since Django + React is running on port 80 . I am not able to host Express JS in same app service and if I am trying to host Express JS on separate app service, it is getting hosted but now domain is changed or there need to be some subdomain which I don't want. PROBLEM: I want to host both Django+React server and Express JS server in same app service in which my main web-app is hosted. Any help or any leads are highly appreciated -
While activating the user in django using the token and uid, there getting the following error, why? [closed]
File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'str' object has no attribute 'get' [12/Jun/2023 06:25:59] "GET /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ HTTP/1.1" 500 66953 and this is my page AttributeError at /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:7000/active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: /home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py, line 27, in process_response Raised during: user.views.active Python Executable: /home/cybermate/Desktop/NewProject/env/bin/python3 Python Version: 3.10.6 Python Path: ['/home/cybermate/Desktop/NewProject/eshopy', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages'] Server time: Mon, 12 Jun 2023 06:25:59 +0000 i tried a lot can you mension what should and why this happening. could you explain? -
How to view the progress of the django app in the browser
I want the process of the app to be dispayed in the browser so that suers know how much it has been done. However, in django, the view receives the event that occurred in the template(browser) and passes it back to the template, so I don't know how to pass it from the view itself to the template. For example, when the user clicks a button, a total of 3 fuctions are executed in trun. At this time, I want to show 'End of function1, start of function 2' when fuction 1 ends. it same way for fuction2,3. I'm not sure if I should do this in view or make it in JS. The functions runs in python. I'm not familiar with django, so this might be a very rudimentary question. Please Help me :) The fuctions are performed in the view in order, and when each function is completed, render or redirect is perfomed to template. but it is expressed only at the first fuction and does not proceed any further. -
Find out which field a file is being uploaded to
def _image_directory_path(instance, filename): pass class TreatyParagraph(CommentMixin, models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) english = models.TextField(blank=False, null=False, default="") english_img = models.ImageField(blank=True, null=False, default="", upload_to=_image_directory_path) spanish = models.TextField(blank=True, null=False, default="") spanish_img = models.ImageField(blank=True, null=False, default="", upload_to=_image_directory_path) I want to organize file storage like this: 253e8498-7859-4490-b8ff-644f928607e5 en.png sp.png Depending on the field I'd like to rename the file (english_img corresponds to en.png etc.). The problem is that I have failed to find out which field a file belongs to. If only I could determine which field a file is being uploaded to, I'd just sliced the first two letters. Could you help me? -
Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused
celery -A video_subtitle worker --loglevel=info ` -------------- celery@user-Inspiron-15-3520 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.19.0-43-generic-x86_64-with-glibc2.35 2023-06-12 05:44:21 *** --- * --- ** ---------- [config] ** ---------- .> app: video_subtitle:0x7fbb41f5dde0 ** ---------- .> transport: redis://localhost:6379// ** ---------- .> results: *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery ` [tasks] . video.tasks.process_video . video_subtitle.celery.debug_task [2023-06-12 05:44:21,877: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) [2023-06-12 05:44:23,883: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 4.00 seconds... (2/100) [2023-06-12 05:44:27,889: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 6.00 seconds... (3/100) [2023-06-12 05:44:33,898: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 8.00 seconds... (4/100) [2023-06-12 05:44:41,909: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 10.00 seconds... (5/100) [2023-06-12 05:44:51,924: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again … -
All static assets not loading - Django, Gunicorn, NGINX
I am running Ubuntu 22.04, gunicorn, django, and nginx. Everytime I load the main page: http://dev.api.afisado.com, none of the CSS is loaded and the js is executed. From the developer tab in chrome I see a 404 not found. I'm not sure what to do. Folder Structure is like this: `/home/devbackend_directory/core/static/ Inside static I have assets. Inside assets I have css, js, and img files. Here is what my settings.py looks like: STATIC_URL = '/static/' STATIC_ROOT = '/home/devbackend_directory/core/static/' MEDIA_ROOT = '/home/devbackend_directory' MEDIA_URL = '/media/' server listen 80; server_name dev.api.afisado.com; location = /favicon.ico { access_log off; log_not_found off;} location static/ { root /home/devbackend_directory/core/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } and here is my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ali Group=www-data WorkingDirectory=/home/devbackend_directory/core/ ExecStart=/usr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ core.wsgi:application [Install] WantedBy=multi-user.target ` -
Im not able to get post values through my django view
I'm new to django and I made a custom view for logging in, but no matter my post request, The function never gets username nor password. Here is my view: @csrf_exempt def custom_login(request): if request.method == 'POST': username = request.POST.get("usuario") password = request.POST.get("clave") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return JsonResponse({'success': True}) else: return JsonResponse({'success': False, 'message': 'Invalid credentials', 'username': username, 'password': password}) Also here is my url patterns in urls.py urlpatterns = [ # asocia la raiz del proyecto con el index.html path("", views.index, name="index"), # asocia las rutas creadas previamente por el enroutador Router path('', include(router.urls)), # incluye rutas de autenticacion de usuario de Django path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('admin/', admin.site.urls), path('custom-login/', custom_login, name='custom_login'), ] I've tried using postman for making the request, I expect a successful login but always get unsuccesful. When I debug username and passwords values in python i always get None. If i change it manually to a real user string it logs in successfully -
Issue with exited containers named "django-run-{uuid}" when switching interpreters in PyCharm
I have connected PyCharm with a docker-compose container for debugging multiple services. However, changing the interpreter creates exited containers named "django-run-{uuid}". I have investigated and it doesn't seem to be a persistent issue with PyCharm. There are no syntax problems in the Dockerfile or docker-compose configuration files either. I'm curious to know if this is a natural occurrence during the interpreter refresh process in PyCharm or if it is an artificially induced problem. If it is artificially induced, I would like to know where to look for the source of the issue. -
Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'
I've been trying to merge Vue and Django for a long time, but my efforts are even. Here is the error that I can't solve for a long time: ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } Do you have any options for solving this problem? Maybe there is another way to combine them. Vue.config.js var BundleTracker = require('webpack-bundle-tracker') var WriteFilePlugin = require('write-file-webpack-plugin') module.exports = { outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'), publicPath: '/', devServer: { publicPath: "http://localhost:8080/", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method", "Access-Control-Allow-Credentials": "true" } }, chainWebpack: config => { config.optimization.splitChunks({ cacheGroups: { vendors: { name: 'chunk-vendors', test: /[\\\/]node_modules[\\\\/]/, priority: -10, chunks: 'initial' }, common: { name: 'chunk-common', minChunks: 2, priority: -20, chunks: 'initial', reuseExistingChunk: true } } }) }, configureWebpack: { output: { filename: 'js/[name].js', chunkFilename: 'js/[name].js' }, plugins: … -
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) while sending notification using firebase in django
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) code `def send_notification(registration_ids , message_title , message_desc): fcm_api = "" url = "https://fcm.googleapis.com/fcm/send" headers = { "Content-Type":"application/json", "Authorization": 'key='+fcm_api } payload = { "registration_ids" :['e1aLmMZPeegz36PP3KUw0t:APA91bGjoJBwraENbW9PHsE5IUVIh_lLhnPI99qqr_VewvRFLjbJbu_vcSfT0dk4Tu4CGbcvUfR-x8INAkqovEDuJB4OdQma2NrEPsGufjtrsizYskD_ANCpKjT5wltIAfzJkbjY0YAV'], "priority" : "high", "notification" : { "body" : "message desc", "title" : "message_title", "image" : "https://i.ytimg.com/vi/m5WUPHRgdOA/hqdefault.jpg?sqp=-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLDwz-yjKEdwxvKjwMANGk5BedCOXQ", "icon": "https://yt3.ggpht.com/ytc/AKedOLSMvoy4DeAVkMSAuiuaBdIGKC7a5Ib75bKzKO3jHg=s900-c-k-c0x00ffffff-no-rj", } } result = requests.post(url, data=json.dumps(payload), headers=headers ) print(result.json())` not able to send notifications to my user