Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File import issue - python Django
I have a file in my management/commands folder and I am trying to import my models into the report.py folder. However, I get the following error. Traceback (most recent call last): File "c:\Users\Timmeh\source\Python\Django Projects\env\topxgym\members\management\commands\report.py", line 2, in <module> from members.models import ActiveMember ModuleNotFoundError: No module named 'members' I have a active.py file in that same folder with the same import and it works. However, the active.py is run from python manage.py active. The report.py I am just compiling/running it (not running it from python manage.py). That is the only difference. the file structure. -
How do I print the query that Python uses to call the database?
How do I print to the terminal the query used by a specific line of python code? see below notifications = user.get_notifications(max_id=max_id, types=types).order_by('-created')[:count] -
Nginx can't find bundles js file
I am trying this for a long time. I would really appreciate the help. In local, application is working, but in nginx, main.js resource is not found I have a django application with react on the save server served with webpacker and babel URL / will render frontend/index.html Index.html code: Nginx.conf file Settings.py In local, its working But in nginx server, its not project structure -
Errow while working with django, psycopg file shifting to mac (I WOULD ANSWER MYSELF, IT MAY HELP SOMEONE) [duplicate]
I recently shifted to MAC M2 MONTEREY & one project involved django & my dev env from older system isn't setup here. I got error while installing "psycopg" like this: Using cached psycopg2-2.8.5.tar.gz (380 kB) ERROR: Command errored out with exit status 1: command: /opt/homebrew/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"'; __file__='"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r cwd: /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/ Complete output (23 lines): running egg_info creating /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info writing /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ============================================================================== Its beginning of the error, After that its tried to install each previous version of Psycopg ============================================================================== Searching out for solution, a few things helped me out so here's the answer from my side thinking it may help someone else … -
Apache + Python (Django): Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
I'm trying to host my Django Rest Framework project using Xampp & Apache on my Windows server but I'm getting the following error. Does anyone have an idea what causes it? I installed Python, mod_wsgi and all the requirements for my app. Full stacktrace below Current thread 0x00000e94 (most recent call first): <no Python frame> [Sat Aug 27 11:05:43.581446 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00428: Parent: child process 5104 exited with status 1 -- Restarting. [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00455: Apache/2.4.53 (Win64) PHP/8.1.6 mod_wsgi/4.9.3 Python/3.10 configured -- resuming normal operations [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00456: Apache Lounge VS16 Server built: Mar 16 2022 11:26:15 [Sat Aug 27 11:05:43.741583 2022] [core:notice] [pid 2484:tid 332] AH00094: Command line: 'C:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Sat Aug 27 11:05:43.757121 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00418: Parent: Created child process 2976 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.path = [ 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', … -
Django replace text in template
In my project i can filter products with queryset. How can i change a h1 element to the filter name? I tried to change with javascript, but when i filtered the products the page reloaded and the text didn't change models.py TYPE = ( (0, "monitor"), (1, "pc"), (2, "phone"), ) class Product(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(upload_to='images/') description = models.TextField() price = models.CharField(max_length=12, unique=True) type = models.IntegerField(choices=TYPE, default=0) def __str__(self): return self.name views.py class ProductList(generic.ListView): template_name = 'products.html' def get_queryset(self): queryset = Product.objects.all() type_query = self.request.GET.get("type", None) if type_query == 'monitor': queryset = Product.objects.filter(type=0) elif type_query == 'pc': queryset = Product.objects.filter(type=1) elif type_query == 'phone': queryset = Product.objects.filter(type=2) elif type_query == 'all': queryset = Product.objects.all() return queryset products.html <form onsubmit="return setTypeText()" id="type-form"> <input type="radio" id="all-radio" name="type" value="all"> <input type="radio" id="monitor-radio" name="type" value="monitor"> <input type="radio" id="pc-radio" name="type" value="pc"> <input type="radio" id="phone-radio" name="type" value="phone"> <input type="submit" value="Filter"> </form> <h1 id="type-text">All product</h1> #<---I need to change this I need to change the h1 to the input value Javascript function setTypeText(){ var elements = document.getElementsByName('type'); var type_name; for(i = 0; i < elements.length; i++) { if(elements[i].checked) type_name = elements[i].value; } document.getElementById("type-text").innerHTML = type_name; return true; } When … -
Show only users that don't yet exist in the through table
Inside of the __init__ method of a form ProjectUserCreateForm(forms.ModelForm) to add Users to a Project (Project model has a users = models.ManyToManyField(...)) I have self.fields['users'].queryset = User.objects.filter(company=self.request.user.company) This way I'm able to show only the users to be added to the Project that belong to the company of the user requesting the page. This form can be found in path('<int:pk>/users/create/', views.ProjectUserCreateView.as_view(), name='project-user-create'), where the <int:pk> is the PK of the Project, and ProjectUserCreateView is a CBV CreateView. How can I show only the users that belong to the company of the logged in user (this part already works) AND that don't yet exist in the through table (the table based on the ManyToManyField)? -
Django messages not displaying message
I'm trying to use django messages to notify user if form was submitted successfully or not. But nothing pops up when I submit the form no matter what. I've gone through the views.py code and template and I don't seem to anything wrong. I've even tried changing the default messages backend storage to session yet nothing. MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' views.py: from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect from django.contrib import messages from .forms import MyUserCreationForm import bcrypt def register(request): if request.method == "POST": # Populate form using submitted data form = MyUserCreationForm(request.POST) if form.is_valid(): # Clone form model user = form.save(commit=False) password = user.password # Validate password length if len(password) > 25: messages.error( request, "PASSWORD MUST BE LESS THAN OR EQUAL TO 25 CHARACTER LENGTH") # Hash user password bytes = password.encode('utf-8') salt = bcrypt.gensalt() hash = bcrypt.hashpw(bytes, salt) # Save modified form to database user.password = hash user.save() messages.success(request, "ACCOUNT CREATED SUCCESSFULLY!") messages.add_message(request, messages.INFO, 'Thanks for reaching out! We will be in contact soon!', extra_tags='ex-tag') return redirect('register') # Create empty form form = MyUserCreationForm() return render(request, 'register.html', {'form': form}) templates/register.html: {% extends "layout.html" %} {% block title %} Testing Registration {% endblock %} {% load static %} {% load … -
How to connect two django projects on two different servers
Problem: I am having a website which has various apps (Accounts, Community, Company, Payments, Main_project_app). What I want is to set up a google type similar architecture where the userbase is on one server and other apps such as Gmail, drive, etc. serve the specific services on different servers based on the user authentication from the main Google userbase server i.e. Accounts app which have information about the user such as username, email, password, etc must remain on one server and using the REST API's or something we connect accounts app with another server to take the user from sign-in page to dashboard and serve them other services by using all other apps. I am a newbie so please if I have done some mistakes to explain or something do correct me. -
Django Template – Mark only certain HTML tags as safe
I have the following use case: a user should be able to enter in HTML input and it should be displayed as such. However, it can only contain <br>, <italic>, <strong>, <ul> or <li> tags. I know about the safe filter, but that way it would allow every HTML input and be prone to XSS. Any idea how I can solve this? Thanks! -
Social Authentication from drf_social_oauth2 : error with django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace
I'm developing an new application with an Angular and Django Rest Framework stack. In my API, I use drf_social_oauth2 for a Social Authentication. The token exchanges are successful. Tokens and users are created on the database. However, the authentication for others views are in failure. I use this type of authentication_classes in my others views : from rest_framework import authentication from drf_social_oauth2.authentication import SocialAuthentication class UsersListApiView(APIView): authentication_classes = [authentication.TokenAuthentication, SocialAuthentication] My URLs are : path('auth/login/', obtain_auth_token, name='login'), path('auth/', include('dj_rest_auth.urls')), path('auth/registration/', include('dj_rest_auth.registration.urls')), re_path(r'^auth/', include('drf_social_oauth2.urls', namespace='drf')), This is a part of my settings.py file : AUTHENTICATION_BACKENDS = [ # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # drf_social_oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # DJango 'django.contrib.auth.backends.ModelBackend', ] # Facebook configuration SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook. # Email is not sent by default, to get it, you must request the email permission. SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "" # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SITE_ID = 2 … -
How do I sync my ecommerce django website with my Facebook page to automatically display products
I have developed a ecommerce website using Django, I want to link it with my Facebook business page. I searched but couldn't find any good answer -
What is the correct field it should be applied
I cannot figure out what kind of field shoud I use in my serializer class if in the model it is a ForeignKey class DotPrivateSerializer(serializers.ModelSerializer): tag = serializers.________________Field( queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault()) ) models.py class DotPrivate(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) name = models.CharField(max_length=255) description = models.TextField(max_length=350, blank=True) lon = models.CharField(max_length=20) lat = models.CharField(max_length=20) rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(5.0)]) tag = models.ForeignKey('TagPrivate', on_delete=models.PROTECT) -
Can't install mysqlclient error metadata-generation-failed
I am trying to install mysqlclient, but it throws me an error, what should I do, please help. pip install mysqlclient Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
django-markdown: How to disable loading image when render article briefing
I am a beginer of web development and I have had some python exprience while this is my first try on django (Django==3.2) . I have managed to store markdown article by using Markdown==3.3.7, the everything looks like: # models.py class ArticlePost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=64) body = models.TextField() # views.py def article_create(request): if request.method == "POST": article_post_form = ArticlePostForm(data=request.POST) if article_post_form.is_valid(): new = article_post_form.save(commit=False) new.author = User.objects.get(id=1) new.body = markdown.markdown( new.body, extensions=[ 'markdown.extensions.extra', ]) new.save() return redirect("article:article_list") # else: # Shell test: >>> print(article.body) <p><a href="https://img.com/"><img alt="test.png" src="https://xxxx" /></a></p> >>> type(article.body) <class 'str'> at first it looks like: so I use CSS display:none, the img doesn't render just as expecting But I happened to find that display:none doesn't prevent browser to load image: a practical way is when calling article_create() "sed" out img tag and dump a copy which is only for the usage of rendering the brief but to me, I prefer some way that I can remain current article.body content, then add something in html or css, so that I can make the brief brief(cuz it render without loading img). thx in advance! -
How to set Django settings from within a function?
Is there a way to set django settings from within a function? Essentially, I want to create logic blocks that set various django settings (perhaps more than one at a time). An quick example of this: def set_log_settings(env): if env == 'prod': set_settings({'LOG_LEVEL': 'INFO', 'LOG__HANDLER': 'prodhandler'} else: set_settings({'LOG_LEVEL': 'DEBUG', 'LOG__HANDLER': 'devhandler'} I would call this instead of having in my settings.py: if env == 'prod': LOG_LEVEL='INFO' LOG__HANDLER='prodhandler' else: LOG_LEVEL='DEBUG' LOG__HANDLER'='devhandler' Note: I want to call this from within the settings.py file, not from the actual loaded app code, it's more a question of grouping settings-related logic, rather than a question of when that logic runs. This would allow me to not have a giant settings file where all logic is sitting virtually un-organized at the global level. -
POST request with ajax not working after installing django hosts
Hello I am just getting acquainted with django hosts which I am trying to set up on an ecommerce website I am building. So basically I will have the main website - www.shop.com And I want to have a subdomain - sell.shop.com - which will be where sellers can register and access their dashboard. Previously I set the seller website on www.shop.com/sell which is wrong in my opinion. When the seller would register, I was handling the form validation using AJAX. And everything was working properly. Once I installed django hosts and reconfigured the application, I noticed that the AJAX POST request is no longer getting detected. And so, no data is being stored in the DB nor is the validation on the form working. settings.py ALLOWED_HOSTS = ['127.0.0.1', 'www.shop.com', '.shop.com',] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third Party 'django_hosts', 'corsheaders', # Custom 'pages', 'users', 'vendors', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsResponseMiddleware' ] ROOT_URLCONF = 'sns.urls' ROOT_HOSTCONF = 'sns.hosts' DEFAULT_HOST= 'www' PARENT_HOST = 'surfnshop.mu' HOST_PORT = '8009' CORS_ALLOWED_ORIGINS = [ "http://surfnshop.mu:8009", "http://sell.surfnshop.mu:8009" ] CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', … -
Django admin command equivalent for gin golang
I want to write a script a to migrate data from one table to another using gin golang. The dataset is quite big so I can't create an API endpoint and do it as it will get timed out. I am looking an equivalent of django admin commands for golang that can help me to connect to the database easily and perform these task. -
How to convert a char field to uuid field in django models
I have a django model, where I am storing uuid kind of strings in a character field of max length 255, I want to convert this field to uuid field, how can this be done in django. -
Django URL error: noreversematch in my app
I'm seeing this error in my Django app NoReverseMatch at /kaitorihyou/delete_fields_group/18 Reverse for 'delete_fields_group' with arguments '('',)' not found. 1 pattern(s) tried: ['kaitorihyou/delete_fields_group/(?P<fields_group_id>[0-9]+)\\Z'] However my urls.py does contain this pattern like this: app_name = "kaitorihyou" urlpatterns = [ path('delete_fields_group/<int:fields_group_id>', views.delete_fields_group, name="delete_fields_group"), # etc. ] Why is the url pattern not matching? -
How to incorporate django-tailwind into django rendered forms for input fields?
I have the following form: <form class="form" method="post" action="."> {% csrf_token %} <div class="error-wrapper"> <div class="errors">{{ form.errors }}</div> </div> <div class="email-wrapper field-wrapper"> <div class="tag name-tag">{{ form.username.label }}*</div> <!-- How to apply tailwind css classes to the rendered input field here? --> <div class="input rounded-lg">{{ form.username }}</div> </div> ... </form> # forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') Now I want to apply tailwind classes to the input field which is rendered by {{ form.username }}. But how to basically do it? Is there any way to apply classes to the element other than changing the form class itself? -
ModelViewSet Queryset Filter with table based value with another table
I have two tables in my database ProductStock and Sales.And I am storing the Product info in the ProductStock table and Sales info inside the Sales table. Based on the total sum of sold quantity I want to filter the data, and return the data only whose quantity is greater than 0. for eg. PRODUCT STOCK DATA ID PRODUCT QUANTITY 1 Django Course 50 2 Social Codia 50 SALES DATA PRODUCT_STOCK_ID QUANTITY 1 5 1 45 2 35 2 10 Here the sold quantity of product 1 is 5+45=50, that means there is no stock left in the database for product 1. QUESTION IN SHORT : How can i fetch all these products whose quantity is greater than current_quantity - sold_quantity greater than 0. My ProductStock Model class ProductStock(Core): medical = models.ForeignKey(Medical, on_delete=models.CASCADE) distributer = models.ForeignKey(Distributer,on_delete=models.DO_NOTHING) product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='product') variant = models.ForeignKey(Attribute,on_delete=models.DO_NOTHING) batch = models.CharField(max_length=20,null=True, blank=True) purchase_price = models.CharField(max_length=10,null=False, blank=False) price = models.CharField(max_length=10,null=False,blank=False) quantity = models.IntegerField(null=False,blank=False) location = models.ForeignKey(Location, on_delete=models.DO_NOTHING) low_stock = models.IntegerField(default=10,null=False,blank=False) expire_date = models.DateTimeField(null=False,blank=False) My SALE Model class Sale(Core): product_stock = models.ForeignKey(ProductStock,on_delete=models.CASCADE,related_name='sales') medical = models.ForeignKey(Medical,on_delete=models.CASCADE,related_name='medical') quantity = models.IntegerField(default=1,null=False,blank=False) price = models.CharField(max_length=10,null=False,blank=False) discount = models.FloatField(max_length=10,default=0) ProductStockViewSet class ProductStockViewSet(ModelViewSet): serializer_class = ProductStockSerializer permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] def get_queryset(self): … -
fully empty logs using gunicorn nginx and django
I have the following django API set up with nginx and gunicorn and all my logs except one are completely empty. I have never set up logs before. I was expecting to get the normal server output of any 500 errors and such like I get on local in my terminal: nano /etc/nginx/sites-available/stocks_backend server { ... access_log /root/stocks_backend/log/nginx-access.log; error_log /root/stocks_backend/log/nginx-error.log; } /etc/supervisor/conf.d/stocks [program:stocks] user=root directory=/root/stocks_backend command=/root/stocks_backend/stocks-env/bin/gunicorn --workers 3 --bind unix:st> autostart=true autorestart=true stdout_logfile=/root/stocks_backend/log/gunicorn.log stderr_logfile=/root/stocks_backend/log/gunicorn.err redirect_stderr=true /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/root/stocks_backend ExecStart=/root/stocks_backend/stocks-env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target 3 of the 4 logs are empty: root@-droplet:~/stocks_backend# cat log/nginx-error.log root@-droplet:~/stocks_backend# cat log/nginx-access.log root@-droplet:~/stocks_backend# cat log/gunicorn.err [2022-08-25 21:27:39 +0000] [61321] [INFO] Starting gunicorn 20.1.0 [2022-08-25 21:27:39 +0000] [61321] [INFO] Listening at: unix:stocks_backend.sock (61321) [2022-08-25 21:27:39 +0000] [61321] [INFO] Using worker: sync .... [2022-08-27 07:27:06 +0000] [67233] [INFO] Shutting down: Master [2022-08-27 07:27:08 +0000] [69840] [INFO] Starting gunicorn 20.1.0 [2022-08-27 07:27:08 +0000] [69840] [INFO] Listening at: unix:stocks_backend.sock (69840) [2022-08-27 07:27:08 +0000] [69840] [INFO] Using worker: sync [2022-08-27 07:27:08 +0000] [69842] [INFO] Booting worker with pid: 69842 [2022-08-27 07:27:08 +0000] [69843] [INFO] Booting worker with pid: 69843 [2022-08-27 07:27:08 +0000] [69844] [INFO] Booting … -
Send context the template in a class based view
How can I send context to my template in a class based view with the get_object funtion? This is my class: class DetailMessages(LoginRequiredMixin, DetailView, ChannelFormMixin): template_name = 'DM/chat.html' def get_object(self, *args, **kwargs): my_username = self.request.user.username username = self.kwargs.get("username") channel, _ = Channel.objects.get_dm_channel(my_username, username) if channel == None: raise Http404 context = {"example1" : "I want this on the template", "example2" : "I want this on the template too"} return channel -
why the css of my django application only works in incognito mode?
I don't know if it's happened to someone else, but I have a django application that only shows the styles created in css only when it's in incognito mode, when the browser is in normal mode you can't see the changes created in css. what would cause the problem? and how can i fix it?