Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I reduce number of requests made to redis data store when using celery and beat
I am using on a project Django + celery + beat. Is there a way how to reduce number or requests made to redis data store? -
Phonenumber-field issue
I have already installed django-phonenumber-field and also added in Installed apps but still facing this issue (AttributeError: module 'django.db.models' has no attribute 'PhoneNumberField') while running migrations I was expecting the migrations to work fine -
Can not install typed-ast==1.1.0
I am trying to run a django python project, but I can not install typed-ast == 1.1.0. Below is the error I encountered, please help me note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for typed-ast Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml-based projects I tried to find a way on the internet but couldn't. -
How to implement fool proof Error handling in python-django
I am a newbie and have a question related to error handling in django/python; hoping the pros can provide some directions. In my project, I am sometimes using try/except and other places checking for errors returned from functions. Mostly, all API calls have try/except and then general error handling otherwise. As the project has grown in size, it is becoming quite unwieldy and now it is very hard to ensure that all errors are being properly handled. Especially, with multiple levels of nested functions, it is hard to make sure that I am checking for errors from each function, propagating it properly upstream and handling at every level. I have so far ensured that all APIs have try/except. And I am also checking each function for error handling. My simple question is - is there a defined or recommended way to handle errors? is it possible to really end the program and gracefully exit (after logging the error + stack trace in the log file) in case of certain errors? This is because even if I am handling the error in the function and returning appropriate value, I don't want to rely on the upstream functions properly handling/propagating the error? … -
Adding a Doughnut plot using Vue.js 3 to a Django template
I want to display a Doughnut plot in a Django template using Vue.js 3. The Doughnut plot will be a component because I need to reuse this plot a lot. So far I have managed to create a simple text component in this way: base.html <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script> {% block vue %} {% endblock %} status.html {% extends "../base.html" %} {% load static %} <doughnut-plot title={{title}}></doughnut-plot> {% block vue %} <script type="module" src="{% static 'js/status.js' %}"></script> {% endblock %} status.js import DoughnutPlot from "./components/doughnut_plot.js" const app_status = Vue.createApp({ components: { DoughnutPlot, } }); app_status.mount("#app_status"); doughnut_plot.js export default { props: ['title'], template: `<h4>{{title}}</h4>` }; This code show the correct title that I pass with the context in the corresponding view. However, I cannot manage to change doughnut_plot.js into a plot. I tried the following: status.html % block vue %} <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Include Vue Chart.js wrapper --> <script src="https://cdn.jsdelivr.net/npm/vue-chartjs@3"></script> <!-- Include your Vue component script --> <script type="module" src="{% static 'js/components/doughnut_plot.js' %}"></script> <script type="module" src="{% static 'js/status.js' %}"></script> {% endblock %} doughnut-plot.js import { Doughnut } from 'vue-chartjs'; export default { extends: Doughnut, props: ['data', 'options'], mounted() { this.renderChart(this.data, this.options); } }; But I get the error Uncaught TypeError: Failed to resolve … -
Method Not Allowed Error when calling an existing endpoint
I get this error: Method Not Allowed: /api/v1/auth/users/student/submission/ "POST /api/v1/auth/users/student/submission/ HTTP/1.1" 405 41 when accessing the endpoint to one of my Django apps modelviewset (Submission). Below is the setup; views class SubmissionViewSet(viewsets.ModelViewSet): serializer_class = SubmissionSerializer queryset = Submission.objects.all().order_by("-created_at") permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(student=self.request.user) URLs router = routers.DefaultRouter() router.register("admin/courses", views.AdminCourseViewSet) router.register("student/courses", views.StudentCourseViewSet) router.register("student/submission", views.SubmissionViewSet) urlpatterns = [ path("users/", include(router.urls)), ] Serializer class SubmissionSerializer(serializers.ModelSerializer): project = serializers.UUIDField() course = serializers.SerializerMethodField() date_submitted = serializers.SerializerMethodField() class Meta: model = Submission fields = [ "id", "project", "course", "submission_link", "status", "date_submitted", "student_comments", "mentor_comments", ] read_only_fields = ["course", "status"] def get_course(self, instance): return instance.project.course.title def get_date_submitted(self, instance): return instance.date_submitted.strftime("%b %d, %Y") Models class Submission(TimeStampedUUIDModel): class STATUS(models.TextChoices): """ Choices for the project """ REVIEWED = "Reviewed", _("Reviewed") PENDING = "Pending", _("Pending") NOT_SUBMITTED = "Not_Submitted", _("Not_Submitted") student = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) submission_link = models.URLField() status = models.CharField( verbose_name=_("Project Review Status"), choices=STATUS.choices, default=STATUS.NOT_SUBMITTED, max_length=20) date_submitted = models.DateTimeField(default=timezone.now) student_comments = models.TextField(blank=True, null=True, default="") mentor_comments = models.TextField(blank=True, null=True, default="") def __str__(self): return f"{self.student.first_name} {self.student.last_name} {self.project.project_title} submission." I want to understand what I am doing wrong as I have exhausted all possibilities to get it work. django version: 4.1.13 django-rest-framework: 3.14.0 -
Incorrect vps nginx redirect settings for django app
I use vps, ubuntu 20, nginx, gunicorn for run django project. <my_ip>:3000 runs react app, <my_ip>:8000 runs django app. I want run <my_ip> react (frontend), <my_ip>/api/ django (backend) sudo nano /etc/nginx/sites-available/default/: root /home/ubuntu/clinent/build; server { listen 80; server_name <my_ip>; access_log /var/log/nginx/example.log; location /media/ { root /home/ubuntu/api; expires 30d; } location /static/ { root /home/ubuntu/api; expires 30d; } location /api/ { rewrite /api/(.*) /$1 break; proxy_pass http://<my_api>: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; } location / { try files $uri $uri /index.html } } Frontend, backend works fine, static and media works fine. But when I get into api/admin page, all my hrefs still point to root directory. For example, when I press to "orders" href I-ve got link to Orders I want get "/api/admin/orders/" I think about /admin/ redirect, but is it correct decision? I see a lot of not found errors in gunicorn logs because of incorrect links. Can I fix it with nginx? Or in django settings? -
Access to fetch at 'http://127.0.0.1:8000/api/movie/1' from origin 'http://localhost:3000' has been blocked by CORS policy
Every thing is normal but its not working, I have followed https://pypi.org/project/django-cors-headers/,https://github.com/adamchainz/django-cors-headers these documentation but its not working for me after that I have tried every possible solution available but its not working. Can anyone tell me what is wrong in this why it is not working. this is settings file of my project from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', "rest_framework", "cinemagic", ] 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', ] ROOT_URLCONF = 'cinemagic_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cinemagic_backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': "cinemagic", } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
The current path, login/accounts/login/, didn’t match any of these
I'm trying to make a login application, however whenever I try to log in using my template it gives this error.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' urls.py from django.urls import path from .views import login urlpatterns = [ path('', login), path('login/', login, name="login"), ] views.py from django.shortcuts import render from django.contrib.auth import authenticate from django.http.response import HttpResponse from CRUDfuncionario.models import Funcionario # Create your views here. def login(request): if request.method == "GET": return render(request,'login.html') else: idFuncionario = request.POST.get("idFuncionario") senha = request.POST.get("senha") user = Funcionario.objects.filter(idFuncionario=idFuncionario, senha=senha) if user: return HttpResponse('autenticado') else: return HttpResponse('Email ou senha invalidos') login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form action= "{% url 'login' %}" method="POST"> {% csrf_token %} <input type="text" placeholder="Identificação" name="idFuncionario"> <br> <input type="text" placeholder="Senha" name="senha"> <br> <button type="submit">Login</button> </form> </body> </html> apps.py from django.apps import AppConfig class LoginConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'login' settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent X_FRAME_OPTIONS = 'SAMEORIGIN' # 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 = 'django-insecure-2$2#kr-+3(*k46w+*+r-ij5@=bhhzuee$o57%@3rgfofo%ek&(' # SECURITY WARNING: don't run with debug turned on in … -
data not sent by AJAX to Django view
register.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="{% static 'jquery.min.js' %}"></script> <link rel="stylesheet" href="{% static 'all.css' %}" /> <title>Customer Registration</title> <style> body { font-family:Verdana, Geneva, Tahoma, sans-serif, 'Arial', sans-serif;s margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } #cr{ color: #f8f8f8; } #registration-container { display: flex; flex-direction: column; align-items: center; gap: 15px; width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 8px; background-color: #fff; box-shadow: 0 0 10px rgba(110, 1, 1, 0.1); } .maindiv { gap: 15px; padding: 10px; background-color: rgb(40, 6, 6); opacity: 1; /* Set the opacity to 60% */ display: flex; flex-direction: column; align-items: center; } input { padding: 10px; width: 100%; box-sizing: border-box; margin-bottom: 10px; } input[type="submit"] { cursor: pointer; background-color: #2ecc71; color: #fff; border: none; border-radius: 8px; transition: background-color 0.3s ease; } input[type="submit"]:hover { background-color: #27ae60; } </style> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">HOME</a></li> <li><a href="{% url 'Registration' %}">REGISTRATION</a></li> <li><a href="{% url 'Entry' %}">LOGIN</a></li> </ul> </nav> </header> <div class="maindiv"> <h1 id="cr">Customer Registration</h1> <div id="registration-container"> <form method="POST" id="someForm"> {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" … -
Deploy Django on WHM and Cent7
This is my issue: I am using bluehost VPS & WHM plan, and VPS Cent7 to deploy my django project which was created by python 3.11 and django v.4, I have installed python 3.11 and sqlite 3 successfully on Cent7, everything is working but when try to run this command " python 3.11 manage.py runserver 8000 ", I get this error Python 3.11.X ModuleNotFoundError: No module named '_sqlite3' Please help me to solve this problem, thanks -
How to fix Internal Server Error for Django deployment on Heroku
I am facing an issue on deployment of the website using django and heroku the image in production als on build logs it seems okay , i think is something with secret key or anything else ? -
Django. DJ_REST_AUTH redirects to login page after email confirmation
As I want my app to be REST app I don't want users to be redirected to login page after successful email confirmation. I use following: settings: ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_CONFIRM_EMAIL_ON_GET = True installed apps: APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' 'allauth', 'allauth.account', 'allauth.socialaccount', "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "dj_rest_auth.registration", 'accounts', ] and urls: from django.urls import path, include from dj_rest_auth.registration.views import VerifyEmailView, ConfirmEmailView urlpatterns = [ path("", include("dj_rest_auth.urls")), path( 'signup/account-confirm-email/<str:key>/', ConfirmEmailView.as_view(), name="account_confirm_email", ), path("signup/", include("dj_rest_auth.registration.urls")), path('signup/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), ] The registration works, I get an email with a link to confirm. I click and it redirects me to login page which as it is REST doesn't exists. I belive that it is allauth responsible for this redirection as I haven't found any settings in dj_rest_auth What I can see in the logs is just: Not Found: /accounts/login/ I expect there to be some way to redirect to page that informs about the result of verification but I can't find anything in the documentation. Do I need to make my own ConfirmEmailView doesn't redirects but returns page with the result? -
DTL tags are not working inside the template script
I am working on a django web application and I need to create a pie graph on dashboard page. I decided to use chart js for this. For some reason when I try to use DTL inside the script inside the template, every piece of DTL has a red line underneath(error ofc). I have no idea how to solve this. Solving the issue with the DTL meaning it's working <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> var ctx = document.getElementById('expenseChart').getContext('2d'); // Prepare data using Django template language var data = { labels: [ {% for expense in expenses_by_type %} "{{ expense.place_type }}"{% if not forloop.last %}, {% endif %} {% endfor %} ], datasets: [{ data: [ {% for expense in expenses_by_type %} {{ expense.total_amount }}{% if not forloop.last %}, {% endif %} {% endfor %} ], backgroundColor: [ 'rgba(255, 99, 132, 0.7)', 'rgba(255, 159, 64, 0.7)', // ... add more colors as needed ], }] }; var myPieChart = new Chart(ctx, { type: 'pie', data: data, }); </script> Here in this script, every DTL part is an error -
Double request logged from node request to Django endpoint
I'm trying to send a POST request to a django endpoint. It fails due to a 405. Inspecting the logs, it appears to receive the POST request, but then immediately followed by a GET request and returns a 405 as this is a POST only endpoint. I've stripped the fetching code back to the following js script: const fetchData = async() => { const response = await fetch("http://localhost:8000/api/auth/user", { method: "POST", body: { test: "test", }, headers: { "Content-Type": "application/x-www-form-urlencoded", }, }); if (!response.ok) { const text = await response.text(); console.log("error", response, text); } const json = await response.json(); console.log("json", json); }; fetchData(); It doesn't seem to matter what endpoint, or what method I send, it always logs a double request. What's also interesting, is if I send a PUT request, it logs a double PUT request, same for GET or even OPTIONS. However, for all POST requests, the second requests is always a GET. Again, it doesn't matter what endpoint I hit! I'm stumped I'm a JS dev, but I have access to the Django code if it would help to post the urls.py or any of the views from there? -
Error connection to server at "localhost", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
I'm trying to build API(with FastAPI) using python. I have installed python on windows WSL(ubuntu) and I have postgress on Windows. Now I'm trying to connect to Postgresssql via python code like below. but the connection is failing with Connection refused error code: try: conn = psycopg2.connect(host='localhost',database='fastapi',password='xxxx',cursor_factory=RealDictCursor) cursor = conn.cursor() print("Database connection was successfull") except Exception as error: print("Connetion to database has failed") print("Error", error) Error Connetion to database has failed Error connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I have gone through below link from from Stackoverflow but luck, can you please advice what could be the issue. How to connect to windows postgres Database from WSL Steps followed from the above link Add Windows Firewall Inbound Port Rule for WSL2 IP Addresses: Open Windows Defender Firewall with Advanced Security Click New Rule... Select Port for rule type Select TCP and for Specific local ports enter 5432 Select Allow the connection. Connecting from WSL2 won't be secure so don't select the secure option Select at least Public. Can select Domain and Private as well. I could only connect if Public was selected Name the … -
React - Django Rest Framework - Nested Form Items
I have a react form with an nested array of items. When i try to submit the form via DRF i receive a 400 status error detailing that the Item, Delivery Date, Description and Quantity fields are required. The models are setup so that i have a separate model for for the MaterialRequsitions and MeterialRequsitionItems On Submit Function (frontend) onSubmit={(values, { setSubmitting }) => { const formData = new FormData(); console.log('Material Requsition Form Values:', values); // Object.keys(values).forEach((key) => { // if ( key !== 'upload_documents' ){ // formData.append(key, values[key]); // } // }); formData.append('project', values.project); formData.append('title', values.title); formData.append('buyer', values.buyer); formData.append('date', values.date); formData.append('requested_by', values.requested_by); // values.items.forEach((item, index) => { // // Convert each item object to JSON string // formData.append(`items[${index}]`, (item)); // }); values.items.forEach((item, index) => { Object.keys(item).forEach(key => { formData.append(`items[${index}].${key}`, item[key]); }); }); // values.items.forEach((item, index) => { // Object.keys(item).forEach(key => { // formData.append(`items.${index}.${key}`, item.item); // }); // }); formData.append('user', userId); console.log(Array.from(formData.entries())); const uploadedFiles = uppy.getFiles(); uploadedFiles.forEach((file, index) => { console.log(`File ${index}: `, file); formData.append(`upload_documents[${index}]`, file.data, file.name); }); console.log('Form Data:', values); console.log(Array.from(formData.entries())); dispatch(addMaterialRequsition(formData)) .unwrap() .then((result) => { console.log('Material Requsition Added Sucessfully:', result); alert('Material Requsition Added Sucessfully'); onClose(); }) .catch((error) => { console.log('Failed to add Material Requsition:', error); }) .finally(() => … -
Django Custom Authentication Not Authenticating Users
I have a Django website, what I want is there to be separate user bases, one is User and another is Agent. Now Agent model does not extend the CustomUser Model. So that Agents can register themselves without being registered as a User first. When I register my Agents through AgentRegister form, my Agent passwords are being hashed properly which I can see in my Admin panel. Now the problem is, even when I enter correct Agent credentials in my AgentSignIn form, I can't log in as an Agent as it says "Please enter a correct username and password. Note that both fields may be case-sensitive." Same things happens when I enter correct User credentials into UserSignIn form. I can't sign in and it says "Please enter a correct username and password. Note that both fields may be case-sensitive." Note that both fields may be case-sensitive." How do I fix this? Neither login is working properly. My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') class Profile(models.Model): user = … -
How can I restrict the access to /admin only to staff users
I have admin site like this, urlpatterns = [ path('', include('defapp.urls')), path('admin/', admin.site.urls), I want to restrict the access only to the staff user. I tryied to do like this, from django.contrib.admin.views.decorators import staff_member_required urlpatterns = [ path('', include('defapp.urls')), path('admin/', staff_member_required(admin.site.urls)), However this shows the error 'tuple' object is not callable -
Django sum two columns with conditions using mysql raw query and render value to template
Please I need assistance on how to use Django to sum two columns with conditions using mysql raw query. Am just a newbie I need somtin select sum(amt), sum(qty) from table where transid=7 How can I use Django raw mysql query to solve it -
How can I setup a "can visit the link once and only once" kind of permission for my links in django?
I am creating a game webapp using on HTML CSS and Django. There is no JS involved so far because I dont know JS well enough to implement it in my app. I am not a webdeveloper either. I just know python and basic web design. Now to my issue: I have setup various tasks in different levels of the game. the user can visit these task to play them. But they should not be allowed to visit these tasks again after they've played it once. I was think of disabling the link after visiting once. Or maybe lock the link and make it unaccessable after visiting it one time and only be able to unlock it through the admin panel with a toggle or something. These are the ideas I have but don't know how to code. How can I implement this in django. I am also open to solutions on the front end with JS. Is this a case for django permissions or is it something else?. an image of the the levels dashboard I have tried targeting links using :visited pseudo class but not what I wanted. -
Creating a simple Many to Many seeding using Django Seed library
I am facing problem while creating a seeding for my Election and ElectionCandidate models in my Django project using Django-seed library. This is what I am trying to election3 = Election.objects.get(id=3) positions = Position.objects.all() random_position = random.choice(positions) # Seed the ElectionCandidate model # Seed the ElectionCandidate model with the related CandidatePosition model seeder.add_entity(ElectionCandidate, number, { 'first_name': lambda x: seeder.faker.first_name(), 'last_name': lambda x: seeder.faker.last_name(), 'biography': lambda x: seeder.faker.text(), 'date_of_birth': lambda x: seeder.faker.date_of_birth(), 'email': lambda x: seeder.faker.email(), 'contact_number': lambda x: seeder.faker.phone_number(), 'address': lambda x: seeder.faker.address(), 'image': None, 'is_incumbent': lambda x: seeder.faker.boolean(chance_of_getting_true=20), }) # Execute the seeding operation for ElectionCandidate inserted_pks = seeder.execute() election_candidate_ids = inserted_pks[ElectionCandidate] #add candidate posisitons to ElectionCandidates via positions.set method for election_candidate_id in election_candidate_ids: election_candidate = ElectionCandidate.objects.get(id=election_candidate_id) CandidatePosition.objects.create(election_candidate=election_candidate, position=random_position,election=election3) election_candidate.positions.set([random_position]) #election3.positions.set([random_position]) candidate_positions = CandidatePosition.objects.filter(election=election3) positions_for_candidate = [cp.position for cp in candidate_positions] election3.positions.set(positions_for_candidate) and Here are my relationships from django.utils import timezone from django.db import models from django.utils.timezone import localdate # from Candidate.models import ElectionCandidate class Position(models.Model): position_code = models.CharField(max_length=4, unique=True) position_name = models.CharField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.position_name # Create your models here. class Election(models.Model): election_type = models.CharField(max_length=20) election_date = models.DateField() title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) positions = models.ManyToManyField(Position, … -
Supervisor cannot start Gunicorn: ENOENT, problems with static files
Помогите, пожалуйста, возникли проблемы при деплое проекта на django (версия 4.2.1) с помощью gunicorn, nginx, supervisor Структура каталогов проекта: enter image description here enter image description here. Конфигурационные файлы для gunicorn и supervisor:enter image description here enter image description here supervisor выдаёт ошибку: supervisor: couldn't exec /root/workout/venv/bin/gunicorn: ENOENT supervisor: child process was not spawned Однако командой gunicorn myworkout.wsgi -b 172.18.0.1:8000 сайт запускается, но не загружаются статические файлы, ошибка: enter image description here В свою очередь, конфигурационный файл для nginx /etc/nginx/sites-available/default: enter image description here. Админка так же не закрывается... Подступалась к проблеме с разных сторон, проверила все пути, прописывала их по-разному, в конфигурационном файле nginx прописан include /etc/nginx/mime.types; -
Can create extended Field classes for Django Models introduce unexpected problems?
I'm starting a Django project and in my early design I'm thinking about extending the model's fields classes to add a new optional attribute belongs_to. It will be a list of elements that later would serve the purpose of filtering the object attributes. Example: # models.py class CustomCharField(models.CharField): def __init__(self, belongs_to: list=list(), *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.belongs_to = belongs_to class ModeloTest(models.Model): attr1 = CustomCharField(max_length=20, belongs_to=list(('type1', 'type2'))) attr2 = CustomCharField(max_length=10) attr3 = CustomCharField(max_length=10, belongs_to=list(('type1',))) attr4 = CustomCharField(max_length=10, belongs_to=list(('type2', 'type3'))) attr5 = CustomCharField(max_length=10, belongs_to=list(('type4'))) attr6 = CustomCharField(max_length=10, belongs_to=list(('type3',))) def fields_belongs_to(self, search_element): # 'id' Field is not Custom, doesn't have or need 'belongs_to' and can be ignored fields = [field for field in self._meta.fields if field.name != 'id'] filtered_fields = [field for field in fields if search_element in field.belongs_to] output = dict() for field in filtered_fields: output[field.name] = getattr(self, field.name) return output # views.py def main_view(request): m = ModeloTest.objects.first() context = { 'type1': m.fields_belongs_to('type1'), } return render(request, 'placeholder/main.html', context) With this design I can organize and classify fields in the Model and with the object.fields_belongs_to(search_element) method I get a dict of the Fields that belong to the type selected in search_element. If in the future I add a new … -
Problem loading image in user-uploaded images in Profile page
I am a beginner to Django (version = 5.0) and I have issue in viewing user-uploaded content on their profile page that is being rendered on HTML. I have installed Pillow library properly and I tried all methods but I can't seem to understand what the issue seems to be. views.py @login_required def user_profile(request): return render(request, "register_user/profile.html") urls.py from django.urls import path from register_user import views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static # url patterns app_name = 'register_user' urlpatterns = [ path("", views.index, name="register-index"), path("signup/", views.userRegister, name="register-user"), path("login/", auth_views.LoginView.as_view(template_name='register_user/login.html'), name="login"), # path("login/", views.login_user ,name="login"), path("profile/", views.user_profile, name="profile"), path("logout/", views.logout_user, name="logout"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = "default.jpg", upload_to='profile_pics') def __str__(self) -> str: return f"{self.user.username} Profile" settings.py STATIC_DIR = BASE_DIR / 'static' STATIC_URL = "static/" STATICFILES_DIRS = [STATIC_DIR,] # MEDIA MEDIA_ROOT = BASE_DIR / "media" MEDIA_URL = "media/" profile.html {% block content_block %} <div class="card border-light mb-3" > <img src="{{ user.profile.image.url }}" alt="Card image cap"> <div class="card-header">Username ~ {{ user.username }}</div> <div class="card-body"> <h5 class="card-title">{{user.first_name}} {{user.last_name}}</h5> …