Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to copy annotations from one Django queryset to another?
I am currently trying to overcome the challenge of ordering a queryset in Django with foreign key attributes. As you may know this can have unintended results with duplicate entries. The other option is to specify an ordering on the same queryset but to avoid duplicates I specified that results should have distinct ids which leads no an error saying the distinct key should be in the initial ordering. So I resorted to creating another queryset to filter the id's in an already annotated queryset so i can get a fresh queryset with which can be ordered by what is needed in the end. -
python manage.py runserver not working or showing errors
Ive set up django on a virtual env and im trying to run it. I've made sure that python is installed and that my virtual env is activated. I created a django project "my_site" with the command django-admin startproject my_site . The virtual env is "my_env" This is my project directory: enter image description here In the command terminal when i run python migrate.py runserver nothing happens, the server crashes with no error message and i am not able to access localhost 8000 enter image description here This is the output for pip list : enter image description here This is the output for pip show Django : enter image description here This is my python and django version enter image description here I tried running : python C:\Users\Ananya\OneDrive\Desktop\django\manage.py runserver , I tried deleting and creating a new env . i was expecting the terminal output to be something like : enter image description here where i can be directed to localhost 8000 -
Routing does not work for Django on Azure Function
I have a Django App and I'm trying to migrate app into Azure Function. But seems like sub routes always return 404. Can someone please help on this. urls.py urlpatterns = [ path(FUNCTION_APP_PATH + '/admin/' , admin.site.urls), ] setting.py FUNCTION_APP_PATH = 'api/app' function.json { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "route ": "app/{*route}", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" } ] } init.py import azure.functions as func from config.wsgi import application def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse: return func.WsgiMiddleware(application).handle(req, context) Web Page output No web page was found for the web address: http://localhost:7071/api/app/admin/ HTTP ERROR 404 -
How to make a delete button delete a specific post?
I have this delete button with a dialog on it but the button does not get the post right and I think it always starts to delete from the first post so I end up deleting them all also my template does not even gets the correct title of the post even though I'm using the same tag why is that? it always gets the title of the first post and deletes only that not the one I click on I will appreciate your help views.py @login_required() def delete(request, id): poost = get_object_or_404(post, pk=id) if request.user == poost.author: poost.delete() messages.error(request, f'Post deleted!') return redirect("/") post.html (where my delete dialog and button is) <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text-muted"> Do you really want to … -
NoReverseMatch at /login/login/signup
I am trying to create a sign up page using django after the user press the sign up button i want the page to redirect them to another page using this line of code return redirect('congrat') and also a function for "congrat" has already been created by me def congrat(request): return render(request,"login/congratulation.html") also the url has been defined in the urls.py file path("login/congrat",views.congrat,name = "congrat"), but for some reason this is the output from the website after the button is clicked I have consulted chatgpt which told me to check my urls.py and check if the function was defined which i have done and i cant seem to find an error there. -
TFIDF Vectorizer not assigning values to all rows of data
I am attempting to create a song recommendation system. For starters I used TFIDF on all genre names with the following code: data['track_genre'] = data['track_genre'].fillna("") tfidf_vector = TfidfVectorizer(stop_words='english') #max_features= 60 tfidf_matrix_genre = tfidf_vector.fit_transform(data['track_genre']) tfidf_vector.get_feature_names_out() Once I did that I used pd.concat to combine it into a dataframe as shown here: data_full = pd.concat([data, pd.DataFrame(tfidf_matrix_genre.toarray(), columns=tfidf_vector.get_feature_names_out())], axis=1) data_full = data_full[data_full['track_name'].notna()] data_full = data_full.drop('track_genre', axis =1) Unfortunately, in the 'data_full' df some of the songs were not assigned any values from the vectorizer. For example, songs with the initial genre of "soul" have no values in any of the new TFIDF columns despite the vectorizer creating a "soul" column. This is unfortunate as my function first filters the data based on the vectorizer's descriptors and with certain soul songs this is impossible and results in an error. On all other genre's and songs I have checked thus far it seems to work well. My question is: Is there a way to ensure the vectorizer gives each row at least one value in the newly created columns? Also, are there any errors in my code / would you like to see more code? Below is where the error comes into play: song_title = … -
Django Admin is not showing X out of X selected and the link to select all
For some reason after I upgrade django to 3.2.21, when I select all records in the admin page, it's no longer showing 100 out of 100 records selected and providing the link to select all records across multiple paginated pages. I'm not doing anything special in the admin class, just set list_display, list_filter, list_display_links, and actions. Anyone knows what might be wrong? -
Creation of django project
Image of my problem(django) After installation of django in pycharm, I tried creating my first ever django project but I encountered a problem. Then I decided to check the version of django installed but same issue appeared. I want to know why is it so and the solution so I could begin with the project. The problem is in the image provided -
I got different results from a chi-squared test when using a calculator and sklearn chi2 function
Recently I was learning about chi2 test. For a toy dataset, X = np.array([0, 1, 0, 0, 1, 1]), y = np.array([0, 1, 0, 1, 0, 1]). When calculating the chi2 statistic and the p-value, I got different results. The first result is: Using online calculator which is the same as I calculate myself based on the knowledge I learned from class. The second result using sklearn chi2 is: Using sklearn.chi2 which I can not understand why. -
cloudflare with django hosting on aws causing "domain.com redirected you too many times"
After I transferred my nameserver from AWS Route 53 To Cloudflare (also with the same dns settings), I get: "mydomain.com redirected you too many times" I have this settings in django, which work without Cloudflare, I tried to remove them all but it didnt help. #SSL configuration SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True I currently use: nginx django ubuntu aws I really would like to use Cloudflare, any help to solve this issue ? -
DJango signup list
I have this Django model from django.db import models from django.utils.timezone import localtime from django.conf import settings from django.db import models # Create your models here. class Meal(models.Model): meal_time = models.DateTimeField("Tid/Dato") meal_description = models.CharField(verbose_name="Beskrivelse af måltid", max_length=300) meal_deadline = models.DateTimeField(verbose_name="Tilmeldingsfrist") meal_price_pp = models.DecimalField(verbose_name="Pris per person", decimal_places=2, max_digits=5) meal_price_tt = models.DecimalField(verbose_name="Pris i alt", decimal_places=2, max_digits=5) meal_resp = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_offer_takeaway = models.BooleanField(verbose_name="Tilbyd takeaway", default=False) meal_offer_eat_in = models.BooleanField(verbose_name="Tilbyd spisning i netværket", default=False) # meal_timezone = models.CharField(verbose_name="Tidszone", default='Europe/Copenhagen', max_length=50) def __str__(self): return (f"{self.meal_description} Dato:" f" {localtime(self.meal_time).date().strftime("%d/%m/%Y")} " f"{localtime(self.meal_time).strftime("%H:%M")} Pris: {self.meal_price_pp}") def weekday(self): weekdays = ["Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"] index = self.meal_time.date().weekday() return weekdays[index] def resp_name(self): return self.meal_resp.name class Participant(models.Model): list_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Bruger", on_delete=models.CASCADE) list_meal = models.ForeignKey(Meal, verbose_name="Måltid", on_delete=models.CASCADE) list_takeaway = models.BooleanField(verbose_name="Takeaway", default=False) list_eat_in = models.BooleanField(verbose_name="Spisning i netværket", default=False) list_registration_time = models.DateTimeField(verbose_name="Date/time registered") payment_due = models.DateField(verbose_name="Betales senest") payment_status = models.BooleanField(verbose_name="Er betalt", default=False) def registered_on_time(self): meal_record = self.list_meal return self.list_registration_time <= meal_record.meal_deadline def __str__(self): return f"Bruger: {self.list_user} Dato: {localtime(value=self.list_meal.meal_time).strftime("%x kl. %H:%M")}" And I would like to create a list of Meals where the (authenticated) user can select whether to sign up for a meal (on the Participants list) by selecting (if avalialable) check boxes for eat in, takeaway or both. I … -
how does the form_invalid() works in django5?
I am trying to pass the loggedin user to a form using form_invalid() and the code I used is as below. but it seems like there is a different way to code it in django 5.0 as the above code doesn't do anything. Any idea about how to do it in django 5.0? I tried : def form_invalid(self, form): form.instance.user = self.request.user return super(TaskListView, self).form_invalid(form) I want to : Restrict the user attribute of the model to the currently logged in user using django 5.0 -
Django rest not getting the image and attribute fields for any of my parent and child product
I crate an product model where I am showing all children product under it's parent but I am not seeing image and arribute fileds for any of my product. here my code **models.py class Product(models.Model): parent_product = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) ...others fileds class Attribute(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='product_images/') serilizer.py class AttributeSerializer(serializers.ModelSerializer): class Meta: model = Attribute fields = ('name',) class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image',) class ChildProductSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' class ProductSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() attributes = AttributeSerializer(many=True, read_only=True) images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' def get_children(self, obj): children = Product.objects.filter(parent_product=obj) serializer = ChildProductSerializer(children, many=True) return serializer.data here my response look like this [ { "id": 1, "children": [ {...my children product}] "title": "hello test sashjhas ahsbahs ahs ba sh as", "slug": "hello-test-sashjhas-ahsbahs-ahs-ba-sh-as", "description": "", "orginal_price": "200.00", "discount_price": "180.00", "discount": "10.00", "available": true, "quantity": 1, "unit": null, "is_published": false, "sku": "c2a4a7fa-afbd-484a-9cdf-ec03284ab2cc", "createdAT": "2023-12-29 19:50:13.637279+00:00", "updatedAt": "2023-12-29 19:52:53.172203+00:00", "parent_product": null } ] I added AttributeSerializer and ProductImageSerializer in my ProductSerializer and ChildProductSerializer but not getting the attribute … -
Strange duplicate logs in django app while starting
Basically I'm working on a website using django, and when I start the django app I can see that some lines are actually printed twice. Here is an example of logs: (in this case there is an error at the end, but when the app works correctly i don't see other duplicate logs, just at the startup) >python manage.py runserver test, this line should appear once! test, this line should appear once! Watching for file changes with StatReloader Watching for file changes with StatReloader Performing system checks... couldn't import psycopg 'c' implementation: No module named 'psycopg_c' System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): ... Maybe this information can be useful, some months ago I had to use another thread in this same app to perform a long task without making the website unavailable in the meanwhile. I stopped working at this code for some time and now I don't remember exactly what I did but probably i messed up something. I know it's difficult to help me with not so many details, but I don't even know/remember where to look, I would appreciate advices for a better debug of what's going … -
How to design a django website architecture with all the details ,proper plan
If we get a new django project requirement that we need to develop from scratch. Then how do We need to plan the project with all details in architecture like low level and high level design. I need some one to help me with detailed explanation and diagrams. I need exact architecture diagram and detailed api endpoints information -
Django throttle_scope doesn't seem to work
The problem I was trying to implement throttling following the django rest framework guide. Since I don't need to create another throttle class, I tried to use the .throttle_scope attribute. So, I implemented it like this: class MyView(APIView): throttle_scope = 'my_scope' def post(self, request) -> Response: # do something return Response(status=status.HTTP_200_OK) And in the settings I wrote something like this: REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'my_scope': '1/minute', } } What I tried I tried, using postman, to make more than 1 request per minute to that endpoint and I never received a 429 code. Than I tried creating a new throttle class and using the .throttle_classes attribute, like this: class MyView(APIView): throttle_classes = [MyThrottle] def post(self, request) -> Response: # do something return Response(status=status.HTTP_200_OK) class MyThrottle(UserRateThrottle): scope = 'my_scope' I left the settings unchanged and it worked as expected. Possible solution? So now I'm wondering, could it be that the throttling_scope attribute only works if the user is anonymous? -
What is the relationship here, One to Many or a Many to Many?
I am building a project(using django) whereby agents are issued with phones. When a phone gets damaged the agent sends the phone to hq for repairs. In the meantime, the agent is issued with another different phone. Once the phone gets repaired, its then issued to another agent who may have similar problems as the first agent. What is the relationship between the phone and agent keep in mind i want to preserve the history of phone ownership and also avoid having data that says " Phone x with imei XXXXX and Phone.Status=active is currently being used by more than one agent" I am still in planning phase but i cant crack this one -
How to fix django timeout error when sending email
I'm trying to make a simple django app that sends an email to a user, but every time i try to run the program, i get an error 'TimeoutError at /automail2/success [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond' this happens after a couple seconds of loading after the email address has been submitted. Here's a github link to the code https://github.com/Taterbro/automail I'm fairly new to coding and the stackoverflow community, so any help would be appreciated. tried to send an email using django expected the code to send an email the code timed out while trying to send the email -
Django-based Docker project will connect to local postgres DB on windows machines but not on a Mac or Linux machine
been struggling with this issue for close to a month now and I am at my wits end. I have the following docker-compose.yml file: version: '3.8' services: web: container_name: targeting build: ./Targeting command: python manage.py runserver 0.0.0.0:80 volumes: - ./:/usr/src/project/ ports: - "80:80" db: env_file: - ./.env restart: always image: postgres container_name: postgres environment: - POSTGRES_DB=${NAME} - POSTGRES_USER=${USER} - POSTGRES_PASSWORD=${PASSWORD} - POSTGRES_PORT=${PORT} ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ pgadmin: image: dpage/pgadmin4 container_name: pgadmin4_container restart: always ports: - "8888:80" environment: PGADMIN_DEFAULT_EMAIL: user-name@domain-name.com PGADMIN_DEFAULT_PASSWORD: strong-password volumes: - pgadmin-data:/var/lib/pgadmin volumes: postgres_data: pgadmin-data: and I have the following .env file: SECRET_KEY=random_secret_key DEBUG=TRUE NAME=postgres USER=postgres PASSWORD=password HOST=db PORT=5432 The following Dockerfile is used to create the python container: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/project # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ../requirements.txt . RUN pip install -r requirements.txt # copy project COPY .. . On a Windows machine, after a docker compose build and a docker compose up command is issued, the project will be up and running and the django project will connect to the postgres database perfectly fine. I have verified this on two … -
Django Backend is giving me this Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'
I have tried just about everything from researching. Basically I have my frontend server and a backend server. My fronend server is getting the error from the backend server that is running Django. This is my settings in my Django app """ Django settings for appliAI project. Generated by 'django-admin startproject' using Django 4.2.7. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'removed because I am not giving that out' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # asdf.com has is replacing my actual URL ALLOWED_HOSTS = [ "localhost", "127.0.0.1", "asdf.com", "*.asdf.com", ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sslserver', 'django_extensions', 'rest_framework', ] # Access-Control-Allow-Credentials = 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', # 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.asdf\.com$", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_DEBUG = True CORS_ALLOW_METHODS … -
Django channels and react useState variable for room parameter instead of url
Is it possible instead of a url parameter in django channels to just use state from react. I mean instead of having to go to a specific url for example 'chat/str:roomname' to do something like this const [roomName, setRoomname] = useState('example') const chatSocket = new WebSocket( `ws://${window.location.host}/ws/chat/${roomName}/` ); I am asking this because I don't wanna redirect users to another page when they want to chat. -
python (Djanjo) - Page not found
I don't understand what the problem is, I'm a beginner in Python and I was asked to do this. I would be grateful for your help)) urls.py views.py models.pyurls.py - 2 example.html - it should be reflected in the price result -
formulario en Django a outlook
eh estado trabajando en una app en django en la que debo implementar un formulario de contacto el cual el cliente podra completar con sus datos y luego al **correo empresarial de outlook **me deberia llegar el correo con la info que el cliente ingreso, a la vez se debe confirmar la existencia del correo que ingresa el cliente para enviarle una copia del correo, esto lo habia hecho antes pero con Gmail y con outlook al parecer no es igual alguien me puede ayudar para saber en que estoy fallando, ya que no se envia el correo, ni tampoco entiendo el error que me aparece, gracias. settings.py from dotenv import load_dotenv from pathlib import Path env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) from decouple import config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True OUTLOOK_EMAIL = config('OUTLOOK_EMAIL', default='') OUTLOOK_PASSWORD = config('OUTLOOK_PASSWORD', default='') DEFAULT_FROM_EMAIL = '#!' views.py def contact(request): if request.method == 'POST': form = ContactoForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] message = form.cleaned_data['message'] # Construir el cuerpo del correo email_body = f"Nombre: {name}\n" email_body += f"Email: {email}\n" email_body += f"Teléfono: {phone}\n" email_body += f"\nMensaje:\n{message}" # Crear el objeto EmailMessage email … -
DJANGO: send_mail is not throwing errors or exceptions
I want to send smtp emails. But it is not working and I do not know how to debug this problem. In my settings.py I set a complete wrong port: EMAIL_PORT = 3 In the Django shell I run this script without getting an error. send_mail is just returning 1 after execution. from django.core.mail import send_mail send_mail( 'Test Email', 'That is an test.', 'test@test.com', ['test@gmail.com'], fail_silently=False, ) I also have configured an error logger, which should log everything. But it is also not appearing anything in my logfile: ... 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, ... Is this the default behavior? I guess no? What I am doing wrong? -
Getting Unresolved attribute reference for inherited methods in Pycharm
I am getting Unresolved attribute reference for inherited methods in my Pycharm Django project. What I have tried without any luck: Used interpreter through poetry (also tried venv through poetry) Also tried to Invalidate caches and restart. Note: This issue seems to occurred only on inherited methods. When importing classes directly the autocomplete suggestions propagate correctly.