Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am using django and my login form is not working
I have a login form in index.html file and in same file I have login form by clicking in login button I want message to displayed you logged in and some buttons will visible. But I am not getting any response i view.py i tried to print something in terminal to check login_view is getting called or not but i got nothing. I am not getting any error message too. My html code- <form method="POST" action="{% url 'login_view' %}" id="login-form"> <h5>Login Here</h5> {% csrf_token %} <input type="email" class="input-field" placeholder="Email" id="mail" name="email"><br> <input type="password" class="input-field" placeholder="Password" id="loginpass" name="password"><br> <button id="login" type="submit">LOGIN</button><br> </form> my view.py code- def login_view(request): print("View accessed") if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email__iexact=email, password=password) if user is not None: login(request, user) messages.success(request, 'You are logged in ') return redirect('home') else: messages.error(request, 'Invalid email or password.') else: messages.error(request, 'Error in login.') return render(request, 'index.html') my url code- from django.contrib import admin from django.urls import path from PMP import views from PMP import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name='home'), path('register/', views.register_view, name='register'), path('', views.login_view, name='login_view'), ] -
When we apply the migration process, It can't done correctly, error occurs
Applying branches.0002_remove_branch_district_remove_branch_sub_areas_and_more...Traceback (m ost recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backen ds\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File Migration process not done -
cannot static file through static url using django.test.client
1.env python : 3.8.14 django version : '4.2.4' 2.Purpose Make sure that the static file is saved Make sure that the static file can be accessed from the web browser 3.Issue The problem is that after running django server, the static file can be accessed through url, but not in the unitest environment. For example, suppose a file is stored in the following path 'MAPPER #<- project dir |-datasets #<-app name |-static |-datasets |-images |-Recursion Cellular Image Classification.jpeg 3.1 Access the browser after running the server enter the following path into the browser to confirm that it works well. http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg 3.2 unittest get a 404 status code. and cannot get the image file from django.test import Client client = Client() res_redirect = self.client.get(res.url) 4. try I tried using requests.get , but i didn't work requests.get(http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg) 5. Question SO this is my question, how can i access file through url in unittest env -
Am I doing CSRF right?
I'm making a website that's business in the front, but all Django in the back. Django is what concerns me. Each request asks for a CSRF token. Actually, two tokens. One is set automatically by a cookie, and another has to be provided as a POST argument. So I have an API endpoint that sends a token. Then I use that token to make other requests. But this feels like having a guard who won't let you in without a password, but will gladly tell you the password if you ask him for it. Whom does this help? -
Django Rest Framework, two different approach to POST request
i have question about two different approaches in DRF (Django Rest Framework) regarding POST request. So my question is if it is better to keep view and serializer simpler with Approach 2 in beginning or is it more common to start with approach 1 because in this case it is more likely I would need .create() method in future? Approach 1: // view.py class ExampleView1(APIView): def post(self, request): data = request.data serializer = CourseSerializer(data=data, context={"request": request}, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) // serializer .create() method class ExampleSerializer(ModelSerializer): def create(self, validated_data): user = self.context.get("request").user return Course.objects.create(**validated_data, owner=user) Approach 2: class ExampleView2(APIView): def post(self, request): data = request.data data["owner"] = request.user.pk serializer = CourseSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) -
Specify multiple targets to the django migration command
I am planning to load a bunch of data from elsewhere another environment into my development database. The problem is that the data source is not necessarily from the most recent version. I have a list of apps:migration_levels, that I can migrate too. But there does not seem to be a good way give the migration command multiple targets. how can I do somthing like this: ./manage.py migrate postapp:0020 commentapp:0015 userapp:0008 We tried looping and doing one app at a time, but ran into problems with cross dependencies. If there is a library that provides a version of this command, that would also be a valid answer. -
Why is my Django CreateView not able to create multiple records for work experience using formsets?
I am currently working on a Django project where I'm implementing a Candidate Profile creation feature using the CreateView class. The Candidate Profile consists of general candidate information as well as multiple work experience records. To achieve this, I have created a form class for the candidate information (CandidateForm) and a formset for the work experience records (WorkExperienceFormSet). Here's how I've set up my CandidateProfileCreateView: class CandidateProfileCreateView(CreateView): form_class = CandidateForm model = Candidate_Account template_name = "candidate_create_profile.html" def get(self, request, *args, **kwargs): candidate_form = CandidateForm() workexperience_formset = WorkExperienceFormSet(queryset=WorkExperience.objects.none()) return render( request, self.template_name, { 'candidate_form': candidate_form, 'workexperience_formset': workexperience_formset, } ) def post(self, request, *args, **kwargs): candidate_form = CandidateForm(request.POST, request.FILES) workexperience_formset = WorkExperienceFormSet(data=request.POST) if candidate_form.is_valid() and workexperience_formset .is_valid(): candidate_object = candidate_form.save() workexperience_instances = workexperience_formset.save(commit=False) for workexperience_instance in workexperience_instances: workexperience_instance.candidate = candidate_object workexperience_instance.save() return HttpResponseRedirect(self.get_success_url(candidate_object)) return render( request, self.template_name, { 'candidate_form': candidate_form, 'workexperience_formset': workexperience_formset, } ) def get_success_url(self, candidate_object): return reverse('candidate_profile', kwargs={'pk': candidate_object.pk}) My problem is that although the candidate information is being saved correctly, I'm facing issues when trying to create multiple work experience records using the formset. The formset is not able to create or save the work experience instances as expected. I've verified that both the candidate_form and workexperience_formset are valid … -
syncing products with d-stripe
I am having trouble syncing the products from my Stripe account to my django project. I've successfully synced the products, but I also inadvertently synced my entire stripe purchase and payment history to my django project. I followed most of this tutorial which describes how to set up stripe subscriptions on your django site using dj-stripe. When it came time to adding my products, the tutorial says to use this command: python manage.py djstripe_sync_plans_from_stripe But that command did not work for me. The command that did work for me was python manage.py djstripe_sync_models This worked but it literally downloaded all of my stripe data and synced it to my django project, which was unnecessary. I just wanted to sync the subsription products that I created. How can I sync only the products from my stripe account? -
Is it possible to run a django pytest that has access to multiple databases, without executing the test against each database?
I have a Django project in which I'm trying to add a second database, however I'm having a hard time getting my existing test suite to cooperate. I'm utilizing django==3.2.16, pytest==6.2.2 along with pytest-django==4.3.0. I seem to be running into two problems: I'm seeing tests fail with an error like such AssertionError: Database queries to 'second' are not allowed in this test. Add 'second' to pytest_django.fixtures._django_db_fixture_helper.<locals>.PytestDjangoTestCase.databases to ensure proper test isolation and silence this failure. From what I've found through issues and documentation is that I can do something like this to configure the test to have permission to the second db pytestmark = pytest.mark.django_db(databases=['default', 'second']) By having this at the top of my test file, it seems all the tests within have access to 'second', but this comes with the side effect that the test is now run TWICE, on each of the databases. [gw0] [ 2%] PASSED src/app/tests/test_some_stuff.py::test_case_1 [gw0] [ 2%] ERROR src/app/tests/test_some_stuff.py::test_case_1 That is not the behaviour I'm looking for. I need the test to be run once, with access to both databases, and I can't seem to find an existing solution for this. Is what I'm trying to accomplish possible within my existing toolset/versions? -
Context doesn`t send to the render_to_string Python/Django
hi guys I have a Django view that I want to filter my products with ajax(Js) and I think u know that I need to show the products to template too! Im using render to string Function which gets a template name and a context(dictionary) and return the string of the template , now my problem is my , idk why but my context is not sending to the template , if u have ever used Pycharm u know that for example when u map a template , if every thing is ok it will shows the template icon in the left near the line number! and every things is ok for me but still context doesnt send :( , i should say that I have a for loop in my template and I think u Know that too , when u click on your for loop context it will move you to the context in view but for me it shows "Cannot find the Declaration" ill write my codes , and ill be thankful if u guys help me :D ( and I have tried context: {"asd": asd} , {"asd": asd} every methods for a template: {% for product … -
Extracting JSON from API response using .json() causes entire Django view to run multiple times
On a locally-hosted Django server, I'm using the requests module to send an request to an external API. For example, this code works fine: from django.http import HttpResponse import requests url = "https://rapidapi.com" apiKey = "MY-KEY" apiHost = "isitwater-com.p.rapidapi.com" headers = { "X-RapidAPI-Key": apiKey, "X-RapidAPI-Host": apiHost } locationParameters = { "latitude": "32", "longitude": "-26" } response = requests.get(url, headers=headers, params=locationParameters) print(response) def generatePage(request): return HttpResponse() And outputs what I'd expect: <Response [200]> But when I try to get the JSON from the (supposedly) successful request using .json(), the entire view runs twice and then throws an error. For example, this code: from django.http import HttpResponse import requests url = "https://rapidapi.com" apiKey = "MY-KEY" apiHost = "isitwater-com.p.rapidapi.com" headers = { "X-RapidAPI-Key": apiKey, "X-RapidAPI-Host": apiHost } locationParameters = { "latitude": "32", "longitude": "-26" } response = requests.get(url, headers=headers, params=locationParameters) print(response) print(response.json()) def generatePage(request): return HttpResponse() Outputs the following: <Response [200]> <Response [200]> Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Derek\Desktop\World Color Map\World_Color_Map-xFfPFma1\Lib\site-packages\requests\models.py", line 971, in json return complexjson.loads(self.text, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 355, in raw_decode raise … -
django channel websocket failed
in my frontend which is built with vue js , alongside npm run serve ( running outside docker) the webscocket throw this error WebSocket connection to 'ws://localhost:8000/ws/notifications/' failed: My infrsactructure in docker , is looking like this Backend Code of Backend\Backend\asgi.py """ ASGI config for Backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack # Setting the default Django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Backend.settings') # Import the WebSocket routing from your notifications app (not the Backend app) import notifications.routing # Create the ProtocolTypeRouter and include both the standard Django application # and the websocket application from the routing you've created in your notifications app. application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(notifications.routing.websocket_urlpatterns) ), }) Code of Backend\Backend\wsgi.py """ WSGI config for Backend project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Backend.settings') application = get_wsgi_application() Code of Backend\Backend\settings.py """ Django settings for Backend project. Generated by 'django-admin startproject' using Django 4.2.4. For more information on … -
Django CORS error in media file | Nginx | React
I am trying to fetch image from my django server from my react app. Tried multiple configuration but nothing to rescue. It would be great if anyone could provide any insight or leads or something I am missing React Using react behind nginx (on client machine) so origin is always http://127.0.0.1 instead of http://localhost:3000 import axios from "axios" export async function getImageFromNginx() { const IMAGE_URL = "http://{SERVER_URL}/media/pages/64d3d8cb4d3bd545823595e4.png" const config = { mode: 'cors', // no-cors, *cors, same-origin headers: { 'Access-Control-Allow-Origin' : 'http://127.0.0.1', 'Access-Control-Allow-Credentials': 'true', }, auth: {'username': 'username', 'password':'password'}, withCredentials: true, } console.log(config) try{ const response = await axios.get(IMAGE_URL, config).then((res)=>console.log("in axios",res)) console.log('Call to Nginx') return await response.json(); }catch(error) { return []; } } Django in django settings for cors, have installed django-cors-headers and added app and middleware settings CORS_ALLOWED_ORIGINS = ['http://127.0.0.1'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['Content-Type', 'Access-Control-Allow-Origin'] CORS_ALLOW_METHODS = ['GET', 'POST', 'OPTIONS'] Django Method to serve file using nginx (on server) def send_file(roots, file_name, disposition_type=None, default_file_name=None): valid = ['/download/{}'.format(root) for root in roots \ if os.path.exists(get_absolute_filename(root,file_name))] if valid: response = HttpResponse() response['Content-Type'] = '' if disposition_type is not None: end_user_filename = default_file_name and default_file_name or file_name response['Content-Disposition'] = "{}; filename={}".format( disposition_type, end_user_filename) response['X-Accel-Redirect'] = os.path.join(valid[0], file_name) response['Access-Control-Allow-Origin'] = 'http://127.0.0.1/' … -
Is returning list of app_name + codename of permissions for currently logged in user a security risk in django?
I have an app named "todos" and inside this app I have a permission code named "add_todo", Is it a bad idea to return app name + code name(todos.add_todo) as a mechanism to control which buttons and UI to show to user in the Frontend? I currently wrote an endpoint that returns all of the user's permissions as a list in this format: "app_name.permission__codename". I was wondering whether this would pose a security risk or not. Also it's worth noting that only currently logged in user can see his/her own permissions. -
Django cannot import name 'Response' from 'rest_framework'
I have a Django rest_framework project which is working fine. I am using pipenv and used it to install django_rest_framework. I can import functions such as serializer from rest_framework and use them without problems. I would like to use rest_framework's Response class as givenhere and described here, so I wrote from rest_framework import Response This is not faulted by VSCode's syntax checks. However, when I start the server I receive the message cannot import name 'Response' from 'rest_framework' All help welcome -
Is it possible to stop the PyCharm debugger from exiting after an exception from Django shell?
I started the PyCharm debugger with python manage.py shell so I could interactively debug my Django project. However, if I run into an error, the debugger just exits. If I run python manage.py shell directly in a terminal this is not an issue. The same error will happen, but it doesn't just kick me out of the shell. Is there a way to have the same functionality while debugging in PyCharm? -
Secure way to use API keys and Client Secrets in the frontend of a django app
I have a django application with a react frontend. The frontend connects to a websocket server at one point with the following code client.send('PASS ${password}');. What is a safe secure way to keep that password in the backend and then access it when I need to connect to the websocket. Currently I just have it set as an environment variable and use an api request to my REST API to retrieve it when I want to connect. This works but I feel like its not the best way to do this. -
Deploying a Django web application that uses SQL Server
I am getting ready to deploy my Django app, with a SQL Server backend, but I'm not sure where to even start. I've done a lot of research and reading, but I have not found any clear path to follow. Does it have to be hosting with AWS, Azure, or the like? Can it instead be hosted on my Windows Server (on-prem)? -
Apache2 not starting on Debian server after following dev.to guide
I am trying to host my Django website on my Debian 12 server but I am encountering an error even after following the guide on dev.to. The error is that Apache2 is not starting and is showing the following message: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xeu apache2.service" for details. After running systemctl status apache2.service it is showing that without matching section. I have tried the following steps to fix the problem: I have checked that the Apache2 service is not running everytime restarting the server. I have checked that the port 80 is not being used by another process. I have cleared the Apache2 configuration files. I have reinstalled Apache2. However, I am still getting the same error. Can anyone help me to fix this problem? <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) … -
Django with djangorestframework-simplejwt results in POST error 403: Forbidden (CSRF cookie not set.): on /api/token/
i want to set up a simple Django Backend with a rest api. If i'am trying to login with the supplied urls, but everytime i try to login i get a 403 error: CSRF Verficatoin failed. CSRF cookie not set. This are my used apps: Django==4.1.10 # Rest Framework djangorestframework==3.14.0 djangorestframework-api-key==2.3.0 djangorestframework-simplejwt==5.2.2 markdown==3.4.4 # CORS for rest api django-cors-headers==4.2.0 and my settings: ALLOWED_HOSTS='*, localhost' ALLOWED_ORIGINS='http://*, https://*' CSRF_COOKIE_AGE=31449600 CSRF_COOKIE_NAME='csrftoken' CSRF_USE_SESSIONS=False CSRF_TRUSTED_ORIGINS='http://*, https://*' CSRF_COOKIE_HTTPONLY=False CSRF_COOKIE_SECURE=False CSRF_COOKIE_DOMAIN = None CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CORS_ALLOW_ALL_ORIGINS=False CORS_ALLOWED_ORIGIN_REGEXES='' CORS_ALLOWED_ORIGINS='http://localhost:8888, http://127.0.0.1:8888' the server runs on port 8888 with the command: python3 manage.py runserver 0.0.0.0:8888 The Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] and the Settings for the Rest Framework: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', # only for testing ], "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], } and these urls are in the introduction of the app: path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), and now, if i try following request: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "my_username", "password": "my_password"}' \ http://localhost:8888/api/token/ i get the error code 403, as described … -
Django a problem that chatgpt can not solve :-) i am newbie [closed]
`Django 4.2.3 I have a problen when i try to create a window. First i create a quote then when i want to add a window to the quote, the connection field between class Quote and class Windows is "quot" field. This field is shown to the user at the moment the user want to create a new window At the moment the form is sent to the function function create_window do not enter in the if form.is_valid() so it gives an error "This field is required" <ul class="errorlist"><li>quot<ul class="errorlist"><li>This field is required.</li></ul></li></ul> VIEW.py def create_window(request, quote_id): quote = get_object_or_404(Quote, pk=quote_id) if request.method == 'POST': form = WindowForm(request.POST) print(form.errors) if form.is_valid(): window = form.save(commit=False) window.quot = quote # Assign the related Quote form.cleaned_data['quot'] = quote window.save() return redirect('detail_quote', pk=quote_id) else: form = WindowForm(initial={'quot':quote}) context = {'form':form} return render(request, 'create_window.html', context) create_window.html <!DOCTYPE html> <html> <head> <title>Create New Window</title> </head> <body> <h1>Create New Window</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Create"> </form> </body> </html> MODELS.py class Quote(models.Model): quote_number = models.PositiveBigIntegerField(null=True, blank=True, unique=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) slug= models.SlugField(max_length=100, unique=True) def save(self, *args, **kwargs): if not self.quote_number: self.quote_number = generate_next_quote_number() super(Quote, self).save(*args, **kwargs) def __str__(self): return f"Nro Presupuesto: {self.quote_number}" def … -
pydev debugger: unable to find translation for: (please revise your path mappings)
I have a problem using debugpy with vscode on Windows with the repository on a local server. I have a dockerized django app with the following dockerfile and docker-compose: FROM python:3.6.15-slim-bullseye ARG ENVIRONMENT=master # Python logs to STDOUT ENV PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ TZ=America/Santiago \ DEBIAN_FRONTEND=noninteractive WORKDIR /app COPY requirements.txt . RUN set -x \ && buildDeps=" \ git \ build-essential \ libpq-dev \ libssl-dev \ locales \ gnupg \ wget \ " \ && runDeps=" \ pkg-config \ unzip \ lsb-release \ libcairo2-dev \ libpangocairo-1.0-0 \ " \ && apt-get update \ && apt-get install curl tzdata -y \ && apt-get install -y --no-install-recommends $buildDeps $runDeps \ && ln -fs /usr/share/zoneinfo/${TZ} /etc/localtime \ && dpkg-reconfigure -f noninteractive tzdata \ && locale-gen es_CL.UTF-8 \ && sed -i -e 's/# es_CL.UTF-8 UTF-8/es_CL.UTF-8 UTF-8/' /etc/locale.gen \ && wget http://dev.mysql.com/get/mysql-apt-config_0.8.26-1_all.deb \ && echo 'mysql-apt-config mysql-apt-config/select-product select Ok' | debconf-set-selections \ && dpkg -i mysql-apt-config_0.8.26-1_all.deb \ && rm mysql-apt-config_0.8.26-1_all.deb \ && apt-get update \ && apt-get install -y libmysqlclient-dev \ && pip install -r requirements.txt --no-dependencies \ && apt-get clean \ && apt-get autoremove -y \ && rm -rf /var/lib/apt/lists/* \ && rm -Rf /tmp/* version: "3.8" services: django: image: "django:dev" build: … -
Change the url that search_form hits during search in Django admin changelist page
I have a custom implementation for the changelist page in the Django admin, such that a custom query parameter is provided in the url. For example, it is like this: admin/app_label/model_name/?custom_parameter=value Although I have made the changes I needed to filters and action to work using this url, I have an issue with search. Hitting the search in changelist page, I see that it hits the normal url admin/app_label/model_name/ . This is an issue since I need the custom parameter in the GET request to appropriately handle things in the django admin backend. I have also seen the search_form.html file that renders the search element. Is there a way to define the url that the search will hit, either from the backend or somehow via the javascript of the search_form.html, since I also have the custom_parameter provided in the context of the html page? -
(admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'name', which is not a field of 'store.Category'
I'm making an ecommerce app with Django. The command terminal keeps popping the above error whenever I try to run a command with it. models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length = 150, db_index = True), slug = models.SlugField(max_length = 150, unique = True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name = 'product', on_delete = models.CASCADE) created_by = models.ForeignKey(User, on_delete = models.CASCADE, related_name= 'product_creator') title = models.CharField(max_length = 150) author = models.CharField(max_length = 150, default = 'admin') description = models.TextField(blank = True) image = models.ImageField(upload_to = 'images/') slug = models.SlugField(max_length = 150) price = models.DecimalField(max_digits = 4, decimal_places = 2) in_stock = models.BooleanField(default = True) is_active = models.BooleanField(default = True) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title admin.py: from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug' : ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'slug', 'price', 'in_stock', 'created', 'updated'] list_filter = ['in_stock', 'is_active'] list_editable = ['price', 'in_stock'] prepopulated_fields = {'slug' : ('title',)} It's also worth noting that for … -
Django gunicorn nginx 111 connection refused while connecting to upstream
A fresh Django application is running on the Debian server, configured via gunicorn and nginx. After setup i tried to connect to it, but i can reach it only by server ip. The only error i found is in nginx log: 2023/08/10 16:08:48 [error] 19252#19252: *9 connect() failed (111: Connection refused) while connecting to upstream, client: x.xx.xxx.xxx, server: mydomain.ru, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "xxx.xxx.xxx.xxx:80" or sometimes host: "mydomain.ru" my nginx configuration: server { listen 80; server_name mydomain.ru; access_log /var/log/nginx/example.log; location /static/ { root /home/alex/myproject; expires 30d; } location /media/ { root /home/alex/myproject; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } my gunicorn.conf bind = '127.0.0.1:8000' workers = 2 user = 'alex' timeout = 120 mydomain.ru is in django settings ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS, but anyway, when i python3 manage.py runserver django shows some activity only accessing it by server ip. when i stop project with supervisor there are no other servers in netstat -tpln Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 324/zabbix_agentd tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 20083/nginx: master tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 358/sshd tcp …