Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello guys,pls can help me:(staticfiles.W004) The Directory /Users/jcu/Desktop/work/webserver/static in the STATICFILES_DIRS setting does not exist
and so, I'm just interning and learning everything right now, I need to make sure that there is an input your name field and when entering the name it gives Hello,"name",I did it initially using js+node+webpack, but now I need to transfer it to Django, I have already entered and connected css files,but for some reason an error occurred with the js file I watched a lot of videos and guides, I set all the settings correctly and seemed to indicate the correct path to the folders, as well as the folders themselves are correctly arranged, but still nothing happens when you enter the name and click on the button and there is such an error in the console,if you need to throw off the code, please tell me about it, can there also be a problem that I connected css and js in the same HTML file? -
Visual Studio Django - Freezes on python manage.py createsuperuser
So, I'm new to Django and am using Visual Studio 2022 with Python 3.12 (which is apparently not fully supported by Visual Studio). When I start a fresh Django web app project, it prompts for me to create a super user. Doing so, it freezes (without any error message) as it executes "manage.py createsuperuser" (as shown in screenshot). Any suggestions? -
Issue with Swagger representation of geographical coordinates in Django using DRF and drf-yasg
I am facing an issue with Swagger representation for geographical coordinates in my Django project. I'm using Django Rest Framework (DRF) along with drf-yasg for API documentation. I have a model named Facility with a field coordinates representing geographical coordinates in the Point format. To handle this, I'm using the GeoFeatureModelSerializer from DRF-GIS and a custom serializer PointSerializer for proper representation. However, the Swagger documentation is not correctly displaying the coordinates. I suspect there might be an issue with how Swagger processes geographical data. Here are relevant code snippets: # models.py from django.contrib.gis.db import models class Facility(models.Model): coordinates = models.PointField() # serializers.py from rest_framework_gis.serializers import GeoFeatureModelSerializer from django.contrib.gis.geos import Point from drf_yasg.utils import swagger_serializer_method class PointSerializer(serializers.BaseSerializer): def to_representation(self, instance): if isinstance(instance, Point): return { 'type': 'Point', 'coordinates': [instance.x, instance.y], } def to_internal_value(self, data): if data['type'] == 'Point': coordinates = data['coordinates'] # Your coordinate validation here return Point(coordinates[0], coordinates[1]) @swagger_serializer_method(serializer_or_field=Point) def to_swagger_object(self, value): return { 'type': 'Point', 'coordinates': [value.x, value.y], } class FacilitySerializer(GeoFeatureModelSerializer): coordinates = PointSerializer() class Meta: model = Facility geo_field = 'coordinates' fields = '__all__' depth = 1 I implemented a custom PointSerializer with DRF-GIS's GeoFeatureModelSerializer in Django to handle geographical coordinates. The serializer works in regular API responses, … -
python: can't open file 'manage.py': [Errno 2] No such file or directory (Docker-compose)
when i tryna run a django server with docker-compose up, i got this error [+] Running 2/2 ✔ Network service_default Created 0.3s ✔ Container service-web-app-1 Created 0.5s Attaching to service-web-app-1 service-web-app-1 | python3: can't open file 'manage.py': [Errno 2] No such file or directory service-web-app-1 exited with code 2 My docker-compose version: "3.9" services: # postgres: # image: postgres:15 # container_name: dj_post # env_file: # - .env web-app: build: dockerfile: ./Dockerfile context: . ports: - '8000:8000' command: > sh -c "python3 manage.py runserver " My Dockerfile FROM python:3.8-alpine3.16 COPY requirements.txt /temp/requirements.txt WORKDIR /service EXPOSE 8000 RUN pip install -r /temp/requirements.txt RUN adduser --disabled-password service-user USER service-user I will attach the architecture of the folders below, but I immediately say that by setting the full path to manage.py in docker-compose file I get the same error,I just started studying docker and for two days I can't find a working solution to this problem,share your ideas:( -
Get a dictionary of related model values
I have a model Post with some fields. Aside from that I have some models which have Post as a ForeignKey. Some examples are: class ViewType(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="view_types", verbose_name=_("Post"), ) view = models.CharField( max_length=20, choices=VIEW_TYPE_CHOICES, verbose_name=_("View") ) ... class HeatType(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="heat_types", verbose_name=_("Post"), ) heat = models.CharField( max_length=30, choices=HEAT_TYPE_CHOICES, verbose_name=_("Heat") ) ... So what I want to do here is somehow get a dictionary with all the values of those fields in my view. For example instead of doing this for all of the models that have Post as a ForeignKey: heat_type = HeatType.objects.filter(post=post) view_type = ViewType.objects.filter(post=post) dict = { "view_type": view_type.view, "heat_type": heat_type.heat, etc... } get all the relevant related fields in one go. Is there a simpler solution for that? Or do I have to manually get all queries for each model? Thanks in advance -
VS Code debugger not working (by using launch.json) for a django project
I am having trouble using the debugger in VS code. This is my first time using VS code and I'm following a Django tutorial from VS code (https://code.visualstudio.com/docs/python/tutorial-django). By the section 'explore the debugger' I got stuck, because my debugger doesn't seem to work (probably because I did something stupid or didn't do something). The thing is, I don't get an error message or something but it just keeps running. As the status bar in VS code doesn't change in the color orange, see image (which it should according to the tutorial). Statusbar while debugging My debugger also doesn't seem to stop at the breakpoint, that I have set at line 9.enter image description here. And here it just keeps running enter image description here I tried stopping the debugger and trying it again, but the outcome doesn't change. -
AttributeError: 'Logger' object has no attribute 'warn'
I'm trying to connect celery to my django project via docker. But when starting the worker container, I get the following error - File "/usr/local/lib/python3.13/site-packages/kombu/transport/redis.py", line 92, in <module> crit, warn = logger.critical, logger.warn ^^^^^^^^^^^ AttributeError: 'Logger' object has no attribute 'warn' My requirements.txt file: Django==4.2.7 psycopg==3.1.13 celery[redis]==5.3.6 django-celery-beat==2.5.0 redis==5.0.1 My dockerfile: FROM python:3.13.0a1-alpine3.18 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements /temp/requirements RUN apk add postgresql-client build-base postgresql-dev RUN pip install -r /temp/requirements/local.txt WORKDIR /myproject COPY . . EXPOSE 8000 My docker-compose.yml: redis: image: redis:7.2.3-alpine3.18 ports: - '6379:6379' restart: always worker: build: context: . command: > sh -c "celery -A config worker -l INFO" restart: always depends_on: - redis Structure of my project: The src folder contains apps. I tried to solve this problem but I failed. Please tell me what the problem might be and how to solve it. Thank you! -
How can I send emails from the system (admin user) to the client authenticated by oauth2 using Microsoft email and django rest framework?
I know I can do it by configuring django's sendmail, it doesn't matter if the email is gmail or outlook. However, I cannot use an email with my own provider. I need to do this authentication with oauth2, how can I do it to send emails from my own provider? I hope to send emails with any provider that implements oauth2 -
View does not contain the user which send a request
i created a view for payment verification, but after the payment, even use logged in before, it return anonymous user. how can i edit my code to include the user which send the request def verify(request, *args, **kwargs): order_id = kwargs['order_id'] open_order: Order = Order.objects.filter( Q(user=request.user.id) & Q(is_paid=False)).first() total_price = int(open_order.total_price()) t_status = request.GET.get('Status') t_authority = request.GET['Authority'] req = None if request.GET.get('Status') == 'OK': req_header = {"accept": "application/json", "content-type": "application/json'"} req_data = { "merchant_id": MERCHANT, "amount": total_price, "authority": t_authority } req = requests.post(url=ZP_API_VERIFY, data=json.dumps( req_data), headers=req_header) if len(req.json()['errors']) == 0: t_status = req.json()['data']['code'] if t_status == 100: order = Order.objects.get_queryset().get(id=order_id) order.is_paid = True order.refrence_id = req.json()['data']['ref_id'] order.authority_id = t_authority order.pay_date = datetime.now() order.save() context = { 'verification_successful': True, 'reference_id': str(req.json()['data']['ref_id']), 'orderID': order_id, } return render(request, 'eshop_cart/verify.html', context) elif t_status == 101: context = { 'verification_successful': False, } return render(request, 'eshop_cart/verify.html', context) else: context = { 'verification_successful': False, } return render(request, 'eshop_cart/verify.html', context) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") else: context = { 'verification_successful': False, 'order_id': order_id, } return render(request, 'eshop_cart/verify.html', context) how can i edit this code to have user id in it, thanks for helping -
Why is this Django test opening so many database connections?
I'm testing my Django REST API using Schemathesis and Django's built-in unittest. The code for my test suite is: from contextlib import contextmanager import schemathesis from hypothesis import given, settings from hypothesis.extra.django import LiveServerTestCase as HypothesisLiveServerTestCase from my_app.api import api_v1 from my_app.tests import AuthTokenFactory # 3 requests per second - `3/s` # 100 requests per minute - `100/m` # 1000 requests per hour - `1000/h` # 10000 requests per day - `10000/d` RATE_LIMIT = "10/s" openapi_schema = api_v1.get_openapi_schema() @contextmanager def authenticated_strategy(strategy, token: str): @given(case=strategy) @settings(deadline=None) def f(case): case.call_and_validate(headers={"Authorization": f"Bearer {token}"}) yield f class TestApiSchemathesis(HypothesisLiveServerTestCase): """ Tests the REST API using Schemathesis. It does this by spinning up a live server, and then uses Schemathesis to automatically generate schema-conforming requests to the API. """ def setUp(self): super().setUp() self.schema = schemathesis.from_dict( openapi_schema, base_url=self.live_server_url, rate_limit=RATE_LIMIT ) def test_api(self): """ Loop over all API endpoints and methods, and runs property tests for each. """ auth_token = AuthTokenFactory().token for endpoint in self.schema: for method in self.schema[endpoint]: with self.subTest(endpoint=f"{method.upper()} {endpoint}"): strategy = self.schema[endpoint][method].as_strategy() with authenticated_strategy(strategy, auth_token) as run_strategy: run_strategy() This has been running in CI just fine for a while, but now that I've added some new REST endpoints, I've started getting errors like: psycopg2.OperationalError: connection … -
I need the success swa to be shown when entering the password correctly
js document.addEventListener("DOMContentLoaded", function () { const botonGuardarCambios = document.getElementById('botonGuardarCambios'); botonGuardarCambios.addEventListener('click', function() { const form = document.querySelector('form'); const formData = new FormData(form); // Mostrar el componente cuando se carga la página const passwordHelpBlock = document.getElementById('passwordHelpBlock'); passwordHelpBlock.classList.remove('d-none'); // Borrar mensajes de error al recargar la página const formErrors = document.getElementById('form-errors'); if (formErrors) { formErrors.classList.add('d-none'); } const url = `/usuarios/cambiar_password`; console.log('antes del fetch') fetch(url, { method: 'POST', body: formData, }) .then((response) => response.json()) .then((data) => { console.log(data); if (data.success) { // Mostrar el Swal después de ocultar el componente Swal.fire({ icon: 'success', title: 'Éxito', text: 'Guardado correctamente', showConfirmButton: false, timer: 1500 }).then(() => { // Recargar la página solo si la contraseña se ha cambiado correctamente location.reload(); }); } else { console.log('Error al intentar cambiar la contraseña:',error); Swal.fire({ icon: 'error', title: 'Error', text: 'No se pudo cambiar la contraseña', }); } }) .catch((error) => { console.log('Error al intentar cambiar la contraseña:', error); Swal.fire({ icon: 'error', title: 'Error', text: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', }); }); }); }); views.py def cambiar_contraseña(request): try: if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return JsonResponse({ 'success': True, }) else: # Manejar errores en el formulario for field, errors in form.errors.items(): for error in errors: … -
How do I serve my Django App in a SSH connection with limited user restrictions?
The context is the following: I'm using a SSH connection to my college's serve, on teacher's demands, in order to serve my Django application. I found out - I suppose - that by using gunicorn I can deploy my Django application. Furthermore I found out you can bind it to a specific port. When I do the following command gunicorn --bind 0.0.0.0:8000 myapp.wsgi. I proceed to my college site address, and use the port, returning 404; collegesite:8000/ What could be the problem here? Am I lacking permissions from the OS? Do I need to run gunicorn as sudo? -
Data sending with ESP8266 and receive with Django
I want to send data from ESP8266 to Django How can i? Can you please help me Thanks?! I tried this code in Django: views.py def data(request): if request.method=="POST": data = Data() data.temperature = request.POST.get('Temperature') api_key = request.POST.get('api_key') data.save() return HttpResponse("<h1>Data received and saved.</h1>") elif request.method == "GET": return HttpResponse ("<h1>Data received and save<h1>") -
How to connect bootstrap form to django form?
So, I need to have the styling of the bootstrap classes but actually have it connect to the django form in question. `` <div class="row"> <div class="col-sm-3"> <label for="last_name" class="form-label">Last Name</label> </div> <div class="col-sm-9"> <input type="text" class="form-control" placeholder="Your last name..." id="last_name" value="{{form.last_name.value}}"> </div> </div>`` {{form.last_name}} on its own for example renders the form and actually makes it connect to the database, as it should. It looks ugly though and is thus not what I need. value="{{form.last_name}}" in the above codeblock renders the start of the input tag. -
django cookiecutter shared database server
This is a very easy question, but for some reason I can’t find the answer myself. I have two microservices in Django, I combined them in Docker, but for some reason they don’t want to connect to the postgres database. So how can i resolve this. Here is my configs (im using django-cookiecutter), dockerfiles is stay standart Service A: .envs/.local/.postgres # ------------------------------------------------------------------------------ POSTGRES_HOST = postgres POSTGRES_PORT = 5432 POSTGRES_DB = service_A POSTGRES_USER = debug POSTGRES_PASSWORD = debug service B: # ------------------------------------------------------------------------------ POSTGRES_HOST = postgres POSTGRES_PORT = 5432 POSTGRES_DB = service_B POSTGRES_USER = debug POSTGRES_PASSWORD = debug docker-compose.yml version: "3.8" volumes: postgres_data: {} postgres_data_backups: {} services: service_A: build: context: service_A dockerfile: ./compose/local/django/Dockerfile image: service_A_local ports: - '8001:8001' command: /start service_B: build: context: service_B dockerfile: ./compose/local/django/Dockerfile image: service_B_local ports: - '8002:8002' command: /start postgres: build: context: . dockerfile: ./service_A/compose/production/postgres/Dockerfile image: postgres container_name: postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_data_backups:/backups env_file: - service_A/.envs/.local/.postgres - service_B/.envs/.local/.postgres -
Django framework proplems
For example, from all these movies, when the user chooses a movie, how do I show him the movie he chose specifically? How is it done? I want a detailed explanation with codes When he presses the watch button and I take him to the page for one movie, how do I show him the movie he specifically chose? -
Record Deletion from django model
if I have a live application with thousands of users in this scenario how I delete a record from Django model on live server ??? without effecting ?? first I reverse the migration then delete the record and makemigrations I try thin in local machine code and after changing I push the changes on server -
Django keeps recreating the same migration file for ManyToManyField with default value
I'm encountering a recurring issue in my Django project where Django keeps recreating the same migration file for a ManyToManyField with a default value set to MyModel.objects.all. Each time I run python manage.py makemigrations, it generates a new migration file that keeps creates the same code but increment the dependencies only, even though the model hasn't changed. When running python manage.py migrate it will show me: Running migrations: No migrations to apply. Your models in app(s): 'my_model' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Here's an example of the migration code that keeps getting regenerated: # 0016_alter_my_model_my_field_name_and_more.py class Migration(migrations.Migration): dependencies = [ ("another_service", "0004_previous_migration"), ("this_service", "0015_alter_my_model_my_field_name_and_more"), ] operations = [ migrations.AlterField( model_name="my_model", name="my_field_name", field=models.ManyToManyField( default=django.db.models.manager.BaseManager.all, help_text="My field text help.", to="another_service.my_other_model", ), ), ] The model and field are defined as this: class MyModel(PolymorphicModel): ... my_field_name = models.ManyToManyField( "another_service.AnotherModel", default=AnotherModel.objects.all, help_text="My field text help.", ) ... How can I make my_field_name to have all items from my AnotherModel on database without have the makemigrations on infinite loop to recreate this? -
Internal Server Error: MultiValueDictKeyError in Django
I have problem with my ecommerce project. When i try to add item to the cart I get this error. But item is in the cart and I get this problem only in my console. Can you please help me get rid of this error? html code - https://i.stack.imgur.com/LCns9.png js code - https://i.stack.imgur.com/6NE7L.png view / function - https://i.stack.imgur.com/mja5v.png VScode/ console - https://i.stack.imgur.com/aufFg.png browser/ console - https://i.stack.imgur.com/hcwMm.png error detail - https://i.stack.imgur.com/gEV1Y.png -
pyCharm warning in django code: Unresolved attribute reference 'user' for 'WSGIRequest'
in my brandnew PyCharm professional edition I get the warning "Unresolved attribute reference 'user' for 'WSGIRequest'". The warning occurs in the first line of MyClass.post() (see code below). from django.views import generic from django.db import models from django.http.request import HttpRequest from django.shortcuts import render from django.contrib.auth.models import AbstractUser class CustomUser( AbstractUser ): emailname = models.CharField() class Invoice( models.Model ): posted = models.DateField() class BaseView ( generic.DetailView ): model = Invoice def __int__( self, *args, **kwargs ): super().__init__( *args, **kwargs ) # some more code class MyClass( BaseView ): def __int__( self, *args, **kwargs ): super().__init__( *args, **kwargs ) # some more code def post( self, request: HttpRequest, *args, **kwargs ): context = { 'curr_user': request.user, } # <-- Unresolved attribute reference 'user' for class 'WSGIRequest' # some more code html_page = 'mypage.html' return render( request, html_page, context ) user ist a CustomUser object. Debugging shows, that user is a known attribute in CustomUser and the code works well. Other attributes of request like request.path or request.REQUEST are not warned. Django support is enabled. I work with PyCharm 2023.2.5 (Professional Edition), Windows 11 Can anybody help? What is my mistake? Regards -
Django ldap search restriction by group does not work, search by CN does not work
If I search with this query: AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=E,DC=i,DC=e,DC=int", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") The person is located and logged in. If with a request like this AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=allow,OU=Groups,DC=i,DC=e,DC=int", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") I get the following error: Invoking search_s('CN=allow,OU=Groups,DC=i,DC=e,DC=int', 2, '(sAMAccountName=a.t)') search_s('CN=allow,OU=Groups,DC=i,DC=e,DC=int', 2, '(sAMAccountName=%(user)s)') returned 0 objects: Authentication failed for a.t: failed to map the username to a DN. Why? I need to allow access to people in a limited group. If I do this AUTH_LDAP_REQUIRE_GROUP = "CN=allow,OU=Groups,DC=i,DC=e,DC=int" AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType() AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "CN=allow,OU=Groups,DC=i,DC=e,DC=int", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)") I get this error: cn=Tim Allen,ou=1,ou=2,ou=e,dc=i,dc=e,dc=int is not a member of cn=allow,ou=groups,dc=i,dc=e,dc=int Authentication failed for a.t: user does not satisfy AUTH_LDAP_REQUIRE_GROUP In this case, of course, there is a user in the group. Please tell me what to fix? Thank you -
How to create blob column via Python Migrate
I know it is a bad idea to stored whole file binary into database blob column, so forgive me I have a model defined in python code: class UploadFile(models.Model): id = models.AutoField(auto_created=True, primary_key=True) FileBinary = models.FileField(blank=False, default=None) Then I run migration python manage.py makemigrations && python manage.py migrate But in Mysql I have Columns: COLUMN_NAME DATA_TYPE id int FileBinary varchar How I fixed the code to create blob instead of varchar? -
Annotate Django Foreign Key model instance
Is it possible in Django to annotate a Foreign Key instance? Suppose I have the following models: class BaseModel(models.Model): pass class Foo(models.Model): base_model = models.ForeignKey('BaseModel', related_name='foos') class Bar(models.Model): base_model = models.ForeignKey('BaseModel', related_name='bars') I want to count the Bars belonging to a BaseModel attached to a Foo, that is: foos = Foo.objects.all() for foo in foos: foo.base_model.bars_count = foo.base_model.bars.count() Is it possible in a single query? The following code is syntactically wrong: foos = Foo.objects.annotate( base_model.bars_count=Count('base_model__bars') ) This one would perform that job in a single query: foos = Foo.objects.annotate( base_model_bars_count=Count('base_model__bars') ) for foo in foos: foo.base_model.bars_count = foo.base_model_bars_count Is there a way with a single query without the loop? -
Double Increment Issue in TotalVote Count After Payment in django App
I'm currently developing a talent application where participants can receive votes from voters, and each vote incurs a cost. The collected funds from these votes are meant to be credited to the respective contestants. For instance, if someone casts a vote for a contestant with a count of 10 votes, the contestant's total vote count should increase by the number of votes received. However, I've encountered an issue after a user casts a vote and makes a payment. It appears that the total vote count is incrementing by twice the intended value. For example, if a user submits a vote of 10, the contestant's total vote count is increasing by 20, which is unexpected and seems incorrect. Any assistance in resolving this issue would be greatly appreciated. Please find my code below: def contestant_detail_payment(request, slug, *args, **kwargs): contestant = get_object_or_404(Contestant, slug=slug) vote_charge = contestant.get_vote_per_charge() if request.method == "POST": email = request.POST.get("email", "") vote = request.POST.get("vote", "") amount = int(request.POST["amount"].replace("₦", "")) pk = settings.PAYSTACK_PUBLIC_KEY payment = Payment.objects.create( contestant=contestant, amount=amount, email=email, vote=vote, ) payment.save() context = { "payment": payment, "field_values": request.POST, "paystack_pub_key": pk, "amount_value": payment.amount_value(), "contestant": contestant, } return render(request, "competitions/make_payment.html", context) context = { "contestant": contestant, "vote_charge": vote_charge, } return render(request, … -
How do I put an ID?
I have a Django backend project connected to a Mongo database. I want to manually and personally define the field ID inside this class to be stored in the database so that Django and Mongo can communicate with each other so that I can edit or delete through the Django admin panel. from djongo import models class Category2(models.Model): # id = name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) price = models.PositiveIntegerField() class Meta: ordering = ('name',) def __str__(self): return self.name Unfortunately, I have no idea how to do it